2

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"
  }
}

2 Answers 2

4

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);
2
  • Thanks, but it still doesn't seem to be working. I'm not even getting an error now.
    – David
    Oct 11, 2014 at 22:12
  • @David inline event handlers won't work either, see the update. You can get the element and bind the event dynamically.
    – BrunoLM
    Oct 11, 2014 at 22:15
4
<script> src = "popup.js" </script>

should be

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

I think...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.