我需要捕获window.onbeforeunload事件

问题描述 投票:0回答:2

我正在一个需要捕获浏览器关闭事件(unloadbeforeunload)的项目中。为此,我尝试了下面的代码,但是它不起作用。

仅当我打开浏览器控制台窗口(也许只是一秒钟)时,该代码才起作用,但它是必需的,否则它将不起作用。

Example

$(window).on('beforeunload', function(e) {
 $.ajax({
    type: "POST",
    url: "url",
    data : {'value' : 1},
    dataType:'json'
 });
  return false;   
});
javascript jquery onbeforeunload onunload window.onunload
2个回答
0
投票

信标API专为此目的。在页面卸载时发送请求。 https://developer.mozilla.org/en-US/docs/Web/API/Beacon_API

Beacon请求使用HTTP POST方法,并且请求通常不需要响应。确保在页面被卸载之前启动请求,并且这些请求可以完全运行,而无需阻止请求(例如XMLHttpRequest)。

window.onunload = function analytics(event) {
  if (!navigator.sendBeacon) return;

  var url = "https://example.com/analytics";
  // Create the data to send
  var data = "state=" + event.type + "&location=" + location.href;

  // Send the beacon
  var status = navigator.sendBeacon(url, data);

  // Log the data and result
  console.log("sendBeacon: URL = ", url, "; data = ", data, "; status = ", status);
};

0
投票

信标API专为此目的。在页面卸载时发送请求。 https://developer.mozilla.org/en-US/docs/Web/API/Beacon_API

window.onunload = function analytics(event) {
  if (!navigator.sendBeacon) return;

  var url = "https://example.com/analytics";
  // Create the data to send
  var data = "state=" + event.type + "&location=" + location.href;

  // Send the beacon
  var status = navigator.sendBeacon(url, data);

  // Log the data and result
  console.log("sendBeacon: URL = ", url, "; data = ", data, "; status = ", status);
};
© www.soinside.com 2019 - 2024. All rights reserved.