简体   繁体   中英

How can fix “it violates the following Content Security Policy directive: ”default-src 'self'" when I use datalist?

When I use datalist with the Content-Security-Policy" content="default-src 'self'", it gives error, "Refused to apply inline style because it violates the following Content Security Policy directive: "default-src 'self'". Either the 'unsafe-inline' keyword, a hash ('sha256-pIL...'), 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. Note also that 'style-src' was not explicitly set, so 'default-src' is used as a fallback.".

The data list works as I hope in the browser, however the error message is annoying. As I hope to keep the security as strong as possible, I do not want to change Content-Security-Policy to unsafe-inline. Could you give me a hint to fix this?

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta http-equiv="Content-Security-Policy" content="default-src 'self'">
</head>
<body>
   <label for="animalList" class="form-label">animal</label>
   <input class="form-control" list="animalOptions" id="animalList" placeholder="">
   <datalist id="animalOptions">
     <option value="dog">
     <option value="cat">
   </datalist>
</body>
</html>

This seems to be a new bug in chromium based browsers (including Edge). It doesn't appear in Firefox v89.

To get rid of this error just add into your CSP:

style-src-attr 'sha256-pILX+5FGCpLRHvNBgtABIdSMmytrYudGxJBUYXY1t0s=' 'unsafe-hashes';

This directive works in browsers on Chromium engine only and applies to style= attribute. Other browsers will follow style-src rules. For <style>...</style> blocks a Chrome will follow style-src rules too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM