在背景页面中是否有与“run_at:start”等效的内容? [英] Is there an equivalent to `run_at: start` in a background page?

查看:143
本文介绍了在背景页面中是否有与“run_at:start”等效的内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在加载的页面上执行任何其他代码之前运行一些JavaScript代码。



使用如下内容脚本可以正常工作:

p>

  {
matches:[http:// * / *,https:// * / * ,file:// * / *],
js:[contentScript.js],
run_at:document_start
}

但现在我只想在用户通过点击浏览器动作按钮选择的特定页面上运行内容脚本。



我试着听 chrome.tabs.onUpdated 然后调用 executeScript ,但其他代码正在我的内容脚本之前的页面上运行。



有没有办法确保由背景页面在其他代码之前运行?



我也可以在我的内容脚本中添加一个条件,但这意味着我需要访问当前的tabId和所有选项卡的列表我的分机已被激活。

解决方案

根据文档 chrome.tabs.executeScript 有几个有用的参数,包括 runAt (默认情况下它是 document_idle ,这发生在DOMContentLoaded事件之后),所以要尽快注入脚本,请使用 runAt:'document_start'



<$ $ {
runAt:'document_start',
code:'console.log(document.documentElement.innerHTML);',
});

请注意,在此阶段DOM树通常是空的,特别是如果您从早期执行的事件侦听器作为tabs.onUpdated或webNavigation.onCommitted。即使HEAD或BODY元素可能仍然不存在,因此您必须使用(document.head || document.documentElement) fallback作为所有添加节点的容器,例如< style> < script>


I need to run some JavaScript code before any other code is executed on the page that's being loaded.

That works fine using a content script like this:

{
  "matches": ["http://*/*", "https://*/*", "file://*/*"],
  "js": ["contentScript.js"],
  "run_at": "document_start"
}

But now I'd like to run the content script only on certain pages which the user selects by clicking on the browser action button.

I've tried listening to chrome.tabs.onUpdated and then calling executeScript, but other code is running on the page before my content script.

Is there a way to ensure that the code injected by a background page is run before other code?

I could also add a condition inside my content script, but that would mean I need access to the current tabId and a list of all tabs where my extension is activated.

解决方案

According to the documentation chrome.tabs.executeScript has several useful parameters, including runAt (by default it's document_idle, which occurs after DOMContentLoaded event), so to inject a script as soon as possible use runAt: 'document_start'.

chrome.tabs.executeScript(tabId, {
    runAt: 'document_start',
    code: 'console.log(document.documentElement.innerHTML);',
});

Beware the DOM tree is usually empty at this stage especially if you inject from an early executed event listener such as tabs.onUpdated or webNavigation.onCommitted. Even HEAD or BODY elements may be still absent, so you'd have to use (document.head || document.documentElement) fallback as a container for any added nodes such as <style> or <script>.

这篇关于在背景页面中是否有与“run_at:start”等效的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆