Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute javascript in Firefox extension popup

I am currently taking my very first steps in extension development. At the moment I'm just trying to display some info in a popup that appears when I hit the button. The problem is that it is dynamic information, that I gather from a JSON-file on the internet. I could not get the data to show up in the pop-up however, and I've narrowed the problem down to the point that it just does not seem to run any Javascript at all...

I have a extremely simple code left:

manifest.json:

    {

  "manifest_version": 2,
  "name": "Test Extention",
  "version": "1.0",

  "description": "",

  "icons": {
    "256": "icon/button.png"
  },
  "permissions": [
    "activeTab",
    "storage"
  ],
  "browser_action": {
    "default_icon": {
      "200": "icon/button.png"
    },
    "default_title": "Test Extention",
    "default_popup": "popup/popup.html"
  }
}

popup/popup.html:

<html>
    <head>
        <meta charset="utf-8">
        <style>
        html,body{width:300px}
        </style>
    </head>
    <body>
        <div id="container"></div>
        <script>
        document.getElementById('container').innerHTML = 'testing';
        </script>
    </body>
</html>

When I run the html-file directly in firefox, it displays "testing" as expected. When I run the extension however, I get a empty pop-up when clicking the new button.

I have also tried putting the js-code in a function, and calling that with a button, to see if it needed some time before js-code can be run, but that does not work either.

I am sure it is something extremely simple I'm missing, but I cannot find anything on this...

like image 334
Discoverer Avatar asked Jul 27 '26 18:07

Discoverer


1 Answers

WebExtension APIs have a Content Security Policy applied to them by default. So it can't execute inline javascript code in popup HTML files.

Not only:

<script>
    document.getElementById('container').innerHTML = 'testing';
</script>

But also:

<button onclick="alert('hello')">Hello</button>

If you touched this rule, you can get some error message in Browser Toolbox and Add-on Debugger.

So, for fix this, use <script src="..."></script> rather than <script>...</script>.

Or, maybe set Unsafe inline script to content_security_policy key in manifest.json can fix this too. But MDN tells me:

Note: Valid examples display the correct use of keys in CSP. However, extensions with 'unsafe-eval', 'unsafe-inline', remote script, blob, or remote sources in their CSP are not allowed for extensions listed on addons.mozilla.org due to major security issues.

in this page. It seems that not good way.

like image 95
pea3nut Avatar answered Jul 29 '26 08:07

pea3nut



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!