簡體   English   中英

Chrome擴展程序內容腳本 - 在頁面代碼之前注入Javascript

[英]Chrome Extension Content Script - Inject Javascript before page code

我正在嘗試使用內容腳本制作Chrome擴展程序,以將腳本插入網頁中的所有其他腳本之前 (我正在使用xhook庫來攔截XHR請求,該請求將覆蓋XHR類。因為當前無法使用Chrome擴展API修改響應,所以我需要這樣做。)在任何DOM被執行之前,都會執行“ document_start”事件寫的,所以我用內容腳本手動創建body元素。 但是,這會在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);

謝謝!

如果擴展名是在document_start加載的,則document.head = null 因此,要克服這一點,請執行 - document.lastChild.appendChild(script_tag); 這會在<html>層次結構中創建一個腳本標記。 希望這可以幫助。

另外,你能告訴我你為什么要做以下聲明document.body = document.createElement("body"); 我認為這不是必需的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM