0

所以我在一个网站上实现了谷歌客户评论徽章,它在 devtools 控制台中抛出了一个 JS 错误:

Unrecognized Content-Security-Policy directive 'base-uri'

任何人以前遇到过这个错误并且知道如何解决它?

客户评论徽章是使用 Google 商家中心提供的代码实现的。

<script src="https://apis.google.com/js/platform.js?onload=renderBadge" async defer></script>
<script>
    window.renderBadge = function () {
        var ratingBadgeContainer = document.createElement("div");
        document.body.appendChild(ratingBadgeContainer);
        window.gapi.load('ratingbadge', function () {
            window.gapi.ratingbadge.render(ratingBadgeContainer, { "merchant_id": MERCHANT_ID, "position": "BOTTOM_RIGHT" });
        });
    }
</script>
<script>
    window.___gcfg = {
        lang: 'en_US'
    };
</script>

在 IIS 中,这就是我的访问控制策略:

<httpProtocol>
<customHeaders>
  <remove name="X-Powered-By" />
  <add name="Access-Control-Allow-Origin" value="*" />
  <add name="Access-Control-Allow-Headers" value="Content-Type" />
  <add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS" />
</customHeaders>

如果我尝试添加以下内容,我会在开发工具中收到大量错误:

<add name="Content-Security-Policy"
  value="script-src 'self' apis.google.com api.addressy.com maps.googleapis.com
  cdn.jsdelivr.net code.jquery.com www.googletagmanager.com;" />

这是错误之一:

内容安全策略:页面的设置阻止了自身资源的加载(“script-src https://mydomain.com.au https://apis.google.com https://api.addressy.com https:// /maps.googleapis.com https://cdn.jsdelivr.net https://code.jquery.com https://www.googletagmanager.com ”)。来源:DIV 元素的 onchange 属性。

更新

更新的变通方法因此,由于我无法解决此问题,因此我想出了一个变通方法。由于错误正在阻止其他 javascript 运行(在引发错误后执行),我已将 google 客户评论代码移至页面的最底部。所以这是运行的最后一点 javascript。这样,如果它给出错误并不重要,因为该站点仍然可以运行。

我还检查浏览器是否是 safari,如果是,我不渲染徽章。这不是一个理想的解决方案,因为现在 safari 浏览器中缺少徽章,但这是我得到的最好的解决方案,直到我弄明白为止。

var isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);

window.renderBadge = function () {
    if (!isSafari) {
        var ratingBadgeContainer = document.createElement("div");
        document.body.appendChild(ratingBadgeContainer);
        window.gapi.load('ratingbadge', function () {
            window.gapi.ratingbadge.render(ratingBadgeContainer, { "merchant_id": MERCHANT_ID, "position": "BOTTOM_RIGHT" });
        });
    }
}
4

0 回答 0