javascript Chrome 扩展:在页面加载前注入 JS

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19191679/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 14:43:20  来源:igfitidea点击:

Chrome extension: Inject JS before page load

javascriptgoogle-chromegoogle-chrome-extension

提问by Ian McIntyre Silber

Is it possible to inject JS before page load, or is it necessary to use content scripts and way for the document to finish?

是否可以在页面加载之前注入 JS,或者是否需要使用内容脚本和方式来完成文档?

For example, is there a faster way to execute JS that turns the page red as soon as it's opened?

例如,有没有一种更快的方法来执行打开页面就变成红色的 JS?

回答by Rob W

Declare a content script in the manifest file with "run_at": "document_start"to get it to run as soon as possible, i.e. right after constructing the document root (when <head>does not exist yet).

在清单文件中声明一个内容脚本"run_at": "document_start"以使其尽快运行,即在构建文档根目录之后(当<head>尚不存在时)。

For your very specific example, it might be better to declare a content style instead, similar to content scripts, but using the "css"key instead of "js".

对于您非常具体的示例,最好改为声明内容样式,类似于内容脚本,但使用"css"键而不是"js".

If you want to dynamically run a script as soon as possible, then call chrome.tabs.executeScriptwhen the chrome.webNavigation.onCommittedevent is triggered.

如果要尽快动态运行脚本,那么chrome.tabs.executeScriptchrome.webNavigation.onCommitted事件触发时调用。