Add contextmenu items to a Chrome extension's browser action button

前端 未结 3 849
执念已碎
执念已碎 2020-11-30 03:07

A G Chrome extension can have a \'browser action\'. Usually the ext developer displays the options when you click on it, meaning every action requires 2 clicks, even the def

3条回答
  •  余生分开走
    2020-11-30 03:49

    It is not possible to add any custom entries to the context menu.

    You can, however, dynamically assign a panel to the button with chrome.browserAction.setPopup. You can use an options page to allow the user to choose their preferred option (single-click action, or two-clicks & multiple actions). The fact that the options page is just two clicks away from the button is also quite nice.

    Here's sample code to illustrate the concept of toggling between panel and single-click.

    background.js (used in your event / background page):

    chrome.browserAction.onClicked.addListener(function() {
        // Only called when there's no popup.
        alert('Next time you will see a popup again.');
        chrome.browserAction.setPopup({
            popup: 'popup.html'
        });
    });
    

    popup.html, just for the demo (use CSS to make it look better):

    
    
    

    popup.js, just for the demo. JavaScript has to be placed in a separate file because of the CSP.

    document.querySelector('button').onclick = function() {
        chrome.browserAction.setPopup({
            popup: '' // Empty string = no popup
        });
        alert('Next time, you will not see the popup.');
        // Close panel
        window.close();
    };
    

    As you can see in this example, the chrome.browserAction.setPopup is also available in a popup page.

    PS. manifest.json, so you can copy-paste the example and play with this answer.

    {
        "name": "Test badge - minimal example",
        "version": "1",
        "manifest_version": 2,
        "background": {
            "scripts": ["background.js"]
        },
        "browser_action": {
            "default_title": "Some tooltip"
        }
    }
    

提交回复
热议问题