Javascript How to call a function when we choose Stay on Page in Chrome
html, javascript, jquery
Solution
use a timer to listening for change variable :
var vals=0;
function displayMsg() {
alert('my text..');
}
window.onbeforeunload = function evens(evt) {
var message = 'Please Stay on this page and we will show you a secret text.';
if (typeof evt == 'undefined') {
evt = window.event;
}
timedCount();
vals++;
if (evt) {
evt.returnValue = message ;
return message ;
}
trace(evt);
}
function timedCount()
{
t=setTimeout("timedCount()",100);
if(vals>0)
{
displayMsg();
clearTimeout(t);
}
}
Problem
Please check my code in Chrome Browser, if you hit refresh you will be prompted with 2 options. - Leave This Page and - Stay on This Page When I click the 2. Stay on this page button it must activate my custom function displayMsg() Can any one provide me solution? ``` <script type="text/javascript"> function displayMsg() { alert('my text..'); } </script> <script type="text/javascript"> window.onbeforeunload = function(evt) { var message = 'Please Stay on this page and we will show you a secret text.'; if (typeof evt == 'undefined') { evt = window.event; } if (evt) { evt.returnValue = message; return message; } trace(evt); } </script> ```