Opera 上下文菜单扩展中的函数(事件)

function(event) within an Opera context-menu extension

我正在尝试为 Opera 编写一个简单的扩展。当您右键单击图像时,它会添加一个 "Search Google for image",就像在 Chrome 中一样。类似的扩展已经存在,但这是为了学习。

我第一次尝试使用onClick,这不是正确的方法。我用 this answer 重写了我的 bg.js 文件。现在看起来像这样:

chrome.runtime.onInstalled.addListener(function() {
    chrome.contextMenus.create({
        title: "Search Google for image",
        id: "gsearch",
        contexts: ["image"]
    });
});

chrome.contextMenus.onClicked.addListener(function(info, tab) {
    if (info.menuItemId === "gsearch") {
        function(event) {
            chrome.tabs.create({
                url: "https://www.google.com/searchbyimage?image_url=" + encodeURIComponent(event.srcUrl);
            });
        }
    }
});

当我加载扩展时,Opera 抱怨第 11 行 function(event) { 导致错误消息 Unexpected token (。我显然 在这里遗漏了一些关于语法的东西 ,非常感谢你的专业知识。

不能在 if 块内声明函数。此外,info 可以传递给 encodeURIComponent。以下代码有效:

chrome.runtime.onInstalled.addListener(function() {
    chrome.contextMenus.create({
        title: "Search Google for image",
        id: "gsearch",
        contexts: ["image"]
    });
});
chrome.contextMenus.onClicked.addListener(function(info, tab) {
    if (info.menuItemId === "gsearch") {
        chrome.tabs.create({
            url: "https://www.google.com/searchbyimage?image_url=" + encodeURIComponent(info.srcUrl)
        });
    }
});

谢谢伯吉。