Javascript当我们在Chrome中选择Stay on Page时,如何调用函数

Me *_* 4U 12 html javascript jquery

请在Chrome浏览器中查看我的代码,如果点击刷新,系统会提示您选择2个选项.

  1. 离开这个页面和
  2. 保持此页上

当我点击2.停留在此页面按钮时,它必须激活我的自定义功能displayMsg()

谁能为我提供解决方案?

<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>
Run Code Online (Sandbox Code Playgroud)

Mo *_*ami 7

使用计时器来监听变量变量:

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);
}
}
Run Code Online (Sandbox Code Playgroud)


And*_*y E 5

您可以使用onbeforeunloadonunload事件的组合,在前者中设置计时器并在后者中清除它:

var showMsgTimer;

window.onbeforeunload = function(evt) {
    var message = 'Please Stay on this page and we will show you a secret text.';
    showMsgTimer = window.setTimeout(showMessage, 500);

    evt = evt || window.evt;
    evt.returnValue = message;

    return message;
}

window.onunload = function () {
    clearTimeout(showMsgTimer);
}

function showMessage() {
    alert("You've been trolled!");
}
Run Code Online (Sandbox Code Playgroud)

这是有效的,因为onunload当用户选择留在页面上时,事件永远不会触发.