首页 > 解决方案 > 如何在没有用户交互的情况下捕获标签关闭事件

问题描述

基本上我试图在页面关闭时保存一些数据,即使没有用户交互。我试过使用 onbeforeunload 监听器:

window.onbeforeunload = function (event) {
  event.preventDefault();
  const requestData = {
    parameter : 'test',
    step: 2
  };

  fetch('/send-data', {
    method : 'POST',
    headers: new Headers({'content-type': 'application/json'}),
    body : JSON.stringify(requestData)
  })
  return undefined;
};

我曾希望,因为我没有打开一个对话框,所以我能够使用该事件,但它只能通过用户交互来调用。有没有办法在标签/窗口关闭时捕获事件(或任何其他)以发送/保存一些数据?也可以使用 jquery。

标签: javascriptjquerybrowseronbeforeunload

解决方案


推荐阅读