How to correctly capture selected text into a variable in Google Chrome?

I am trying to create my first Chrome extension - a duplicate of the right mouse button for google search.

This is what I still have

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

chrome.contextMenus.create({
  "title": "mySearch",
  "contexts":["selection"],
  "onclick": searchGoogle
});

The problem is that the selected text is not written, and a query that is performed for any selected text http://www.google.com/search?q=.

What am I doing wrong here? Why window.getSelection().toString()doesn’t work?


After what Brian suggested, I tried this

var query;
function getText(ocd) {
   query = ocd.selectionText;
}

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

chrome.contextMenus.create({
  "title": "mySearch",
  "contexts":["selection"],
  "onclick": searchGoogle
});

but he is looking http://www.google.com/search?q=undefined

What have I done wrong?

+3
source share
1 answer

. Google OnClickData. , . , , , , , . ( ocd), , Google, ocd.*. ocd.selectionText.

, :

// Handle click event and store OnClickData object in first argument
function searchGoogle(ocd) {
  var serviceCall = 'http://www.google.com/search?q=' + ocd.selectionText;
  chrome.tabs.create({url: serviceCall});
}

chrome.contextMenus.create({
  "title": "mySearch %s", // display "MySearch [selected text]" in menu
  "contexts":["selection"],
  "onclick": searchGoogle // pass an OnClickData object to searchGoogle on click
});

, Google. , , , .. API chrome.*.

, window.getSelection().getString() script, ? , , , . , , , .

+4

All Articles