首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Chrome扩展:在远程网站上访问“`window`”是可行的,但在本地主机上是不可能的

Chrome扩展:在远程网站上访问“`window`”是可行的,但在本地主机上是不可能的
EN

Stack Overflow用户
提问于 2022-09-06 21:06:37
回答 1查看 72关注 0票数 0

我有一个非常简单的Chrome扩展,它在window对象上定义了一个常量。

它在在线网站上工作,但在显示本地文件的选项卡上失败。

Blocked script execution in 'file:...mht' because the document's frame is sandboxed and the 'allow-scripts' permission is not set.

我会以某种方式理解,如果它是相反的安全方式,但这种方式,它觉得我可以做一些事情,在扩展,以一种方式,它也适用于本地离线文件。

manifest.json

代码语言:javascript
复制
{
  "name": "Extension Expose",
  "description": "Extension.",
  "version": "1.0",
  "manifest_version": 3,
  "content_scripts": [
    {
      "matches": ["http://*/*", "https://*/*", "http://localhost/*", "https://localhost/*"],
      "js": ["content.js"]
    }
  ],
  "web_accessible_resources": [{ 
    "resources": ["write.js"],
    "matches": ["http://*/*", "https://*/*", "http://localhost/*", "https://localhost/*"]
  }]
}

content.js

代码语言:javascript
复制
console.log("content.js")

var s = document.createElement('script');
s.src = chrome.runtime.getURL('write.js');
s.onload = function() {
    this.remove();
};
(document.head || document.documentElement).appendChild(s);

write.js

代码语言:javascript
复制
console.log("write.js")
window.ee = "abc"
console.log("successfully written to window")

在任何现场直播的网站上,它都能完美地完成自己的任务。

但是,如果打开本地.mht,则会得到以下信息

此外,我现在已经将matches设置为["http://*/*", "https://*/*", "http://localhost/*", "https://localhost/*", "file://*", "file://*/*", "http://127.0.0.1/*", "https://127.0.0.1/*"],只是为了更安全,这并没有改变任何事情。

在纯html文件中,控制台抛出

content.js:8 GET chrome-extension://abcdef/write.js net::ERR_BLOCKED_BY_CLIENT

这可能与跨域http请求有关,但我不明白为什么相同的错误不会在mht文件上触发。

备选方案

我找到了这个答案,https://stackoverflow.com/a/9517879列出了许多不同的方法来做类似的事情。我在这里主要做的是Method 1。有趣的是,方法3(定义内嵌脚本)对online htmloffline html都有效,但不幸的是,这在.mht上仍然失败。我认为这是因为.mht内部的工作方式。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-09-07 05:38:03

文件:// pages上有一个web_accessible_resources错误,只在Chrome 106中修复。

一个更好的解决方案是使用chrome.scripting而不是,因为它可以在页面开始可靠加载之前设置变量,而且我们不会让网站检测到扩展。

从manifest.json.

  • Remove content.js

  • 添加到manifest.json:

  1. 删除content_scripts和web_accessible_resources

代码语言:javascript
复制
  "background": {"service_worker": "bg.js"},
  "permissions": ["scripting"],
  "host_permissions": ["<all_urls>"]

background.js:添加

代码语言:javascript
复制
chrome.runtime.onInstalled.addListener(async () => {
  const old = await chrome.scripting.getRegisteredContentScripts();
  if (old[0]) await chrome.scripting.unregisterContentScripts({ids: old.map(s => s.id)});
  await chrome.scripting.registerContentScripts([{
    id: 'write',
    js: ['write.js'],
    matches: ['<all_urls>'],
    runAt: 'document_start',
    world: 'MAIN',
  }]);
});
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73627752

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档