反应窗口卸载事件不会触发

Sag*_*ika 7 javascript ajax dom-events reactjs

我需要使用navigator.sendBeacon()窗口卸载,以便让我的服务器知道客户端已关闭他的窗口。我到处搜索过,但它对我不起作用。

作为参考,这篇文章中的解决方案也不起作用。

我有一个应用程序组件来包装我的整个项目。我试图在其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';
}
Run Code Online (Sandbox Code Playgroud)

我希望服务器获得 AJAX 调用,并且窗口在关闭窗口之前提示用户“测试”。实际发生的情况是窗口像往常一样关闭。

注意:return 'test'&e.returnValue = ''语句纯粹用于测试。我只对 AJAX 请求感兴趣。

任何帮助将非常感激。

Pro*_*tay 5

如果您使用的是功能组件,您可以尝试以下操作:

 useEffect(() => {
    window.addEventListener("beforeunload", handleUnload);
    return () => {
      window.removeEventListener("beforeunload", handleUnload);
    };
  }, []);

  const handleUnload = (e) => {
    const message = "o/";
    (e || window.event).returnValue = message; //Gecko + IE
    return message;
  };


Run Code Online (Sandbox Code Playgroud)


小智 2

您应该将其绑定到 unload 方法或将其转换为箭头函数。

暴饮暴食方式

constructor() {
    super();
    this.state = {
      //stuff
    };
    this.unload.bind(this);
  }

  componentDidMount() {
  window.addEventListener("beforeunload", this.unload);
}

componentWillUnmount() {
  window.removeEventListener("beforeunload", this.unload);
}

unload(e) {
  navigator.sendBeacon(`http://localhost:8080/window-closed/${this.props.username}`);
}
Run Code Online (Sandbox Code Playgroud)

箭头函数方式:

  constructor() {
    super();
    this.state = {
      //stuff
    };
  }

  componentDidMount() {
  window.addEventListener("beforeunload", this.unload);
  }

  componentWillUnmount() {
    window.removeEventListener("beforeunload", this.unload);
  }

  unload = (e) => {
    navigator.sendBeacon(`http://localhost:8080/window-closed/${this.props.username}`);
  }
Run Code Online (Sandbox Code Playgroud)

请记住删除事件侦听器componentWillUnmount(您当前正在再次添加它)。