Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capture text selection in Google Docs

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?

like image 809
Noam antebi Avatar asked Jan 01 '17 21:01

Noam antebi


2 Answers

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);
like image 131
Mr. Java Wolf Avatar answered Sep 21 '22 20:09

Mr. Java Wolf


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);
});
like image 25
N-ate Avatar answered Sep 20 '22 20:09

N-ate