如何在关闭窗口前发送 HTTP 请求并在本地存储中设置项目

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

我想跟踪我的网站使用情况,所以我在网站打开时设置开始时间ending time 当窗口关闭并将它们存储在 localStorage 中,以了解一个人是否多次访问过。使用这些时间戳,我想找到在我的网站上花费的时间

关闭窗口时,我想保存在本地存储中并将API请求发送到firebase以保存数据。

但是使用 useEffect,我无法在关闭窗口时存储在本地存储中并发送 API 请求

我用过beforeunload eventListener,这个也没用。

我该怎么办?

useEffect(()=>{

 /*
   {
      IP, location, starting time after mounting 
   }
*/

 const unload = async (e) => {
      e.preventDefault();

      const end = moment().toString();
      this.localStorage.setItem("end", JSON.stringify(end));
      const start = JSON.parse(localStorage.getItem("start"));
      const timeSpent= moment(end).diff(start, "second");
      this.localStorage.setItem("timeSpent", timeSpent);

      await addDoc(collectiondata, {
        ip: IP, 
        location: location,
        visits: [
          {
            start: start,
            end: end,
            timeSpent: timeSpent,
          },
        ],
      });
      return ()=>unload() --- not working
     /*
      window.addEventListener(BeforeUnloadEvent, unload);
      return () => window.removeEventListener(BeforeUnloadEvent, unload); --- not working
      
     return unload() --- this works only for API with an erorr TypeError: destroy is not a function
     return window.removeEventListener(BeforeUnloadEvent, unload) --- this works only for localstorage with an erorr TypeError: destroy is not a function
   */

    
},[])
reactjs firebase react-hooks frontend local-storage
© www.soinside.com 2019 - 2024. All rights reserved.