出于安全原因,我们需要从应用程序的内容安全策略 header 中删除 unsafe-eval
。但删除它后,我们收到一个控制台错误:
call to eval() or related function blocked by CSP
我们也在script-src
中添加了“https://www.googletagmanager.com”域,但仍然提示错误。
是否有办法只允许 Google 跟踪代码管理器域使用 unsafe-eval
?或者还有其他选择吗?
下面是我们在脚本中使用的示例分析代码片段
(function (w, d, s, l, i) {
w[l] = w[l] || []; w[l].push({
'gtm.start':
new Date().getTime(), event: 'gtm.js'
}); var f = d.getElementsByTagName(s)[0],
j = d.createElement(s), dl = l != 'dataLayer' ? '&l=' + l : ''; j.async = true; j.src =
'//www.googletagmanager.com/gtm.js?id=' + i + dl; f.parentNode.insertBefore(j, f);
})(window, document, 'script', 'dataLayer', 'GTM-123456');
最佳答案
根据this Lunametrics article GTM 使用 eval 来自定义 JavaScript 变量:
[...] your scripts may execute a little more slowly as a result, since there will now be an additional eval() for the Custom JavaScript Variable that you are passing your arguments to
事实上,当我将自定义 JS 变量添加到之前没有任何变量的容器时,将以下代码添加到 gtm.js 文件中:
// Copyright 2012 Google Inc. All rights reserved.
// Container Version: QUICK_PREVIEW
(function(w,g){w[g]=w[g]||{};w[g].e=function(s){return eval(s);};})(window,'google_tag_manager');(function(){
var __c;__c=function(a){return a["39"]};__c.a="c";__c.b=["google"];__c.isVendorTemplate=!0;
(请注意注释后第一行中 eval 的使用)。
因此,我怀疑如果您可以不使用自定义 JavaScript 变量,那么删除 unsafe-eval 可能会起作用。
关于security - 从 CSP header 中删除 unsafe-eval 后,Google 跟踪代码管理器控制台出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41340237/