如何修复chrome-extension内联JavaScript调用错误?

oma*_*h94 25 javascript google-chrome google-chrome-extension content-security-policy

我正在进行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:"
Run Code Online (Sandbox Code Playgroud)

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.
Run Code Online (Sandbox Code Playgroud)

这是我的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'"


}
}
Run Code Online (Sandbox Code Playgroud)

任何帮助修复此错误将非常感激.

Hai*_* Ai 13

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

  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'"
    
    Run Code Online (Sandbox Code Playgroud)

    另外,我认为更好的方法是下载遥控器client.js并将其作为本地脚本包含在内.

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

直到Chrome 45,没有放松限制执行内联JavaScript的机制.特别是,使用包含"unsafe-inline"的脚本策略将不起作用.