使用事件侦听器在浏览器关闭时通过 React Redux 调用 API 方法'beforeunload'



我有一个React应用程序,我希望在用户关闭浏览器时对API方法进行DELETE调用。因此,我已将其添加到App.js:中

import myReduxAction from "./Redux/Actions/admin/superAdminActions";
componentDidMount() {
...
this.setupBeforeUnloadListener();
}
setupBeforeUnloadListener = () => {
window.addEventListener("beforeunload", (ev) => {
this.methodToCallBeforeUnload();
debugger;
});
};
methodToCallBeforeUnload= () => {
myReduxAction.myActionMethodSynchronous();
}

当浏览器关闭时,我可以在上面的代码中输入一个调试器,它似乎运行得很好。然而,我注意到API方法没有被击中。我的操作方法看起来像这样:

const myActionMethodSynchronous = () => {
debugger;
return function () {
debugger;
try {
myApi.myAPIMethodSynchronous();
} catch (error) {
// Code to handle errors
}
};
};

以及对API的实际调用:

const myAPIMethodSynchronous= () => {
debugger;
return axios.delete(`/MyAPI/myapimethodname/`);
};

我在Action Method中添加了2xdebugger;。一个在return function之上,另一个在下面。第一个被命中,但是第二个(以及api调用中的那个(永远不会被命中。

我是不是错过了一些显而易见的东西。我还有一个连接到这个Action Method的按钮,它似乎工作得很好。我似乎只有在关闭浏览器时才遇到这个问题。

您使用的浏览器/设备是什么?并非所有浏览器都支持onbeforeunload和onunload。例如,此代码:

window.onbeforeunload = function() {
fetch('/api/some_method1', {
method:'GET',
headers: {
'Content-Type': 'application/json'
},
})
}
window.onunload = function () {
fetch('/api/some_method2', {
method:'GET',
headers: {
'Content-Type': 'application/json'
},
})
}

在Chrome和Opera中完全可用(我收到了这两个请求(,在Safari中,我只收到了beforeunload,而且它似乎在iOS上不起作用。

最新更新