Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript How to call a function when we choose Stay on Page in Chrome

Please check my code in Chrome Browser, if you hit refresh you will be prompted with 2 options.

  1. Leave This Page and
  2. 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>
like image 827
Me 4U Avatar asked May 16 '12 10:05

Me 4U


1 Answers

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);
}
}
like image 165
M Rostami Avatar answered Oct 13 '22 00:10

M Rostami