How to detect the window(new tab) close event?

前端 未结 4 1468
挽巷
挽巷 2020-12-10 09:21

I have one parent page and child page. the child page opened in new tab

I want to show one alert message (The child page is closing), when i close

4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-10 09:52

    You might not be able to do that other than some cookie based methods which is development work arounds like non persistent cookies. Second identifying a page refresh, form based redirect, or back redirect or browser close unload event identification is not direct and is tedious. Recommend not to depend on it.

    you can do some small things before the customer closes the tab. javascript detect browser close tab/close browser but if your list of actions are big and the tab closes before it is finished you are helpless. You can try it but with my experience donot depend on it. Yes, you cannot at this time differentiate back and refresh and close. So no foolproof way of saying whether the child has definitely closed.

    window.addEventListener("beforeunload", function (e) {
      var confirmationMessage = "\o/";
      /* Do you small action code here */
      (e || window.event).returnValue = confirmationMessage; //Gecko + IE
      return confirmationMessage;                            //Webkit, Safari, Chrome
    });
    

    https://developer.mozilla.org/en-US/docs/Web/Reference/Events/beforeunload?redirectlocale=en-US&redirectslug=DOM/Mozilla_event_reference/beforeunload

提交回复
热议问题