Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OnUnload message needed for external links

I need a message script that will only come up when people are leaving the current webpage and not the current website.

When people are leaving the website entirely, the message will come up and they will need to press the OK button to stay at the current page (and cancel to leave the website).

The script may not run when people actually stay on the website or when they click on internal links or pages.

Can this be done?

like image 717
tumtummetjes Avatar asked May 27 '10 12:05

tumtummetjes


People also ask

What triggers Onbeforeunload?

The beforeunload event is fired when the window, the document and its resources are about to be unloaded. The document is still visible and the event is still cancelable at this point. This event enables a web page to trigger a confirmation dialog asking the user if they really want to leave the page.

How can I be alerted when someone leaves my page?

The onbeforeunload event fires when the document is about to be unloaded. This event allows you to display a message in a confirmation dialog box to inform the user whether he/she wants to stay or leave the current page. The default message that appears in the confirmation box, is different in different browsers.


3 Answers

Check out this very basic example solution. It sets the onbeforeunload handler but then removes it if the user clicks an internal link. Below is a generic version of the code from the example solution.

HTML:

<a href="internal_link.html">internal link</a>
<a href="http://www.example.com">external link</a>

JS (uses jQuery):

window.onbeforeunload = function(){
    return "Are you sure you want to leave our website?";
}
$(function(){
    $('a, input, button').click(function(){
            window.onbeforeunload = null;
    });
});
like image 121
Adam Avatar answered Nov 11 '22 12:11

Adam


I got a similar problem. However in my case this message was supposed to be translated according with the user's language, if anyone presses F5 or close the window.

Follow my small example.

<html>
<head>
<script type="text/javascript">
function closeThis()
{
    if (window.confirm("Minha mensagem!")){
        window.close();
    }
}

function test() 
{
    // Add a warning in case anyone tries to navigate away or refresh the page
    return confirm("Minha mensagem");
}


</script>
</head>
<body onbeforeunload=test();>
<p>Hello World! Press F5 or Close this Window</p>
</body>
</html>
like image 42
user1167630 Avatar answered Nov 11 '22 14:11

user1167630


In most cases you don't need a popup for all events except the one: user closes the window.

Here is my solution for this:

$(window).on('beforeunload', function() {
    /* whatever you want here */
}   

$(document).on('click keydown', function(){
    $(window).off('beforeunload');
});
like image 1
vchik Avatar answered Nov 11 '22 14:11

vchik