Today, I'm going to show you how to stop your visitor to close window of your site, using JavaScript.
It's useful when they have unfinished processes, or unsaved data, in which they whether accidentally or deliberately clicked on the close button of your page.
It's also useful for your marketing strategy, like one-time offer, final discounts, and so on.
Simple. First, use this following function. Then I'll show you with 3 situations for example.
var askFirst = false;
function preventerOn() {
askFirst = true;
}
function preventerOff() {
askFirst = false;
}
window.onbeforeunload = sureUnload;
function sureUnload() {
if (askFirst)
return "Are you sure you want to exit this page?";
}
</script>
Situation 1, if you want to prevent window closing from the beginning, you may want to use the body tag, like this:
Situation 2, if you want to prevent window closing when your visitor enter something in a form, use it like this:
Situation 3, if you want to prevent window closing before reached an amount of time (i.e: 20 seconds), you may add this one to the script above:
preventerOn();
setTimeout("clear();",20000); // 1000 is for 1 second, so 20000 is for 20 seconds
}
function clear() {
preventerOff();
}
You may need to change in the body tag, from this:
to this:
That's all.
If you have any questions regarding this, please feel free and don't hesitate to ask me through the comment form.
Thank you.