函数(事件)在一个Opera上下文菜单扩展

function(event) within an Opera context-menu extension

本文关键字:Opera 上下文 菜单 一个 扩展 事件 函数      更新时间:2023-09-26

我正在尝试为Opera编写一个简单的扩展。它增加了一个"搜索谷歌图像",当你右键单击图像,就像在Chrome。类似的扩展已经存在,但这是为了学习。

我的第一次尝试使用onClick,这是不正确的方式。我用这个答案重写了我的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)
        });
    }
});

谢谢你Bergi。