I am trying to create my first Chrome extension – a duplicate of the right-click google search option.
This is what I have so far
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 being captured, and the query that executes on any selected text is http://www.google.com/search?q=.
What am I doing wrong here? Why does window.getSelection().toString() not work?
After what Bryan 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 it searches for http://www.google.com/search?q=undefined
What did I do wrong?
See Google’s reference on the OnClickData object. When you click on your context menu item, it will send one of those as the first argument to the specified function. So, first of all, you probably want to add a variable to hold it. Once you have that variable (here
ocd) you can access the properties listed by Google withocd.*. In this case, we wantocd.selectionText.Most likely, you’ll need to make the following change:
Since you’re just starting out, I’ll heavily recommend looking to Google’s Developer’s Guide. It usually has what you need in terms of which methods are available, what values they return, etc. for all of their custom
chrome.*APIs.Also,
window.getSelection().getString()is being called from your background script, right? It actually does work, but it works by returning whatever text you’ve selected on your background page. Since you usually can’t interact with your extension’s background page, that’s probably a blank string.