When the user jumps to another page, use JavaSpript to send data to the server

Use JavaScript to handle the data sending when the user page jumps

Photo by Edho Pratama on Unsplash

As a developer, you may encounter such a scenario: on the PC side, the browser needs to monitor whether the user jumps to a new page? Or toggled/closed Tab? Or did you shrink/close the browser? Or on the mobile side, monitor whether the user switches from the browser to another app. In this article, we will study how to determine whether the content on the Tab is displayed or hidden, and then send the analysis data to the server.

Monitor page changes

The visibilitychange event can be used to record the show/hide behavior of the tab page. This event is available in all modern browsers and can be called directly through the document document.addEventListener('visibilitychange', ... ) object .

Calling the visibilitychange method can only get two possible values: visible (displayed) and hidden (hidden).

If the value of the visibilitychangeevent becomes hidden, it may mean that the user is leaving the page. Access the document.visibilityState variable in to get the current specific page visibility state).

document.addEventListener('visibilitychange', function() {
  if (document.visibilityState === 'hidden') {
    // user session ended
  }
});
复制代码

In addition, if the result of calling the visibilitychange event is visible, it means that the user has returned to the current page.

document.addEventListener('visibilitychange', function() {
  if (document.visibilityState === 'visible') {
    // user is back
  }
});
复制代码

There is an event handler called onvisibilitychange that can be used to listen for changes to the show or hide properties of the visibilitychange method.

document.onvisibilitychange = function() {
  // visibility of page has changed
};
复制代码

Send analysis data to the server

Web APIs provide a navigator object that contains the sendBeacon() method. The sendBeacon() method allows us to send small amounts of data to the server asynchronously.

The sendBeacon method accepts two parameters:

  1. Url : Relative or absolute URI to which the data will be received.
  2. Data : An object containing data that acts on the server.

第二个参数 data 接收的数据类型有 ArrayBuffer, ArrayBufferView, Blob, DOMString, FormData 或者 URLSearchParams

如果数据成功发送到指定的 url 进行数据传输, sendBeacon() 会返回 true。否则,就会返回 false 。

和其它传统技术(像 XMLHttpRequest)相比, sendBeacon 方法是一种更好的发送分析数据的方式。因为通过 XMLHTTPRequest 发送的请求在页面未被加载时会被取消,而 sendBeacon 确保了在给服务器发请求时不被打断。

通过 sendBeacon 方法发送的请求会被用户代理存储在队列中,这也就意味着只要网络是可用的,即使用户关闭了 App,数据最终也会被传输。

当 visibilityState 的值变为 hidden 时,(开发者)就可以调用 sendBeacon 方法把分析数据发送给服务端。

代码实现如下:

document.addEventListener('visibilitychange', function() {
  if (document.visibilityState === 'hidden') {
    navigator.sendBeacon('/analyticslog', data);
  }
});
复制代码

想了解更多的信息,请参考以下 Mozilla 文档:

If you find errors in the translation or other areas that need to be improved, please go to the Nuggets Translation Program to revise and PR the translation, and you can also get corresponding reward points. The permalink to this article at the beginning of the article is the MarkDown link to this article on GitHub.


The Nuggets Translation Project is a community that translates high-quality Internet technical articles. The source of the articles is the English sharing articles on Nuggets. The content covers Android , iOS , front-end , back- end , blockchain , products , design , artificial intelligence and other fields. If you want to see more high-quality translations, please continue to pay attention to the Nuggets translation plan , official Weibo , and Zhihu column .

Guess you like

Origin juejin.im/post/7084175187511345183