简体   繁体   中英

Update Context Menu with right-click selection

I have some code that updates a context menu when a selection is made. My content code is:

document.addEventListener('selectionchange', function() {
    var selection = window.getSelection().toString().trim();
    chrome.runtime.sendMessage({
        request: 'selectionChanged',
        selection: selection
    });
});

and the background code catches the message and updates the context menu.

This works fine if I select text by using the left-mouse button (drag to highlight, double click, etc) and then bringing up the context menu, but does not work if I right-click on a word that is not already highlighted. From what I can tell the problem is that the context menu is brought up before the selection change message is handled and the menu updated.

How can I update the context menu with the right-click selection before the menu is displayed?

Simply have an interval running and checking for a change in the selection using window.getSelection().toString().trim() instead.

Here's a rough example of what I mean:

var selection="";
setInterval(function(){
    if(selection!=window.getSelection().toString().trim()){
        selection=window.getSelection().toString().trim();
        chrome.runtime.sendMessage({
            request: 'selectionChanged',
            selection: selection
        });
    }
},500);

optionally you could do what this guy suggested: Javascript: How to detect if a word is highlighted

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM