似乎无法在 Chrome 扩展程序中触发 chrome.contextMenus.onClicked

apr*_*ion 3 google-chrome-extension

我正在尝试编写我的第一个浏览器扩展程序,但似乎无法通过单击上下文菜单项来触发单击处理程序。console.log 调用似乎没有向控制台输出任何内容,我尝试使用 alert() 以防万一“背景”脚本(不确定背景和内容脚本之间的区别究竟是什么),但是似乎也没有做任何事情。

当我在测试页面的输入中选择一些文本时,右键单击并选择加密或解密,没有任何反应;不在控制台或开发人员工具的网络选项卡中。我究竟做错了什么?

manefest.json:

{
    "manifest_version": 2,

    "name": "my name",
    "description": "my description",
    "version": "1.0",

    "background": {
        "scripts": ["jquery-3.2.1.min.js", "background.js"],
        "persistent": false
    },
    "content_scripts": [
        {
            "matches": ["http://*/*", "https://*/*"],
            "js": ["content_script.js"]
        }
    ],
    "permissions": [
        "activeTab",
        "contextMenus",
        "http://my.hostname.com/"
    ]
}
Run Code Online (Sandbox Code Playgroud)

背景.js:

/**
 * A handler which will run the analysis of the DOM element's selected text
 */
function clickHandler(info, tab) {
    "use strict";
    console.log(info);
    console.log(tab);
    // get selected text as encrypt/decrypt
    chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
        chrome.tabs.sendMessage(tabs[0].id, "get selection", null, function(selection) {
            var data = {
                "action": action,
                "selection": selection
            };
            var max_length = 4095;
            if (data.selection.length > max_length) {
                data.selection = data.selection.substring(0, max_length);
            }
            var url = "http://my.hostname.com/";
            jQuery.post(url, data, function (response) {
                chrome.tabs.sendMessage(tabs[0].id, response);
            }, "json");
        });
    });
}

/**
 * Create a context menu items to allow encode/decode
 */
chrome.runtime.onInstalled.addListener(function() {
    chrome.contextMenus.create({
        "id": "encrypt",
        "title": "Encrypt",
        "type": "normal",
        "contexts": ["editable"]
    });

    chrome.contextMenus.create({
        "id": "decrypt",
        "title": "Decrypt",
        "type": "normal",
        "contexts": ["selection"]
    });

    chrome.contextMenus.onClicked.addListener(clickHandler);
});
Run Code Online (Sandbox Code Playgroud)

Dan*_*err 7

您需要将 contextMenus.onClicked 移到 onInstalled 之外。

chrome.runtime.onInstalled.addListener(function() {
 //create context menus
})
chrome.contextMenus.onClicked.addListener(function() {
 //handle context menu actions
})
Run Code Online (Sandbox Code Playgroud)

“注册以在每次加载事件页面时接收您的扩展程序感兴趣的任何事件。事件页面将为您的扩展程序的每个新版本加载一次。之后,它只会被加载以传递您已注册的事件。这通常意味着你的事件监听器应该添加在事件页面的顶级范围,否则当事件页面重新加载时它们可能不可用。如果你在安装或升级扩展时需要做一些初始化,监听运行时.onInstalled 事件。这是注册 declarativeWebRequest 规则、contextMenu 条目和其他此类一次性初始化的好地方。”

https://developer.chrome.com/extensions/event_pages#best-practices