views:

427

answers:

2

I'm trying to write a Google chrome extension so that I can highlight text that appear on any website and perform at GET query search on another website. It will open the query in new tab.

For example if I highlight the text "google chrome" and right click to activate the chrome extension it will open http://example.com/index.php?q=google%20chrome in a new tab.

What the best way to go about doing this?

+1  A: 

If you simply want to open a new tab, you can use chrome.tabs.create() with a URL parameter. To get selected text, trap a mouseup event and get the selection using window.getSelection().

Max Shawabkeh
+2  A: 

To get the selected text from the tab your visiting, you would need to use Extension Messaging to do so.

For example, lets do a simple Google Search extension, in your content script you would have something like this:

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

Now assuming you want this to happen when you click on a browser action, within your background page, you would need to listen for the onclick event.

chrome.browserAction.onClicked.addListener(function(tab) {
  chrome.tabs.sendRequest(tab.id, {method: "getSelection"}, function(response) {
    var selectedText = response.data;
    chrome.tabs.create({url: 'http://google.com?q=' + selectedText});
  });
});

You would notice once you click on the icon (browser action), it will send a request to the content script, and once the content script receives that action, it will send the selected text back as its payload. You can then open a tab based on the selection to Google to search for the results.

Mohamed Mansour

related questions