I want to show alerts for the following events:
- Page onLoad
- Page Refresh
- Before Close
I want to show alerts for the following events:
Use alert
for load , and return
statement for unload and refresh
below the used code .
// 1-Page Load
window.onload = function() {
alert("Page loaded");
//disable unload message when clicking on links (<a>)
var links = document.getElementsByTagName("a");
for (var i = 0; i < links.length ; i++) {
links[i].addEventListener("click",function(){
window.onbeforeunload = null;
})
}
}
// 2-Page Refresh or 3-Before Close
window.onbeforeunload = function() {
return "Page unloaded !";
}
<a href="#">link</a>
Add this to your <head>
tag, you can pick between onbeforeunload
and onunload
, which ever you prefer. Although onunload
also gets triggered, when you close the tab / browser.
The window.alert
triggers, when the page is loaded.
This is it:
<script type="text/javascript">
window.alert("alert!");
window.onunload = function (){
alert("onunload alert");
};
window.onbeforeunload = function (){
alert("onbeforeunload alert");
};
</script>