Chrome Extension “Refused to load the script because it violates the following Content Security Policy directive”

匿名 (未验证) 提交于 2019-12-03 03:05:02

问题:

I'm trying to create a Chrome extension, but none of my JS works. The console shows this error:

Refused to load the script 'https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js' because it violates the following Content Security Policy directive: "script-src 'self' blob: filesystem: chrome-extension-resource:".

Why is it blocking my jQuery from running?

回答1:

Did you allow it in your manifest JSON file. Something like this:

manifest.json

 {    "name": "My Extension",    "content_scripts": [{      "js": ["jquery.min.js", "YourJavaScriptFile.js"],      "matches": ["http://*/*", "https://*/*"]    }]  } 

There are required fields I left out, but just giving the basic idea.



回答2:

As explained on the Chome website, there is a Content Security Policy preventing your script to load remote script:

A relaxed policy definition which allows script resources to be loaded from example.com over HTTPS might look like:

"content_security_policy": "script-src 'self' https://example.com; object-src 'self'"

So in your case, the manifest.json should contains:

 {   "name": "My Extension",   "manifest_version": 2,   "background":{      "scripts": [...]   },   "content_security_policy": "script-src 'self' https://example.com; object-src 'self'",  } 


回答3:

well, you cant use CDN for js, you will be have to copy the content of "https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js" and create a new file inside your js directory and call it jquery.min.js and paste everything in it , then in your HTML file header remove the line that has this url in it and use this one instead

<script src="js/jquery.min.js"></script> 

but make sure that this is the write path for the file that contains all the data in the mentioned url

cheers,



回答4:

My HTML file had <script> some js code within it </script>. When removed the script tags, the error was gone.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!