[英]Chrome extension - Uncaught TypeError: Cannot read properties of undefined (reading 'sendMessage')
[英]Chrome Extension with injected Javascript - Cannot read properties of undefined (reading 'sendMessage')
我有一個注入 DOM 的腳本,我想在后台向我的服務工作者發送消息。 我收到一個錯誤,我不明白為什么。
這是我的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/*"] }],
...
}
通過“腳本”和/或“選項卡”權限允許的方法以聲明或編程方式注入內容腳本,您將一組對象帶到 web 頁面,這些對象屬於您通常不會訪問的擴展世界能夠訪問。
因此, inject.js腳本將能夠訪問這些對象(在您的情況下為 chrome.runtime),而 inject ED .js 腳本則不能。
我不知道你的中文盒子系統有什么用途,但我會嘗試跳過 inject.js 並以聲明方式注入 injectED.js。
對於與.then一起的await演講,在我看來沒有禁忌症(至少乍一看)。 我以前在使用這種混音的地方編寫過例程,但從未遇到過問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.