Chrome Extension Content Script - Inject Javascript before page code

匿名 (未验证) 提交于 2019-12-03 01:40:02

问题:

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!

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!