gpt4 book ai didi

javascript - Google Analytics,跟踪页面卸载事件

转载 作者:可可西里 更新时间:2023-11-01 02:37:48 25 4
gpt4 key购买 nike

我正在尝试在用户使用 Google Analytics (analytics.js) 离开页面时完成跟踪事件。虽然不知道用户将如何离开,但可能是因为外部链接或只是关闭标签。所以我的想法是 Hook beforeunload 或 unload 事件,然后:

window.addEventListener("beforeunload", function() {
ga('send', 'event', 'some', 'other', 'data');
});

现在我的问题是,对 GA 服务器的请求是同步的还是我可以用 hitCallback 以某种方式强制执行该行为?属性(property)?如果那不可能,我还能如何实现这一目标?最好不必为用户设置超时或固定等待时间!

最佳答案

有一种方法可以确保将请求发送到 GA。 Simo Ahava 写了一篇非常好的博客文章,标题为 -
"Leverage useBeacon And beforeunload In Google Analytics "。

利用辉煌sendBeacon解决方案。这是解决这个问题的选定答案的引述:

User agents will typically ignore asynchronous XMLHttpRequests made in an unload handler. To solve this problem, analytics and diagnostics code will typically make a synchronous XMLHttpRequest in an unload or beforeunload handler to submit the data. The synchronous XMLHttpRequest forces the User Agent to delay unloading the document, and makes the next navigation appear to be slower. There is nothing the next page can do to avoid this perception of poor page load performance.

There are other techniques used to ensure that data is submitted. One such technique is to delay the unload in order to submit data by creating an Image element and setting its src attribute within the unload handler. As most user agents will delay the unload to complete the pending image load, data can be submitted during the unload. Another technique is to create a no-op loop for several seconds within the unload handler to delay the unload and submit data to a server.

Not only do these techniques represent poor coding patterns, some of them are unreliable and also result in the perception of poor page load performance for the next navigation.

关于javascript - Google Analytics,跟踪页面卸载事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23479644/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com