Capture text selection in Google Docs

前端 未结 3 1514
谎友^
谎友^ 2021-01-07 22:28

I\'m writing a Chrome extension that captures the user text selection and sends the selected text to Google search.

manifest.json

{
         


        
相关标签:
3条回答
  • 2021-01-07 23:07

    Google Docs document does not really follow the normal ways of how a to access text on from a Extension. I have for this reason created a tool to work with Google Docs, which can be found here

    This should enable you to:

    //contentScript.js
    var googleDocument = googleDocsUtil.getGoogleDocument();
    console.log("The selected text is: " + googleDocument.selectedText);
    
    0 讨论(0)
  • 2021-01-07 23:11

    You can get this from the context menu. I bet you'll be adding a context menu item anyway.

    chrome.contextMenus.create({
       id:"g-search",
       title:"Search %s",
       contexts:["selection"]
    });
    
    chrome.contextMenus.onClicked.addListener(function(sel){
       console.log(sel.selectionText);
    });
    
    0 讨论(0)
  • 2021-01-07 23:11

    Thanks to Mr. Java Wolf answer.

    I created a fork of his project, and then rewrite his project completely to adopt it for my own needs. Core concepts were keeped, but now it is easier to use because it supports both IIFE and CJS.

    So, here is google-docs-utils package:

    • GitHub - https://github.com/Amaimersion/google-docs-utils
    • NPM - https://www.npmjs.com/package/google-docs-utils

    You can use it with Node.js or directly in browser:

    • Node.js: npm install google-docs-utils
    • Browser: https://unpkg.com/google-docs-utils@latest/dist/iife/index.js

    Here is the code which solves your task using google-docs-utils package:

    const linesData = GoogleDocsUtils.getSelection();
    let selectionData = null;
    
    for (const lineData of linesData) {
        if (lineData) {
            selectionData = lineData;
    
            // we handle only single selection
            break;
        }
    }
    
    if (selectionData) {
        console.log(selectionData.selectedText);
    }
    
    0 讨论(0)
提交回复
热议问题