Capture text selection in Google Docs
Asked Answered
K

3

16

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

manifest.json

{
  "manifest_version": 2,

  "name": "Selection Extension",
  "description": "Search your selected text",
  "version": "1.0",
  "permissions": [
    "tabs",
    "http://*/*",
    "https://*/*"
  ],
  "background": {
    "scripts": [
      "background.js"
    ],
    "persistent": false
  },
  "browser_action": {
    "default_icon": "icon.png",
    "default_title": "Mark it!!"
  },
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content_script.js"]
    }
  ]

content_script.js

chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.method == "getSelection") {
        sendResponse({data: window.getSelection().toString()});
    } else {
        sendResponse({});
    }
});

background.js

function initBackground() {

    chrome.browserAction.onClicked.addListener(function(tab) {
        chrome.tabs.sendMessage(tab.id, {method: "getSelection"}, function(response){
            sendServiceRequest(response.data);
        });
    });
}

function sendServiceRequest(selectedText) {
    var serviceCall = 'http://www.google.com/search?q=' + selectedText;
    chrome.tabs.create({url: serviceCall});
}

initBackground();

This code works for selection in webpages (such as Gmail, Facebook, news.) I also want to be able to get the selection in PDF, and Google Docs (viewed in the browser). In these cases: window.getSelection returns an empty string...

Someone knows how to do it?

Kaminski answered 1/1, 2017 at 21:22 Comment(5)
Thanks you for this! I'll remove the executeScript.Kaminski
For google-docs there's an HTML elements with class "kix-selection-overlay". This class is the actual div that creates the selection look (i.e. teal background). But it's not connected in anyway to the div that contains the text...Malagasy
Regarding PDF: #15527595Malagasy
@Makyen in such case minimal, complete and verifiable example is the only window.getSelection().toString().Hutcheson
This video tutorial does pretty much exactly what you are tempting.Foist
R
11

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);
Rosenzweig answered 10/3, 2017 at 16:3 Comment(1)
Can you please share exact code snipped - only for getting selected text?Hutcheson
P
2

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);
});
Piggery answered 27/11, 2017 at 21:55 Comment(3)
Thank you but this approach is blocked for Google Docs - instead of the context menu of the browser user see the context menu of Google Docs.Hutcheson
If you'd like you can add a Google docs menu item that disables the Google docs menu. I.e. disable this menu and allow native.Piggery
Add the "contextMenus" permission to manifest.json before doing thisMillepore
L
0

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:

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

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);
}
Lacustrine answered 24/12, 2020 at 16:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.