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.
A function cannot be declared inside an if
block. Furthermore, info
can be passed to encodeURIComponent
. The following code works:
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)
});
}
});
Thank you Bergi.