Javascript, Can I “redirect” user in onbeforeunload? If cant, how to

后端 未结 4 783
Happy的楠姐
Happy的楠姐 2020-12-06 17:28

Is it possible to redirect to another page when the user closes the browser?

Attempts:

  1. I tried onunload, does not work

    window.onunlo         
    
    
            
相关标签:
4条回答
  • 2020-12-06 18:08

    Your onbeforeunload event needs to return a string (that doesn't equate to false), the browser will include this string in its own message displayed to the user.

    window.onbeforeunload = function(){
            location.assign('http://www.google.com');
            return "go to google instead?";
        }
    

    However, it's going to be really tricky to word your message in a way that the user would be able to understand what to do. And I'm not sure this is robust in every browser, I just tried it in Chrome, it worked, but I ended up with a tab I could not close! I managed to kill it via the Chrome task manager thankfully.

    0 讨论(0)
  • 2020-12-06 18:10

    The simple answer is no. If browsers allowed you to do more with the onbeforeunload/onunload events, this could be used pretty maliciously by anybody.

    0 讨论(0)
  • 2020-12-06 18:11

    It's not without it's faults but it works

    window.onbeforeunload = function(){
            window.open("http://www.google.com","newwindow");
            return "go to google instead?";
    }
    

    This will open a new window as a popup to the address you selected when the user closes the page, though it is limited by any popup blockers the browser may implement.

    0 讨论(0)
  • 2020-12-06 18:15

    If the user is trying to close the browser, then his intentions are pretty clear; he expects that the browser will close. Preventing that from happening, or causing anything else to happen in between the user clicking on 'close' and the browser closing is just a bad idea IMO. Is there a special reason for this? I mean, when I click on the 'close' button I expect that the browser will close, and should anything else happen, I would find that extremely annoying. I think I'm being reasonable enough. Am I? Who knows such things.

    Why don't you try to entice the user to visit the other page in a less intrusive way? Like with a link or a banner?

    0 讨论(0)
提交回复
热议问题