简体   繁体   中英

Chrome extension not loading jquery

I tried importing jQuery into my Chrome extension, but when I try

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>

It says that it Refused to load the script 'http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js' because it violates the following Content Security Policy directive: "script-src 'self' chrome-extension-resource:". What does that mean and, more importantly, how would I go about that?

Works for me when I load jQuery through manifest.json :

{
...
  "background": {
    "scripts": ["jquery.min.js", "background.js"]
  },
...
}

To overcome this, you have to override the default CSP or you have to import the JS file from local resources. Sometimes overriding the CSP may not work (HTTP is not permitted). So I suggest you to always import the JS files from local. Chrome Extensions have some security guidelines for not using external JS.

Just save the jQuery plugin to your local and try to import in you html page. For example, imagine you have saved the jQuery plugin as "jquery_local_file.js" in your local.

<html>
<head>
    <script src="jquery_local_file.js"></script>
</head>
<body>
    //body code here
</body>
</html>

(OR)

manifest.json

"content_security_polciy:"srcipt-src 'self' https://ajax.googleapis.com, object-src 'self'";

It definitely works. :)

Security reasons -- extensions can do much more than a normal sandboxed web page. For that reason you'll likely have to use a version of jQuery you package with your extension, instead of one to be loaded over the internet, especially one loaded over HTTP (vs HTTPS).

For security reason, you cannot refer to an external JavaScript file within your Google Chrome extension. In order to overcome your problem you have to embed the jQuery library in your extension and then reference it in your background.html page. Something like :

<html>
  <head>
    <script src='jquery.min.js'></script>
    <!-- ... -->
  </head>
  <body>
    <!-- ... -->
  </body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM