Search code examples
javascriptvue.jsgoogle-chrome-extension

VueJS app to replace page content in Chrome extension


I am considering writing a Chrome extension in VueJS to totally change the apparence of a specific site.

Thus, I need to dynamically create an element, mount my VueJS app in it, and replace the body of the page with this rendered content.

I tested the dynamic creation of a container in a simple page, without Chrome extension, and it works great:

<html>
  <body>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
    <script>
      const app = new Vue({
        data: () => ({
          count: 0
        }),

        template: '<button v-on:click="count++">Clicked {{ count }} times</button>'
      });


      const body = document.getElementsByTagName('body')[0];
      let vueContainer = document.createElement('div')
      body.replaceWith(vueContainer);
      app.$mount(vueContainer);
    </script>
  </body>
</html>

This renders the VueJS app totally OK.

But then, when I create a Chrome extension, and put the same code in my script.js file, it actually replaces the content of the page with a blank page. The VueJS code is interpreted (if I add a console.log("something") in the mounted method of the VueJS app, it shows up).

// script.js

const app = new Vue({
  data: () => ({
    count: 0
  }),

  template: '<button v-on:click="count++">Clicked {{ count }} times</button>'
});

const body = document.getElementsByTagName('body')[0];
let vueContainer = document.createElement('div')
body.replaceWith(vueContainer);
app.$mount(vueContainer);
// manifest.json

{
  "name": "My extension",
  "description": "Blah",
  "version": "1.0",
  "manifest_version": 3,
  "content_scripts": [
    {
      "matches": ["https://www.mysite.fr/*"],
      "js": ["[email protected]", "script.js"]
    }
  ]
}

It's like the extension prevents the rendered content to be displayed.

Actually, when inspecting the DOM, I have the confirmation that my VueJS app is fired: the div is replaced… but by a HTML comment instead of the rendered content:

<!---->

Any ideas? Thanks in advance!


Solution

  • OK, so I solved it thanks to the doc. Chrome extension will block any js tags within the templates.

    So the only solution is to pass a pre-compiled template.

    Using vue-cli, then building the app to have both scripts ans tags in js files, and then referencing it in the manifest.json file works!