Chrome扩展:如何在使用manifest v3的HTML元素的右键菜单上添加一个选项?



我想创建一个Chrome扩展来获得HTML元素的背景图像,所以我在右键菜单中添加了一个选项。它在Manifest v2中工作,但当我试图更新到Manifest v3时,我的代码不再工作了。我错过什么了吗?

这是我的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"
}
}
}
这是我的background.js文件:
chrome.contextMenus.create({
title: 'Get Background Image',
onclick: function(e){
console.log("Example action")
}
}, function(){})

我试着这样编辑我的manifest.json:

{
"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"
}
}

但这行不通。

请检查Service Worker的DevTools中的错误输出。

不运行时。使用事件页或Service worker的扩展必须传递id参数给chrome. contextmenu .create

修复此错误将打印以下错误:

不运行时。使用事件页或Service worker的扩展不能将onclick参数传递给chrome. contextmenu .create。请使用chrome. contextmenu . onclicked事件。

修复此错误,您的扩展将正常工作。

background.js

chrome.runtime.onInstalled.addListener(() => {
chrome.contextMenus.create({
id: 'hoge',
title: 'Get Background Image',
});
});
chrome.contextMenus.onClicked.addListener((info) => {
console.log("Example action")
});

最新更新