gpt4 book ai didi

google-chrome - 在后台页面: Chrome Extension中加载远程网页

转载 作者:行者123 更新时间:2023-12-04 03:33:14 24 4
gpt4 key购买 nike

是否可以使用chrome扩展程序将远程网页加载到后台页面中?

"background": {
"page": "local.html"
}

可行,但是
"background": {
"page": "http://...."
}

失败并显示以下错误:
Could not load background page http://....

最佳答案

不,那是不可能的。自Chrome 22以来,可能是-请参阅答案的底部。

您可以whitelist a https: resource in the manifest file文件,以便可以手动构造背景脚本。如果网络中断,请确保在扩展中包括回退资源:

<!-- ... doctype etc ... (background.html) -->
<script src="https://..../external_bg.js"></script>
<script src="bg.js"></script>

由于存在Content security policy (CSP),因此无法运行内联JavaScript,因此必须使用外部JS文件。 bg.js可能看起来像:
if (!window.namespace_of_external_bg) {
// Fallback, by defining fallback methods or injecting a new script:
document.write('<script src="fallback_bg.js"></script>');
}

如果要动态构建页面,请避免使用类似eval的方法,因为CSP也禁止使用这些方法。您可以编写模板,并请求外部值来填充模板。 localStorage可用于缓存变量。有关缓存外部资源的示例,请参见Chrome extension adding external javascript to current page's html。此答案涉及内容脚本,因此不能使用确切的方法来启用缓存脚本(因为您将需要使用eval来加载脚本)。但是,仍然可以使用缓存技术。

我也尝试过使用以下方法,不起作用(包含在此答案中,因此您不必自己尝试):
从AJAX响应中创建一个 Blob ,然后使用 webkitURL.createObjectURL 创建一个临时URL来加载资源。
// Modification of https://stackoverflow.com/a/10371025
// Instead of `chrome.tabs.executeScript`, use
// x.responseText or x.response (eg when using x.responseType='arraybuffer')
var blob = new Blob([x.responseText], {type: 'application/javascript'});
var url = (window.URL || window.webkitURL).createObjectURL(blob);
var s = document.createElement('script');
s.src = url;
document.head.appendChild(s);

前面的代码产生以下错误:

Refused to load the script 'blob:chrome-extension%3A//damgmplfpicjkeogacmlgiceidmilllf/96356d24-3680-4188-812e-5661d23e81df' because it violates the following Content Security Policy directive: "script-src 'self' chrome-extension-resource:".



在后台页面加载外部资源

从Chrome 22开始,从技术上讲,可以(使用unsafe-eval CSP策略)在后台页面中加载非https资源。出于安全方面的考虑,显然不推荐使用(例如,因为它容易受到MITM attack的影响)。

这是一个加载任意资源并在后台脚本的上下文中运行它的示例。
function loadScript(url) {
var x = new XMLHttpRequest();
x.onload = function() {
eval(x.responseText); // <---- !!!
};
x.open('GET', url);
x.send();
}
// Usage:
loadScript('http://badpractic.es/insecure.js');
  • 必须指定 unsafe-eval CSP策略。
  • 与往常一样,要发出跨域请求,必须在 list 中permissions部分的 list 中将URL列入白名单,否则服务器必须启用CORS

  • 因此, list 至少应包含:
    "content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'",
    "permissions": ["http://badpractic.es/insecure.js"],
    "background": {"scripts": ["background.js"] }

    关于google-chrome - 在后台页面: Chrome Extension中加载远程网页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11845118/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com