简体   繁体   中英

Chrome Extension to inject dynamic script into header and after opening body tag

I am trying to build a Chrome extension that would I am trying to inject a bit of dynamic javascript into both the a) the header of a page b) The body of a page however this should be added on page load I am struggling with the existing documentation.

Any good guidance on how to get this done simply?

Jquery Solution

Keep in mind that if you are adding this javascript on page load , the user will see a brief flash of original content before it's changed/updated by your script.

To add a console.log to both head and body in jquery:

Adding to head

$('head').append('<script>console.log("Script added to head")</script>');

Adding to body

$('body').append('<script>console.log("Script added to body")</script>');

Verification

If you add both of these to your chrome console, you should see something like:

Script added to head
Script added to body

If you search the HTML (Jquery's $('html').html() ) for this script, you get two hits:

> regex = new RegExp(/<script>console\.log\("Script added to \w*?"\)<\/script>/, "g")
> pagetext = $('html').html().match(regex).length
2

As we added 2 lines console log "Script was added to...", we have confirmation that the lines were added.

When to load

If this is in your content script, you don't need to worry about nesting this in a window.onload or similar if you have "run_at": "document_end" in your manifest.json (in the content script JSON).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM