我在DOM中注入了一个脚本,我想在后台向service worker发送消息。我得到一个错误,我不明白为什么。
这是我的background.js
文件:
chrome.runtime.onMessage.addListener((req, sender, sendRes) => {
console.log('this has worked', req, sender, sendRes('this worked'));
return true;
});
这是我的inject.js
文件,注入injected.js
(见下文)代码:
const s = document.createElement('script');
s.src = chrome.runtime.getURL('injected.js');
s.onload = function () {
this.remove();
};
(document.head || document.documentElement).appendChild(s);
injected.js
:
console.log('fetch interceptor started');
const { fetch: origFetch } = window;
chrome.runtime.sendMessage({ works: 'This worked at least' }, (res) => console.log(res)); // Error is thrown immediately
window.fetch = async (...args) => {
const response = await origFetch(...args);
const url = new URL(args[0].url);
// sendMessageToBackground({ pathname, ...url.searchParams }); // not in use because it throws error at the top already
response
.clone()
.json()
.then(async (body) => await sendMessageToBackground({ pathname, body }))
.catch((err) => console.error(err));
return response;
};
async function sendMessageToBackground(msg) {
const res = await chrome.runtime.sendMessage(msg);
console.log('result message', res);
console.log('msg', msg);
}
manifest.json
:
{
...
"permissions": ["storage", "activeTab", "scripting", "webRequest"],
"host_permissions": ["https://REDACTED.com/*"],
"manifest_version": 3,
"background": {
"service_worker": "background.js"
},
"content_scripts": [
{
"matches": ["https://REDACTED.com/*"],
"run_at": "document_start",
"js": ["inject.js"]
}
],
"web_accessible_resources": [{ "resources": ["injected.js"], "matches": ["https://REDACTED.com/*"] }],
...
}
通过声明式地注入内容脚本或通过"scripting"允许的方法以编程的方式注入内容脚本。和或"tabs"权限,你给网页带来了一组属于扩展世界的对象,这些对象通常是你无法访问的。
因此,inject.js脚本将能够访问这些对象(在您的例子中是chrome.runtime),而注入ED.js脚本不会。我不知道你的中文盒子系统有什么目的,但我会尝试跳过inject.js,并以声明式的方式注入injectED.js。
对于await与.then在我看来,没有禁忌症(至少乍一看没有)。我以前写过例程,在那里我使用这个组合,从来没有出现过问题。