繁体   English   中英

注入 Javascript 的 Chrome 扩展 - 无法读取未定义的属性(读取“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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM