title: Capture text selection in Google Docs
body: <p>I'm writing a Chrome extension that captures the user text selection and sends the selected text to Google search.</p>
  
  <p><strong>manifest.json</strong></p>
  
  <pre><code>{
    "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": ["&lt;all_urls&gt;"],
        "js": ["content_script.js"]
      }
    ]
  </code></pre>
  
  <p><strong>content_script.js</strong></p>
  
  <pre><code>chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
      if (request.method == "getSelection") {
          sendResponse({data: window.getSelection().toString()});
      } else {
          sendResponse({});
      }
  });
  </code></pre>
  
  <p><strong>background.js</strong></p>
  
  <pre><code>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();
  </code></pre>
  
  <p>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: <code>window.getSelection</code> returns an empty string...</p>
  
  <p>Someone knows how to do it?</p>