I want to create a Chrome extension to get the background image of an HTML element so I added an option in the right-click menu. It worked in Manifest v2 but when I tried to update to Manifest v3 my code did not longer worked. Is there a thing I missed?
Here is my manifest.json
:
{
"description": "Get background image of an HTML element",
"manifest_version": 2,
"name": "BackgroundImage get",
"version": "0.0.0.1",
"homepage_url": "https://www.example.com",
"icons": {
"48": "icons/icon48.png"
},
"background": {
"scripts": ["background.js"]
},
"permissions": [
"activeTab",
"contextMenus"
],
"browser_action": {
"default_icon": {
"16": "icons/icon16.png",
"32": "icons/icon32.png",
"48": "icons/icon48.png",
"128": "icons/icon128.png"
}
}
}
And here is my background.js
file:
chrome.contextMenus.create({
title: 'Get Background Image',
onclick: function(e){
console.log("Example action")
}
}, function(){})
I tried to edit my manifest.json
like that:
{
"manifest_version": 3,
"name": "BackgroundImage get",
"description": "Get background image of an HTML element",
"version": "0.0.1",
"icons": {
"16": "icons/icon16.png",
"32": "icons/icon32.png",
"48": "icons/icon48.png",
"128": "icons/icon128.png"
},
"action": {
"default_title": "Background Image",
"default_popup": "popup.html"
},
"permissions": [
"contextMenus"
],
"background": {
"service_worker": "background.js"
}
}
But that doesn't work.
Please check the error output in DevTools of Service Worker.
Unchecked runtime.lastError: Extensions using event pages or Service Workers must pass an id parameter to chrome.contextMenus.create
Fixing this error prints the following error:
Unchecked runtime.lastError: Extensions using event pages or Service Workers cannot pass an onclick parameter to chrome.contextMenus.create. Instead, use the chrome.contextMenus.onClicked event.
Fix this error and your extension will work correctly.
background.js
chrome.runtime.onInstalled.addListener(() => {
chrome.contextMenus.create({
id: 'hoge',
title: 'Get Background Image',
});
});
chrome.contextMenus.onClicked.addListener((info) => {
console.log("Example action")
});