【问题标题】:can't execute inline event handler because it violates the Content Security Policy directive无法执行内联事件处理程序,因为它违反了内容安全策略指令
【发布时间】:2019-10-18 04:29:53
【问题描述】:

我正在尝试创建一个闹钟/定时器扩展。以前从未使用过扩展并遇到此问题错误消息:

“拒绝执行内联事件处理程序,因为它违反了以下内容安全策略指令: “脚本源代码‘自我’https://apis.google.com”。 'unsafe-inline' 关键字,哈希('sha256-...'), 或者需要一个 nonce ('nonce-...') 才能启用内联执行。"

它似乎指的是我的 background.js 代码中的“onended”事件。

我发现这是一个类似的问题:

How to fix chrome-extension inline JavaScript invocation error?

由于我是新手,我不确定如何使修复程序正常工作。

我尝试将它添加到我的 manifest.json 文件中,但它没有做任何事情: "content_security_policy":"script-src 'self' https://apis.google.com; object-src 'self'"

然后我阅读了其中的一些内容,但不确定如何实际获取代码的哈希值: https://www.w3.org/TR/2015/CR-CSP2-20150721/#script-src-hash-usage

上面的链接说:

"你可以通过openssl程序在命令行中获取字符串的摘要"

我不确定 openssl 程序在哪里/是什么。我将如何获得这个哈希?

manifest.json“content_security_policy”中的文本应该是什么样子:对于这个哈希信息?

chrome.runtime.onMessage.addListener(function(response){

  myInterval = setInterval(function(){

  var audio = new Audio("Gentle-wake-alarm-clock.mp3");
  audio.setAttribute("onended",
  "function(){alert('your ' + response + ' second alert has ended')}");
  audio.play();
  clearInterval(myInterval);
  }, response * 1000);

})

我的 manifest.json 文件:

{
    "name": "timer",
    "version": "1.0",
    "description": "Build a timer!",
    "manifest_version": 2,
    "permissions": ["storage"],
    "options_page": "options.html",

    "browser_action": {
      "default_popup": "timerpopup.html",
      "default_icon": "green alarm.png"
    },

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

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


}

【问题讨论】:

  • 您需要使用外部 JavaScript。将脚本标签放在您的脑海中,例如<head><script type='text/javascript' src='background.js'></script></head>。在您的外部 background.js 页面上,它就像 addEventListener('load', function(){ /* run JavaScript in here */ }); 顺便说一句,您不会使用 .setAttribute() 分配事件侦听器。

标签: javascript events


【解决方案1】:

不使用内联事件处理程序而使用addEventListener 可能更容易。您也可以使用setTimeout 而不是setInterval 来避免调用clearInterval

chrome.runtime.onMessage.addListener(function(response) {
  myTimeout = setTimeout(function() {
    var audio = new Audio("Gentle-wake-alarm-clock.mp3");
    audio.addEventListener('ended', function() {
      alert('your ' + response + ' second alert has ended');
    });
    audio.play();
  }, response * 1000);
});

如果您没有在其他任何地方使用clearInterval / clearTimeout,您也可以删除myTimeout =

【讨论】:

    猜你喜欢
    • 2023-02-25
    • 1970-01-01
    • 2020-09-26
    • 1970-01-01
    • 2013-03-17
    • 2021-01-18
    • 1970-01-01
    • 1970-01-01
    • 2021-07-26
    相关资源
    最近更新 更多