我有一个使用 SSR 的 Vue 应用程序。为了实现 Content-Security-Policy,我使用 nonce-aware version of GTM snippet .
但它没有添加 nonce
到由 gtm 注入(inject)页面的所有脚本(特别是自定义 HTML 标记)。我遵循了提到的解决方案 here它解决了 Safari 上的问题。但它不适用于 Chrome , 火狐 , 或 边我仍然看到这些标签的错误:
这是我的 CSP 设置:
default-src 'self';
base-uri 'self';
block-all-mixed-content;
font-src 'self' https: https://fonts.gstatic.com data:;
img-src 'self' https: data: https://www.google-analytics.com https://ssl.gstatic.com https://www.gstatic.com https://www.googletagmanager.com;
object-src 'none';
script-src 'self' 'nonce-b62382357618aee340fc9dc596c94a19' https://www.google-analytics.com/ https://ssl.google-analytics.com https://tagmanager.google.com https://www.googletagmanager.com 127.0.0.1:*;
script-src-attr 'none';
style-src 'self' 'unsafe-inline' https://tagmanager.google.com https://fonts.googleapis.com;
upgrade-insecure-requests;
connect-src 'self' https://www.google-analytics.com https://stats.g.doubleclick.net;
经过数小时的研究,我发现了以下评论:Chrome masks the nonce attribute value so tag manager is unable to grab it and store it as a variable.
我不确定这是否真的是问题,但谁能解释我如何在不使用
unsafe-inline
的情况下解决此问题或哈希,因为即使在谷歌文档上似乎也没有标准的方法来修复它?
最佳答案
在网上搜索了很多并阅读了不同的文章后,我找到了提到的解决方案here在 Safari 中运行良好,但在其他浏览器中运行良好,因为:
Chrome, Safari, and Edge mask the nonce attribute value so GTM is unable to grab it and store it as a variable.
考虑 this solution用于传播
nonce
对于自定义 HTML 标签,我们继续应用以下更改来解决 Chrome、Firefox 和 Edge 上的此问题。如建议 here in the comments我们需要稍微修改一下 nonce-aware 脚本并将 nonce 放入
data-
属性(然后浏览器不会屏蔽它),并将其推送到数据层:<!-- Google Tag Manager -->
<script
nonce='{{YOUR_GTM_NONCE}}'
data-gtm-nonce='{{YOUR_GTM_NONCE}}'
>
(function(w,d,s,l,i){
const gtmNonce = d.querySelector('[data-gtm-nonce]').dataset.gtmNonce;
w[l]=w[l]||[];
w[l].push({'nonce': gtmNonce});
w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});
const f=d.getElementsByTagName(s)[0],j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';
j.async=true;
j.src='https://www.googletagmanager.com/gtm.js?id='+i+dl;
j.setAttribute('nonce', gtmNonce);
f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','YOUR_GTM_ID');
</script>
<!-- End Google Tag Manager -->
然后在GTM中,你需要根据this solution更改你定义的nonce变量从此 :到这个 :
其余的将保持不变。
关于google-chrome - GTM nonce-aware 脚本不适用于自定义 HTML 标记的所有浏览器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66598175/