[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 502
  • Last Modified:

window.onbeforeunload url exception

Hi everyone,

I have a page which shows a confirm message when the user tries to leave it, using window.onbeforeunload.

Now I only want it to fire if the url the user is going to is not on my domain. i.e. he'll only get it when trying to close the tab/window or surfing to a different website, but not when reloading my page.

TIA!
0
Feivi99
Asked:
Feivi99
  • 3
  • 2
2 Solutions
 
wht1986Commented:
I dont think the javascript knows the URL of where it is going to. All I can think of is to use a javascript variable to track if it is ok to leave or not.

var isOkToLeave = false;

function MyBeforeUnloadEvent()
{
    if (!isOkToLeave )
           return confirm('do you really want to leave?');
}


then in all your code for every button or hyperlink have some client event that sets this to true.

<asp:Button .... OnClientClick="isOkToLeave=true;" .. />

This way you are telling the onbeforeclose event that it is ok to leave, otherwise hitting the back button on the browser, typing a new URL, etc, will cause the confirm dialog to be presented
0
 
Feivi99Author Commented:
wht, that worked pretty nicely. The only thing that's missing for me is to keep it from happening when the user clicks the browser's "reload" button. Any way you can think of doing that?
0
 
wht1986Commented:
sorry to take so long to get back to you. (2) things:

(1) obviously I'm sure you realized my error above  the function should have been something like

 function MyBeforeUnloadEvent() {
    if (!isOkToLeave)
        return 'Any unsave changes will be discarded.';
}

Guess I spazzed out above with an extra confirm message in the function. no need for that because return a string force the browser to prompt the user as it is

(2) unfortunetly i know of no way to tell a reload request (f5) apart other toolbar based actions that would cause the onbeforeunload event to trigger
0
 
wht1986Commented:
Feivi99,
since that worked ok for you above, could you accept the solution please. Thanks - KW
0
 
Feivi99Author Commented:
Sorry for the delay.
0

Featured Post

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now