Search code examples
javascriptonbeforeunload

make onbeforeunload fire for certain subpages


I'm quite new to javascript. I have a simple onbeforeunload function, which currently works for all the pages and I want it to activate for certain subpages (#clients, #products, #news) , but not for the first subpage of my domain (index.html). I'd like to avoid putting the script in each subpage, but rather would like to use conditional statement(s) to detect name of the subpage before the onbeforeunload function triggers. My current code below:

    window.onbeforeunload = function(event) {
           event.returnValue = "You have unsaved work";
    };

I understand that I need to use window.location.href in some way, but haven't figured out yet. I tried to use the code below to get url or each site and then wanted to enter it into a case statement, the url is returned but the code from case doesn't work:

document.getElementById("demo").innerHTML =
    "Page location is " + window.location.href;

Case code:

<script>
var text;
switch (window.location.href) {
    case "http://mydomain/#/clients":
        text = 1;
        break;
    case "http://mydomain/#/products/":
        text = 2;
        break;
    case "http://mydomain/#/news":
        text = 3;
        break;
    default
        text = 4;
        break;
}
document.getElementById("demo").innerHTML = "Number is " + text;
</script>

Thank you


Solution

  • "window.location.href" returns the entire URL, use location.pathname instead. Also, make sure to add the path names (including extension) to the pathsToAddTheScript Array.

    Try this.

    var pathsToAddTheScript = ['clients', 'products'];
    
    if(window.location.pathname in pathsToAddTheScript) {
       window.onbeforeunload = function(event) {
               event.returnValue = "You have unsaved work";
       };
    }