how can i use a chrome extension content script to inject html into a page at startup

妖精的绣舞 提交于 2019-12-20 17:29:31

问题


i want to create an extension to inject html into every page as soon as it loads up. I am familiar with teh manifest.json rules for this as well as how to run a content script. The problem I'm currently having is the content script injects the html after the web page has loaded which is a bit disruptive. I would like to load it as soon as the window is open so it is injected and then the webpage loads as well. Can you help?


回答1:


Just to be clear here, "loads up" means "starts loading," right? And when you say you're familiar with the manifest.json, you mean you're familiar with the permissions necessary and how to specify which pages and which script to run? Because I think what you're looking for is the run_at property of content_scripts in your manifest.json:

http://code.google.com/chrome/extensions/content_scripts.html#registration

{
  // other stuff
  "content_scripts": [{
    "matches": ["http://*/*"],
    "js": ["content.js"],
    "run_at": "document_start"
  }],
  // other stuff
}

That forces your code to execute before the DOM loads in every page. Note that this can be complex because your extension may fail to create HTML since, of course, the DOM hasn't yet loaded. If you'd like your script to fire just a bit earlier than its default "document_idle", use "document_end" instead.



来源:https://stackoverflow.com/questions/5536035/how-can-i-use-a-chrome-extension-content-script-to-inject-html-into-a-page-at-st

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