function(event) within an Opera context-menu extension

时间:2016-08-31 18:30:00

标签: javascript syntax opera

I am trying to write a simple extension for Opera. It adds a "Search Google for image" when you right-click on an image, just like in Chrome. Similar extensions already exist, but this is for the sake of learning.

My first attempt used onClick, which is not the correct way. I used this answer to rewrite my bg.js file. It now looks like this:

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);
            });
        }
    }
});

When I load the extension, Opera complains about line 11 where function(event) { causes the error message Unexpected token (. I am obviously missing something regarding syntax here, and would appreciate your expertise.

1 个答案:

答案 0 :(得分:0)

无法在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。

相关问题