How do I restrict context menus to appear only for certain selected text in a Chrome extension?

后端 未结 1 922
你的背包
你的背包 2021-02-06 08:04

I made a very simple chrome extension which allows users to highlight a DOI number, right-click and choose \"Resolve DOI\", and it sends them to the associated web page. Right n

1条回答
  •  借酒劲吻你
    2021-02-06 08:37

    You would need to control content menu creation from a content script. Dynamic menu creation/deletion should execute pretty fast and the delay will be unnoticeable for a user.

    • Add mousedown event listener in a content script and check there whether selection satisfies your pattern.
    • Based on whether or not selection matches the patterrn, send a request to a background page asking to create or delete the menu.

    Something along those lines (not tested):

    content_script.js:

    document.addEventListener("mousedown", function(event){
        var selection = window.getSelection().toString();
        if(selection.match(/^10\./)) {
            chrome.extension.sendRequest({cmd: "create_menu"});
        } else {
            chrome.extension.sendRequest({cmd: "delete_menu"});
        }
    }, true); 
    

    background.html:

    chrome.extension.onRequest.addListener(function(request) {
        if(request.cmd == "create_menu") {
            chrome.contextMenus.removeAll(function() {
                chrome.contextMenus.create({
                    "title" : "Resolve DOI",
                    "type" : "normal",
                    "contexts" : ["selection"],
                    "onclick" : getClickHandler()
                });
            });
        } else if(request.cmd == "delete_menu") {
            chrome.contextMenus.removeAll();
        }
    });
    

    0 讨论(0)
提交回复
热议问题