如何解决铬扩展内嵌JavaScript调用错误?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (66)

我正在进行Chrome扩展,但是当我尝试启动onclick()事件时,似乎出现以下错误。

Refused to load the script 'https://apis.google.com/js/client.js?onload=handleClientLoad' because it violates the following Content Security Policy directive: "script-src 'self' blob: filesystem: chrome-extension-resource:"

Refused to execute inline event handler because it violates the following Content Security Policy directive: "script-src 'self' blob: filesystem: chrome-extension-resource:". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution.

这是我的manifest.json:

{
  "manifest_version": 2,

  "name": "SECURE",
  "description": "this extension offers secure communication for GMAIL     users",
  "version": "1.0",

 "browser_action": {
 "default_icon": "resources/icon16.png",
 "default_popup": "popup.html",
 "default_title": "Click here!"


 },

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

 "content_scripts": [
  {
   "matches": ["http://*/*", "https://*/*"],
   "js":["myscript.js"],
   "run_at": "document_end"
  }
  ],
"permissions": ["identity", "https://accounts.google.com/*",  "https://www.googleapis.com/*"],

"oauth2": {
   "client_id": "975410329966.apps.googleusercontent.com",
 "scopes": [
   "<all urls>",
   "https://www.googleapis.com/auth/drive",
   "https://mail.google.com/",
   "https://www.googleapis.com/auth/gmail.login",
   "https://www.googleapis.com/auth/gmail.compose",
   "https://www.googleapis.com/auth/gmail.readonly",
   "https://www.googleapis.com/auth/gmail.send"
  ],

 "content_security_policy":"script-src 'self'  'unsafe-inline' 'unsafe eval'  https://apis.google.com/js/client.js?; object-src 'self'"


}
}
提问于
用户回答回答于

默认情况下,内容安全策略不会加载内联脚本,只能加载本地脚本。您可以通过以下方式放宽默认政策:

  1. 内联脚本。查看官方指南,通过在策略中指定源代码的base64编码散列,可以将内联脚本列入白名单。查看示例的元素的哈希用法但我相信更好的方法是将这个逻辑提取到单独的脚本中,而不是使用内联脚本。
  2. 远程脚本。您可以https://apis.google.com/js/client.js?onload=handleClientLoad通过以下部分将白名单脚本资源列入manifest.json "content_security_policy":"script-src 'self' https://apis.google.com; object-src 'self'" 另外,我相信一个更好的方式可能是下载远程client.js并将其包含为本地脚本。

请注意,根据内联脚本的描述,unsafe-inline不再有效。

直到Chrome 45,都没有放松对内嵌JavaScript执行限制的机制。特别是,制定包含“不安全内联”的脚本策略将无效

扫码关注云+社区