Karan Khurana
Karan Khurana

Reputation: 51

Google chrome extension - Is there a way to add a listener to text select/highlight event on any tab

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

Answers (1)

nab.
nab.

Reputation: 165

You should just add a buffer:

Store selection

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]);
            });
        }
    });
}

Use it when you click on your extension

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);
            });
        }

    });
});

Manifest

Don't forget to update your manifest.json to set the according permissions

{
    ...

    "permissions": [
        "storage",
        "tabs"
    ],

    ...
}

Note

  1. I used storage.local as the clipboard should be kept on the local machine, but if you want to share it cross-machines you can use storage.sync. More to read in the docs.
  2. I'd use contextMenus. It makes more sense if you highlight text to right-click and perform an action.

Upvotes: 1

Related Questions