Search code examples
javascripthtmlgoogle-chrome-extensionweb-componentcontent-script

Can a chrome extension access and alter a static HTML asset?


I want to build a Chrome extension that will be able to inject a script tag into a statically served HTML file (which is not the page itself ie. not index.html).

I am able to do this on the main actual page (ie. index.html) with a content script with this in my manifest:

...
"content_scripts": [
  {
    "js": ["script.js"],
    "run_at": "document_start"
  }
],
...

...and document.body.insertAdjacentHTML('afterbegin', '[SCRIPT_PATH]'); in script.js, but what would I like to do is to perform this on another HTML file served as an asset, which BTW is being imported from my main index.html as a Web Component.

So in other words, can a content script access (and modify/alter) static HTML files served as source files (except the main index.html)?

Thanks!

EDIT: So here's my structure:

index.html contents:

<!DOCTYPE html>
<html>
<head>
  <title>Yay!</title>
  <link rel="import" href="foo.html">
</head>
<body>
  Sexy body woop!
</body>
</html>

foo.html contents:

<script src="bar.js"></script>
<!-- here I want the Chrome extension's content script to inject another script -->

Solution

  • You can access the imported document with the import attribute of the <link> element.

    var link = document.querySelector( 'link[href="foo.html"]' )
    var importedDoc = link.import
    

    Then you can manipulate the imported HTML document as you would do with the main one:

    //get the bar.js script element
    var script = importedDoc.querySelector( 'script[src="bar.js"]' )
    //append your script after it
    importedDoc.body.insertBefore( yourScript, script.nextSibling )