Chrome扩展程序内容脚本-在页面代码之前插入Javascript [英] Chrome Extension Content Script - Inject Javascript before page code
问题描述
我正在尝试使用内容脚本制作Chrome扩展程序,以将脚本插入网页,然后将该脚本插入页面中的所有其他脚本. (我正在使用 xhook 库来拦截XHR请求,该请求将覆盖XHR类.我需要这样做这是因为当前它无法使用Chrome扩展API修改响应.)在写入任何DOM之前执行"document_start"事件,因此我使用内容脚本手动创建了body元素.但是,这会在HTML中创建2个body标记,这似乎使注入的脚本标记中定义的变量无法访问主页中的代码.
I am trying to make a Chrome extension with a content script to inject a script into a webpage before all other scripts in the page. (I am using the xhook library to intercept XHR requests, which overwrites the XHR class. I need to do this because it is currently impossible to modify responses using Chrome extension APIs.) The "document_start" event is executed before any of the DOM is written, so I manually create the body element with the content script. However, this creates 2 body tags in the HTML, which appears to make variables defined within the injected script tag inaccessible to the code in the main page.
我应该怎么做?
我在下面简化了我的代码:
I have simplified version of my code below:
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);
谢谢!
推荐答案
如果扩展名在document_start
,document.head = null
处加载.因此,要克服此问题,请执行-document.lastChild.appendChild(script_tag);
.这将在您的<html>
层次结构中创建一个脚本标签.希望这会有所帮助.
If the extension is loaded at document_start
, document.head = null
. Hence, to overcome this, do - document.lastChild.appendChild(script_tag);
. This creates a script tag in your <html>
hierarchy. Hope this helps.
也请您说出为什么要执行以下语句
document.body = document.createElement("body");
我相信这不是必需的.
Also, Could you please tell why are you doing the following statement
document.body = document.createElement("body");
I believe this is not required.
这篇关于Chrome扩展程序内容脚本-在页面代码之前插入Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!