Chrome extension "Refused to evaluate a string as JavaScript because 'unsafe-eval'

Vitaly Menchikovsky picture Vitaly Menchikovsky · Jul 17, 2014 · Viewed 30.6k times · Source

I have an 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.

chrome-extension://ldbpohccneabbobcklhiakmbhoblcpof/popup.html:1

Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "script-src 'self' chrome-extension-resource:".

the code popup.js

$(document).ready(function() {
     $.getJSON('http://.......alerts.json', function(data) {
        alert('HELLO');
      });
});

Manifest:

{
  "manifest_version": 2,

  "name": "Alert",
  "description": "This extension for  .",
  "version": "2.0",
  "content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'",
  "permissions": [
    "http://www.......il/"
  ],
  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },
  "content_scripts": [ {
    "js": [ "jquery.min.js", "popup.js" ],
    "matches": [ "http://*/*", "https://*/*"]
  }]
}

Popup:

<!doctype html>
<html>
  <head>
    <title>Getting Started Extension's Popup</title>
    <style>
      body {
        min-width: 357px;
        overflow-x: hidden;
      }

      img {
        margin: 5px;
        border: 2px solid black;
        vertical-align: middle;
        width: 75px;
        height: 75px;
      }
    </style>
     <head>
     <script src='jquery.min.js'></script>
     <script src='popup.js'></script>
</head>
  </head>
  <body>
  </body>
</html>

Answer

jeanM picture jeanM · Aug 20, 2014

I had this message because Chrome doesn't allow inline scripts and inline events handler (like onClick) anymore: they have to be moved to an external JS file (e.g. popup.js) and addEventListener() has to be used to associate events to DOM objects.

For example:

<body onload="initialize()">
<button onclick="handleClick()" id="button1">

has to be replaced by:

window.addEventListener("load", initialize);
document.getElementById("button1").addEventListener("click",handleClick);

In your case, I don't see any JS in the HTML but there are a few things you could try:

  • move popup.js include just before the .
  • correct the html (double head).
  • remove the content_scripts section from the manifest. Content scripts are supposed to be executed against the content of the page, they are not the JS file included in the page or browser action popup. The browser action section should suffice.

See Chrome extension manifest V2 notes