For the Google Chrome extension, I need to capture selected text in a web page and send to a web service. I'm stuck!
First I tried a bookmarklet, but Chrome on Mac seems to have some bookmarklet bugs so I decided to write an extension.
I use this code in my ext:
function getSelText(){ var txt = 'nothing'; if (window.getSelection){ txt = "1" + window.getSelection(); } else if (document.getSelection) { txt = "2" + document.getSelection(); } else if (document.selection) { txt = "3" + document.selection.createRange().text; } else txt = "wtf"; return txt; } var selection = getSelText(); alert("selection = " + selection);
When I click on my extension icon, I get a "1". So I think the act of selecting outside the browser window is causing the text to not be seen by the browser as "selected" any more.
Just a theory....
thoughts?
To use the “Copy Link to Text” feature, open a site and select the text that you want to copy a link for using your mouse or keyboard. Next, right-click the highlighted text and select “Copy Link to Highlight” from the menu. Chrome will copy the link for your selected text to your clipboard.
You can do this by using Extensions Messaging. Basically, your "background page" will send the request to your service. For example, lets say you have a "popup" and once you click on it, it will do a "Google search" which is your service.
In your content script, we need to listen for a request coming from your extension, so that we send it the selected text:
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) { if (request.method == "getSelection") sendResponse({data: window.getSelection().toString()}); else sendResponse({}); // snub them. });
Now in background page you can handle the popup onclick event so that we know we clicked on the popup. Once we clicked on it, the callback fires, and then we can send a request to the content script using "Messaging" to fetch the selected text.
chrome.browserAction.onClicked.addListener(function(tab) { chrome.tabs.sendRequest(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}); }
As you have seen, I registered a listener in a content script to allow my extension to send and receive messages from it. Then once I received a message, I handle it by searching for Google.
Hopefully, you can use what I explained above and apply it to your scenario. I just have to warn you that the code written above is not tested, so their might be spelling, or syntax errors. But those can easily be found by looking at your Inspector :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With