【问题标题】:Chrome Extension Content Script - Inject Javascript before page codeChrome 扩展内容脚本 - 在页面代码之前注入 Javascript
【发布时间】:2019-07-03 13:13:54
【问题描述】:

我正在尝试使用内容脚本制作一个 Chrome 扩展程序,以便在页面中的所有其他脚本之前将脚本注入网页。 (我正在使用xhook 库来拦截 XHR 请求,它会覆盖 XHR 类。我需要这样做,因为它当前是 impossible to modify responses using Chrome extension APIs。)“document_start”事件在任何 DOM 被写入之前执行,所以我使用内容脚本手动创建正文元素。但是,这会在 HTML 中创建 2 个正文标记,这似乎使在注入脚本标记中定义的变量无法访问主页中的代码。

我应该怎么做?

下面是我的代码的简化版本:

ma​​nifest.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


【解决方案1】:

如果扩展加载在document_startdocument.head = null。因此,要克服这个问题,请执行 - document.lastChild.appendChild(script_tag);。这会在您的 <html> 层次结构中创建一个脚本标记。希望这会有所帮助。

另外,你能告诉你为什么做以下陈述 document.body = document.createElement("body");我相信这不是必需的。

【讨论】:

    猜你喜欢
    • 2012-04-12
    • 2014-01-18
    • 1970-01-01
    • 2011-12-11
    • 2018-07-25
    • 1970-01-01
    • 1970-01-01
    • 2012-06-17
    • 1970-01-01
    相关资源
    最近更新 更多