【发布时间】:2019-03-28 16:51:49
【问题描述】:
我需要在窗口卸载时使用navigator.sendBeacon(),以便让我的服务器知道客户端已经关闭了他的窗口。我到处搜索,但它对我不起作用。
供参考,this post 中的解决方案也不起作用。
我有一个包含整个项目的 App 组件。我正在尝试在它的 componentDidMount() 生命周期方法上设置卸载事件,但它不会触发。
componentDidMount() {
window.addEventListener("beforeunload", this.unload);
}
componentWillUnmount() {
window.addEventListener("beforeunload", this.unload);
}
unload(e) {
e.preventDefault();
e.returnValue = 'test';
navigator.sendBeacon(`http://localhost:8080/window-closed/${this.props.username}`);
return 'test';
}
我希望服务器能够获得 AJAX 调用,并且窗口会在窗口关闭之前提示用户“测试”。实际发生的是窗口像往常一样关闭。
注意:return 'test' 和 e.returnValue = '' 语句纯粹用于测试。我只对 AJAX 请求感兴趣。
任何帮助将不胜感激。
【问题讨论】:
-
你能提供一个codeandbox吗?
-
尝试将
unload(e) {更改为unload = (e) => { -
很遗憾,这没有用:/ @GabrielePetrioli
标签: javascript ajax reactjs dom-events