I need a message script that will only e up when people are leaving the current webpage and not the current website.
When people are leaving the website entirely, the message will e 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?
I need a message script that will only e up when people are leaving the current webpage and not the current website.
When people are leaving the website entirely, the message will e 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?
Share Improve this question edited Oct 26, 2012 at 10:12 Arnold Zokas 8,5806 gold badges54 silver badges78 bronze badges asked May 27, 2010 at 12:49 tumtummetjestumtummetjes 911 gold badge1 silver badge2 bronze badges 2- ps my webiste consolepro which profides nintendo wii softmod soft mod does have a script which generate the link automaticly – tumtummetjes Commented May 27, 2010 at 13:43
- Possible duplicate of Display a warning when leaving the site, not just the page – KyleMit ♦ Commented Apr 13, 2017 at 12:34
3 Answers
Reset to default 6Check 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.">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;
});
});
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>
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');
});