Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Vue.js in a web extension popup?

I'm trying to develop a web extension and use Vue to style the popup but it doesn't seem to work. The code is extremely basic at the moment

manifest.json:

{
  "manifest_version": 2,
  "name": "Web Extension",
  "description": "Web Extension",
  "version": "1.0.0",
  "browser_action": {
    "default_icon": "icons/compass.svg",
    "default_title": "Web Extension",
    "default_popup": "popup/index.html"
  },
  "permissions": ["<all_urls>"]
}

index.html:

<!DOCTYPE html>
<html>
<head>


<title>My first Vue app</title>
  <script src="https://unpkg.com/vue"></script>
</head>
<body>
  <div id="app">
    {{ message }}
  </div>

  <script>
    var app = new Vue({
      el: '#app',
      data: {
        message: 'Hello Vue!'
      }
    })
  </script>
</body>
</html>

And from the image below it can be seen that the code clearly works when the page is opened in the browser however the js doesn't seem to run in the popup:

enter image description here

like image 637
John Devitt Avatar asked Oct 23 '25 03:10

John Devitt


1 Answers

If you inspect your popup, you will see errors mentioning that the browser refuses to load the vue script due to CSP (you have to specify in you manifest which resources can be accessed by your extension) Add the following CSP in your manifest to load the script :

   "content_security_policy": "script-src 'self' https://unpkg.com; object-src 'self'" 

The script loads but this does not work either : browser refuses to execute inline script because it violates CSP. This one is more tricky because it is related to vue which is using eval function to render your template. To solve this one, you will have to write your render function in js (you don't want to do that...) or to compile your templates. There is a lot of solutions out there to do that. In my opinion, using webpack is the easier way. You can start in a few minutes using a template like this one, which will create almost the same extension as yours, (Hello World popup) using vue and webpack (with all the webpack configuration done for you). Once installed, compile your extension using

npm run build

and load the unpacked extension from the dist directory in chrome. Works like a charm. (or use web-ext cli to run it in Firefox easily)

like image 169
Duhoux Pierre-Louis Avatar answered Oct 25 '25 17:10

Duhoux Pierre-Louis