【问题标题】:Angular gives `Refused to execute inline event handler` errorAngular给出“拒绝执行内联事件处理程序”错误
【发布时间】:2022-01-18 01:05:51
【问题描述】:

我创建了一个 Angular 应用程序。在浏览器中出现以下错误

Refused to execute inline event handler because it violates the following Content Security Policy directive: "script-src 'self'". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution. Note that hashes do not apply to event handlers, style attributes and javascript: navigations unless the 'unsafe-hashes' keyword is present.

原因是angular在index.html中注入了以下内容

<link rel="stylesheet" href="styles.css" media="print" onload="this.media='all'">

onload="this.media='all'"

一种解决方案是将"optimization" 设置为false,在这种情况下,angular 不会注入此代码。但这听起来不是最好的解决方案。有什么建议如何做到这一点?

另一个我认为比前一个更好的解决方案是创建一个包装组件,该组件包含来自styles.scss 的所有样式。就我而言,要使其正常工作,我还需要将该包装器组件的 encapsultaion 设置为 ViewEncapsulation.None

【问题讨论】:

  • 点击某物后会出现这种情况吗?还是只是加载它?
  • 它发生在初始加载
  • 它有没有机会告诉你它是哪个文件?听起来它正在尝试保护代码,因为存在一些潜在的不安全执行。
  • 我找到了导致此问题的根本原因的代码。在我的styles.scss 中,我有几个 scss 和 css 导入(它们导入第三方样式)。当我删除它们时,错误消失了。我认为styles.scss被编译成css并注入index.html。我想这就是原因。这能解决吗?
  • 您可以自己托管第三方 css 吗?他们有什么奇怪的地方吗?

标签: angular content-security-policy


【解决方案1】:

这里介绍了根本原因和修复方法:Refused to execute inline event handler because it violates CSP. (SANDBOX) 让 Angular 以更好的方式来做这件事可能是一个挑战。

正如错误消息所述,您可以使用“不安全哈希”来允许它,但这是 CSP 级别 3 的一项功能,仅在 Chromium 浏览器中实现。

【讨论】:

    猜你喜欢
    • 2020-02-27
    • 2021-07-26
    • 2015-11-10
    • 2016-07-19
    • 2021-12-10
    • 2020-09-21
    • 1970-01-01
    • 1970-01-01
    • 2011-03-28
    相关资源
    最近更新 更多