【发布时间】:2019-07-03 13:13:54
【问题描述】:
我正在尝试使用内容脚本制作一个 Chrome 扩展程序,以便在页面中的所有其他脚本之前将脚本注入网页。 (我正在使用xhook 库来拦截 XHR 请求,它会覆盖 XHR 类。我需要这样做,因为它当前是 impossible to modify responses using Chrome extension APIs。)“document_start”事件在任何 DOM 被写入之前执行,所以我使用内容脚本手动创建正文元素。但是,这会在 HTML 中创建 2 个正文标记,这似乎使在注入脚本标记中定义的变量无法访问主页中的代码。
我应该怎么做?
下面是我的代码的简化版本:
manifest.json
{
// Required
"manifest_version": 2,
"name": "My Extension",
"version": "0.1",
"description": "My Description",
"author": "Me",
"permissions": ["https://example.com/*"],
"content_scripts": [{
"matches": ["https://example.com/*"],
"js": ["xhook.js"],
"run_at": "document_start",
"all_frames": true
}
]
}
xhook.js
var script_tag = document.createElement('script');
script_tag.type = 'text/javascript';
holder = document.createTextNode(`
//Xhook library code
// XHook - v1.4.9 - https://github.com/jpillora/xhook
//...
//Now to use the library
console.log('loading extension');
xhook.after(function (request, response) {
//console.log(request.url);
if (request.url.startsWith("https://example.com/")) {
var urlParams = new URLSearchParams(window.location.search);
fetch('https://example.com/robots.txt')
.then(
function (apiresponse) {
if (apiresponse.status == 200) {
response.text = apiresponse.text();
return;
};
if (apiresponse.status !== 200) {
console.log('File not found. Status Code: ' +
apiresponse.status);
return;
};
});
};
});
xhook.enable();`);
script_tag.appendChild(holder);
document.body = document.createElement("body");
document.head.appendChild(script_tag);
谢谢!
【问题讨论】:
-
1) 不要创建正文,只需将脚本附加到 document.documentElement,因为 DOM 规范对其子项没有限制。 2) 挂钩只是几行代码,因此您可能不需要整个库,3) 目前您正在使用
xhook变量污染全局页面命名空间 - 如果您真的想将其移动到 IIFE 中使用 xhook。 -
@wOxxOm 谢谢!这对我来说主要是为了注入 JS 并拦截 XHR 响应。有什么方法可以重命名真正的
load事件,以便在文档的其余部分引发load之前拦截响应? -
我写了一个事件拦截的新问题:stackoverflow.com/questions/55270830/…
标签: javascript html google-chrome-extension xmlhttprequest