Jeanluca Scaljeri
Jeanluca Scaljeri

Reputation: 29097

Angular gives `Refused to execute inline event handler` error

I have created an angular application. which gives the following error in the browser

enter image description here

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.

The reason is that angular injects the following in index.html

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

Its that onload="this.media='all'"

One solution is to set "optimization" to false, in which case angular doesn't inject this code. But that doesn't sound like the best solution. Any suggestions how to do this?

An other solution, which I think is a little bit better than the previous one, is to create a wrapper component which holds all the styling from styles.scss. In my case, for this to work, I also needed to to set the encapsultaion of that wrapper component to ViewEncapsulation.None

Upvotes: 15

Views: 9689

Answers (2)

Miguel Carbajal
Miguel Carbajal

Reputation: 351

I had to add this on production configuration on angular.json

"optimization": {
  "scripts": true,
  "styles": {
    "minify": true,
    "inlineCritical": false
  },
  "fonts": true
},

Because "optimization": false makes the bundle size too big.

Upvotes: 23

Halvor Sakshaug
Halvor Sakshaug

Reputation: 3455

The root cause and fix is covered here: Refused to execute inline event handler because it violates CSP. (SANDBOX) Getting Angular to do it in a better way might be a challenge.

As the error message says, you can allow it with 'unsafe-hashes', but that is a feature of CSP level 3 and only implemented in Chromium browsers.

Upvotes: 0

Related Questions