由于 cookie 的“SameSite”和“安全”设置,Google Analytics 在 IFrame 中被阻止

sua*_*kim 2 javascript cookies iframe google-analytics samesite

我们在 上运行服务our-site.com。我们的客户可以通过简单地从 链接their-site.comour-site.com/customer-service或通过 iFrame 将我们的服务嵌入到their-site.com. 想象一下直接访问 GMap 与看到它嵌入在 IFrame 中。

使用我们在 IFarme 中的服务访问“外国”页面

从 Chrome 80(我猜)开始,当服务在 iFrame 内运行时,我们的 Google Analytics 停止工作。Chrome 给了我这个(很清楚)的信息:

http://our-site.com/上的跨站点资源关联的 cookie设置为没有该SameSite属性。它已被阻止,因为 Chrome 现在仅在设置了SameSite=None和 的情况下才提供具有跨站点请求的 cookie Secure。您可以在应用程序>存储>Cookies 下的开发人员工具中查看 cookie,并在https://www.chromestatus.com/feature/5088147346030592https://www.chromestatus.com/feature/5633521622188032 上查看更多详细信息。

此外,如果我their-site.com使用our-site.com/customer-service嵌入在 iFrame 中的方式访问,我在 GA 实时概览中看不到任何内容。

如果我手动禁用2层的功能same-site-by-default-cookiescookies-without-same-site-must-be-securechrome://flags和访问their-site.comour-site.com/customer-service嵌入的iFrame我看到在GA实时概览页面访问。

访问我们的服务“独立”

当直接访问our-site.com/customer-serviceGA 时仍然正常工作:

  • 开发工具中没有警告
  • 与 GA 关联的多个 cookie 显示在开发工具 > 应用程序选项卡中
  • 我可以在 GA 实时概览中看到页面访问
  • 两个 cookie 都没有设置SecureSameSite值(全部为“空白”)...

在外部域上的 iFrame 内运行时,我可以做些什么来使 GA 再次工作?

示例代码

我刚刚创建了一个非常简单的测试环境,它也显示了上述问题:

our-site.com/customer-service

<html lang="en">
  <head>
    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async src="https://www.googletagmanager.com/gtag/js?id={tracking-id}"></script>
    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag() { dataLayer.push(arguments); }
      gtag("js", new Date());
      gtag("config", "{tracking-id}");
    </script>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>our site service</title>
  </head>
  <body>our-site.com/customer-service</body>
</html>
Run Code Online (Sandbox Code Playgroud)

他们的网站

<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>their-site.com</title>
  </head>
  <body>
    <iframe src="https://www.our-site.com/customer-service" style="width: 500px; height: 500px;"></iframe>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

即使是这个非常简单的示例也显示了上述行为,其中our-site.com/customer-service直接打开,在 GA 实时概览中显示数据,而打开their-site.com不...

sua*_*kim 8

来自Google 标签管理器支持论坛的回答:

_ga第三方上下文(iframe)中访问第一方 cookie ( ) 时,必须显式添加cookieFlagsvalue samesite=none;secure

可以在此博客文章中找到各种场景的详细说明。

  • 以防有人懒得阅读链接 ```gtag('config', '{tracking-id}',{ cookie_flags: 'secure;samesite=none' })``` (3认同)
  • 此答案适用于 _analytics.js_,奥利弗的评论适用于 _gtag.js_。如果您使用 GTM(和 GA4),则需要将配置标记的“cookie_flags”字段设置为“secure;sameSite=none”。 (3认同)