在页面加载之前是否可以注入JS,或者必须使用内容脚本,并等待文档完成?
例如,有没有更快的方法执行JS,当页面打开时立即将其变红?
在页面加载之前是否可以注入JS,或者必须使用内容脚本,并等待文档完成?
例如,有没有更快的方法执行JS,当页面打开时立即将其变红?
在清单文件中使用 "run_at": "document_start"
声明一个内容脚本,以使其尽可能快地运行,即在构建文档根节点后立即运行(当 <head>
不存在时)。
对于您特定的示例,最好声明一个内容样式,类似于内容脚本,但使用 "css"
键代替 "js"
。
如果您想要尽可能快地动态运行一个脚本,那么可以在触发 chrome.webNavigation.onCommitted
事件时调用 chrome.tabs.executeScript
。
world
。"world": "main"
,并搭配"run_at": "document_start"
和CSP,以允许扩展程序进行注入。否则,注入的脚本将被拒绝,显示如下错误:
"world": "MAIN":Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' 'wasm-unsafe-eval'". Either the 'unsafe-inline' keyword, a hash ('sha256-*'), or a nonce ('nonce-...') is required to enable inline execution.
有效的属性值为[Extensions] Add main world injections for dynamic content scripts
This CL adds a new field "world" for dynamic content scripts which allows the extension to specify if the script will run in the isolated or main world. By default, scripts which do not specify this field will run in the isolated world.
"ISOLATED"
(默认)或"MAIN"
。{
"name": "script injection",
"version": "0",
"manifest_version": 3,
"minimum_chrome_version": "103.0",
"content_scripts": [
{
"matches": ["*://*/*"],
"js": ["inject.js"],
"run_at": "document_start",
"world": "MAIN"
}
],
"web_accessible_resources": [{
"resources": ["injected.js"],
"matches": ["<all_urls>"]
}],
"content_security_policy": {
"extension_pages": "default-src 'self' 'wasm-unsafe-eval';"
}
}
inject.js
let el = document.createElement("script");
el.src = chrome.runtime.getURL("injected.js");
document.documentElement.appendChild(el);
console.log("injected");
injected.js
console.log(typeof alert); // "function"
console.log("injected file");
delete window.alert;
console.log(typeof alert); // "undefined"
[]
"world": "MAIN"
,但如果页面被缓存,在简单刷新时我的脚本不会运行得足够早。我的代码几乎与你的完全相同,如果你的代码可以工作,我会继续研究我的代码,看看有什么区别。 - Bradalert
始终不可用。-提到的两台机器目前都在chrome 109.0.5414.75稳定版上。 - Christopherinjected.js
中的代码:Object.defineProperty(navigator.mediaDevices,'getUserMedia',{ get:(...args)=>{ console.log('Intercepted!'); } });
然后,我使用此URL进行测试:https://webrtc.github.io/samples/src/content/getusermedia/audio/。第一次加载时,它可以正常工作(我在控制台上看到“intercepted”)。如果我单击刷新,它就不起作用。如果我按Ctrl + Shift刷新,它就可以正常工作。如果我禁用缓存,它也可以正常工作。 - Bradel.async = false;
,但据我所见并没有任何区别。 - Brad
chrome.webNavigation.onCommitted
之前运行,但是它无法访问bg可用的chrome函数。对于bg来说,chrome.webNavigation.onCommitted
仍然是最早的方法。 - Pacerierdocument.documentElement.appendChild(document.createElement('script')).innerHTML = 'window.open=null;document.createElement=null'
,它有效果。但是document.documentElement.appendChild(document.createElement('script')).innerHTML = 'document=null;window=null'
不行。你知道如何覆盖window
和document
吗? - Pacerier