首页 > 解决方案 > Chrome 中的 Css 内联样式错误:“拒绝应用内联样式,因为它违反了以下内容安全策略指令……”

问题描述

我有以下html页面:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
    <head>
        <meta charset="utf-8"/>
        <meta http-equiv="X-UA-Compatible" content="IE=11"/>
        <meta http-equiv="Cache-Control" content="no-cache"/>
        <meta http-equiv="Content-Security-Policy" content="default-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline';"/>
        <title>
        </title>
    </head>

    <style>
            .container {
                display: flex;
                display: -webkit-flex;
                justify-content: center;
            }

            .label {
                font-size: 20px;
                text-align: center;
            }

    </style>

    <body>
        <div class="container">
            <div class="label">Label content.</div>
        </div>
    </body>
</html>

尽管带有“unsafe-inline”的“Content-Security-Policy”标签没有应用样式,我在 Chrome 中看到以下错误:

“拒绝应用内联样式,因为它违反了以下内容安全策略指令:“default-src 'self'”。'unsafe-inline' 关键字、哈希 ('sha256-daGc4DKtFpvn1iqhVz5mJJ4bXSwDGTnQKoxHdrHVEhc=') 或随机数 (' nonce-...') 是启用内联执行所必需的。另请注意,'style-src' 未明确设置,因此 'default-src' 用作后备。“

可以做些什么来解决这个问题?

标签: htmlcssgoogle-chrome

解决方案


这可能是因为 HTML 中定义的 CSP 与您的 Web 服务器设置中的不同。对于 Apache,它位于文件“ .htaccess ”中。

但是,如果添加具有全局“unsafe-inline”和“unsafe-eval”的 CSP,则根本没有安全性,并且 CSP 变得有点无用。

此外,考虑为 HTML 和 CSS 创建不同的文件,并在需要时导入样式。


推荐阅读