Chrome extension \"Refused to evaluate a string as JavaScript because 'unsafe-eval'
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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.
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:".
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.
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.
I had a very similar problem. I was not using any Inline Scripts or Inline Event Handlers but still getting that error. Turned out, jQuery internally tries to evaluate the response of such requests which is not allowed in Chrome Extensions. In my case, I was using $.ajax() with dataType: 'json'. I resolved the issue by changing dataType to text and then manually parsing JSON using JSON.parse().
Also it is relevant to mention that most of the jQuery APIs try to execute scripts included in a given html string while parsing which causes similar errors when used in a Chrome Extension. Explicit escaping of scripts in responses is required in such cases. Here is a quote from jQuery parseHTML() 's documentation:
Most jQuery APIs that accept HTML strings will run scripts that are included in the HTML. jQuery.parseHTML does not run scripts in the parsed HTML unless keepScripts is explicitly true. However, it is still possible in most environments to execute scripts indirectly, for example via the attribute. The caller should be aware of this and guard against it by cleaning or escaping any untrusted inputs from sources such as the URL or cookies. For future compatibility, callers should not depend on the ability to run any script content when keepScripts is unspecified or false.
Please note that those points cause problems when used in a Chrome Extension due to Chrome's restriction about inline script evaluation. They might not hold true in general.