jquery – 由于Content Security Policy指令,扩展程序拒绝加载脚本

前端之家收集整理的这篇文章主要介绍了jquery – 由于Content Security Policy指令,扩展程序拒绝加载脚本前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
以下是我的HTML代码

脚本:

@H_403_4@<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="background.js"></script>

HTML:

@H_403_4@<button name="btnlogin" id="btnlogin">Login</button><br/><br/>

以下是js

@H_403_4@$(document).ready(function(){ document.getElementById("#btnlogin").click(function(){ alert("s"); }); });

清单文件

@H_403_4@{ "manifest_version": 2,"name": "One-click Kittens","description": "This extension demonstrates a 'browser action' with kittens.","version": "1.0","browser_action": { "default_icon": "icon.png","default_popup": "popup.html" },}

我发现,当我运行这个代码只是在浏览器,而不是警告出现正常,但当我运行它作为一个镀铬扩展它给我以下错误

未捕获ReferenceError:$未定义

拒绝加载脚本“http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js”,因为它违反了以下内容安全策略指令:“script-src”self’chrome-extension-resource:“。

我不明白这些错误是什么。请帮我理解延期..

谢谢

解决方法

在Chrome扩展程序中,外部脚本源必须明确允许您的清单中扩展程序的 content security policy(CSP):

If you have a need for some external JavaScript or object resources,you can relax the policy to a limited extent by whitelisting secure origins from which scripts should be accepted…

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

06000

脚本只能通过HTTPS加载到扩展中,因此您必须通过HTTPS加载jQuery CDN资源:

@H_403_4@<script src="https://ajax.googleapis.com/..."></script>

并将修改后的CSP添加到清单以允许HTTPS资源:

@H_403_4@{ "manifest_version": 2,"browser_action": { "default_icon": "icon.png","default_popup": "popup.html" },"content_security_policy": "script-src 'self' https://ajax.googleapis.com; object-src 'self'" }

然而,对于您的特定情况,更好的解决方案是将jQuery添加到本地的扩展中,而不是从Internet加载(例如,您的分机目前不会脱机工作)。只需在扩展文件夹中添加一个jQuery的副本,并在脚本标签中使用相对路径。假设您的jQuery库和HTML弹出文件位于相同的子目录中,只需执行以下操作:

@H_403_4@<script src="jquery-x.y.z.min.js"></script>

猜你在找的jQuery相关文章