Reputation: 51
I am trying to trigger a block of code every time the user selects/highlights some text on any of the tabs.
I am able to run the javascript when I highlight some text and then click on my extension. I have already read some of the chrome apis but none of them seem to work. https://developer.chrome.com/extensions/api_index
chrome.browserAction.onClicked.addListener(function() {
alert(window.getSelection().toString());
});
I am not able to run the code as soon as I highlight some text. Is there an API that already handles that?
Upvotes: 5
Views: 2364
Reputation: 165
You should just add a buffer:
As you are talking about selections from any tab, You should use the storage api and refer the tab id for further use.
document.onmouseup = function() {
chrome.tabs.getCurrent(function(_tabId){
if(_tabId){
var _SELECTION = {};
_SELECTION[tabId] = window.getSelection().toString();
chrome.storage.local.set(_SELECTION, function() {
console.log('Selection saved: ', _SELECTION[tabId]);
});
}
});
}
chrome.browserAction.onClicked.addListener(function() {
chrome.tabs.getCurrent(function(_tabId){
if(_tabId){
chrome.storage.local.get(_tabId, function(result) {
alert('Selection restored: ' + result[tabId].txt);
});
}
});
});
Don't forget to update your manifest.json to set the according permissions
{
...
"permissions": [
"storage",
"tabs"
],
...
}
Upvotes: 1