【发布时间】:2021-07-18 19:04:48
【问题描述】:
我正在尝试显示从 Manifest v3 中的 background.js 在我的浏览器中弹出的警报。但是,使用 Manifest v3 页面中描述的代码实现不会产生警报。
Manifest.js:
{
"name": "Focus-Bot",
"description": "A bot meant to help you focus",
"version": "1.0",
"manifest_version": 3,
"background": {
"service_worker": "background.js"
},
"permissions": ["storage", "activeTab", "scripting"],
"action": {
"default_popup": "popup.html",
"default_icon": {
"16": "/images/get_started16.png",
"32": "/images/get_started32.png",
"48": "/images/get_started48.png",
"128": "/images/get_started128.png"
}
},
"icons": {
"16": "/images/get_started16.png",
"32": "/images/get_started32.png",
"48": "/images/get_started48.png",
"128": "/images/get_started128.png"
},
"options_page": "options.html"
}
Background.js:
chrome.runtime.onInstalled.addListener(() => {
chrome.scripting.executeScript({
function: showAlert
})
});
function showAlert(){
alert('object input for later');
}
这个版本的background.js返回如下错误
TypeError:调用 scripting.executeScript 时出错(scripting.ScriptInjection 注入,可选函数回调):参数“injection”出错:缺少必需的属性“target”。
一个正常工作的 Chrome 扩展(绿色背景按钮)的示例代码使用 popup.js 文件中的 chrome.tabs 来获取目标并注入 javascript,但是当 background.js 运行相同的代码时,如下所示:
Background.js(标签):
chrome.runtime.onInstalled.addListener(() => {
let [tab] = await chrome.tabs.query(queryOptions);
console.log(tab)
chrome.scripting.executeScript({
function: showAlert
})
});
function showAlert(){
alert('object input for later');
}
Background.js 似乎因“Service Worker 注册失败”而崩溃,没有错误日志。
如何从 background.js 显示当前活动页面的警报?
【问题讨论】:
标签: javascript google-chrome-extension