简体   繁体   中英

Chrome Extension Content Script - Inject Javascript before page code

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.

How should I do this?

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);

Thanks!

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.

Also, Could you please tell why are you doing the following statement document.body = document.createElement("body"); I believe this is not required.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM