0

i'm trying to do something similar to some websites where you leave and it'll display a popup saying "Are you sure you want to leave this page" and with two options saying "Cancel" and "OK".

How would I do that and make it so when you click "Cancel" it'll just cancel the box and when they click "OK" it'll do a 'leaveChat();' function and leave the website?

I've tried using the onbeforeunload which was working but i'm not sure on the function part.

Thanks for the help!

user1783703
  • 1
  • 2
  • 2
  • 1
    possible duplicate of [How to show the "Are you sure you want to navigate away from this page?" when changes committed?](http://stackoverflow.com/questions/1119289/how-to-show-the-are-you-sure-you-want-to-navigate-away-from-this-page-when-ch) – Alex Kulinkovich Feb 19 '15 at 08:56

3 Answers3

0

There is no way to do that.

You can try sending the AJAX request in onunload, but I don't think that will work reliably.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
0

To pop a message when the user is leaving the page to confirm leaving, you just do:

<script>
    window.onbeforeunload = function(e) {
      return 'Are you sure you want to leave this page?  You will lose any unsaved data.';
    };
</script>

To call a function:

<script>
    window.onbeforeunload = function(e) {
       callSomeFunction();
       return null;
    };
</script>
OG Sean
  • 971
  • 8
  • 18
  • The browser will handle the user's click and decide to leave the page or stay on. No browser that I know of gives you the control to keep the user on the page and not let them leave. – OG Sean Jun 09 '13 at 01:07
0

here is my html

<!DOCTYPE HMTL>
<meta charset="UTF-8">
<html>
<head>
<title>Home</title>
<script type="text/javascript" src="script.js"></script>
</head>

 <body onload="myFunction()">
    <h1 id="belong">
        Welcome To My Home
    </h1>
    <p>
        <a id="replaceME" onclick="myFunction2(event)" href="https://www.ccis.edu">I am a student at Columbia College of Missouri.</a>
    </p>
</body>

And so this is how I did something similar in javaScript

var myGlobalNameHolder ="";

function myFunction(){
var myString = prompt("Enter a name", "Name Goes Here");
    myGlobalNameHolder = myString;
    if (myString != null) {
        document.getElementById("replaceME").innerHTML =
        "Hello " + myString + ". Welcome to my site";

        document.getElementById("belong").innerHTML =
        "A place you belong";
    }   
}

// create a function to pass our event too
function myFunction2(event) {   
// variable to make our event short and sweet
var x=window.onbeforeunload;
// logic to make the confirm and alert boxes
if (confirm("Are you sure you want to leave my page?") == true) {
    x = alert("Thank you " + myGlobalNameHolder + " for visiting!");
}
}