David
David

Reputation: 733

What's wrong with this simple chrome extension?

I'm trying to make an extremely simple chrome extension that alerts something when you click a button, but it's not working. I'm getting the following error:

Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' chrome-extension-resource:". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution.

Can anyone help? This is what I have right now:

popup.html

<html>
    <body>
        <input type = "button" id = "the_button" value = "My button" onclick = "sayHi()"></input>
    </body>
    <script> src = "popup.js" </script>
</html>

popup.js

function sayHi() {
    alert("hi")
}

manifest.json

{
  "manifest_version": 2,
  "name": "Test",
  "description": "Test Extension",
  "version": "1.0",

  "icons": { 
    "48": "icon.png"
   },

  "permissions": [
    "http://*/*", 
    "https://*/*"
  ],

  "content_scripts": [{
    "matches": ["http://*/*", "http://*/*"],
    "js": ["jquery.js", "popup.js"]
  }],

  "browser_action": {
    "default_title": "This is a test",
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  }
}

Upvotes: 2

Views: 2293

Answers (2)

BrunoLM
BrunoLM

Reputation: 100361

The problem is here

<script> src = "popup.js" </script>

To include the js file use

<script src="popup.js"></script>

This error will happen when you try to put inline Javascript in your files. Chrome extensions complain about that.

You would get the same error message if you were to try

<script> alert("hello world"); </script>

From Google Chrome extension documentation

Inline JavaScript will not be executed. This restriction bans both inline blocks and inline event handlers (e.g. <button onclick="...">).

This also means that your inline event handler is not going to work, you have to bind the event dynamically instead, in your popup.js script:

document.getElementById("the_button").addEventListener("click", function()
{
    // click code here
}, false);

Upvotes: 4

<script> src = "popup.js" </script>

should be

<script src="popup.js"></script> 

I think...

Upvotes: 4

Related Questions