1

In my script I need to execute window.close();, but it has a chance of failing (Note: See below for explain), so I want to follow up the window.close(); with a window.history.back(), which will redirect user back a page and back to the correct web flow.

I have tried the following:

Code 1

window.close();
window.history.back();

The above worked all the time, however if I do this:

Code 2

window.close();
alert("123");
window.history.back();

The alert go before window can even close. So let me wonder if Code 1 is a safe code to use.

So I have the following question:

  • Is it safe to assume that in Code 1, window.close() will always run before window.history.back()?

    • and only in the case that window.close() is not permitted, only then window.history.back() will get called?
  • If not, then is it possible to detect the event of window.close() not being called? So I can proceed from that and execute the code I want

Note:

  • The code is being run on multiple platform, and I find that in iOS10 SFSafariViewController, it does not know window.close() due to some reason, hence I need to call window.history.back() after knowing that window.close() failed

Thanks!

Ng Sek Long
  • 4,233
  • 2
  • 31
  • 38

2 Answers2

0

I found something here which explains it in detail, but essentially the answer is you can't. The best you can do is detect the unload events using onunload and onbeforeunload. Try using these, and see what happens.

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
0

Did you considered adding a try.. catch block?

try {
window.close();
}
catch(error) {
console.error(error);
// Note - error messages will vary depending on browser
}

Documentation

Wimanicesir
  • 4,606
  • 2
  • 11
  • 30
  • This doesn't seem to work in Chrome (March 2022). If you try the linked sample code and put in `window.close()`, the catch is never run! – Glen Little Mar 22 '22 at 20:24