簡體   English   中英

Javascript onbeforeunload 打開 window.open() 彈出窗口

[英]Javascript onbeforeunload to open window.open() popup

我正在嘗試編寫一個觸發 window.open(url) 等的 onbeforeunload 事件。我希望它在用戶嘗試離開頁面或關閉瀏覽器時觸發,但在他們單擊任何按鈕時不會觸發這一頁。 頁面上的按鈕通過 javascript 將數據發布到同一頁面。

javascript:

window.onbeforeunload = doSync;

function doSync(){
   if(doSync == true){
       //do sync via popup
       window.open("http://mydomain.com/page.php?var=<?php=sync_var?>", "Synchronizing cluster....", "location=0,menubar=0,statusbar=1,width=10,height=10");
   }
   else {
     //somehow do nothing and allow user to leave

   }
}
-->
</script>

這些按鈕調用 javascript function 創建並提交表單。 在那個 javascript function 我設置了doSync = false的全局變量。 我將包括這個 function 的基本代碼只是為了說明它。

function buttonPush(){
   var form = document.createElement('form');
   form.setAttribute('method' bla bla

   //before submit set dosync to false
   doSync = false;

   form.submit();
}

現在我在window.onbeforeunload = doSync上收到一個Not Implemented錯誤; 陳述。

任何幫助,將不勝感激。

謝謝,

吉姆

是不是我的window.open有問題? 如果我執行window.open('','','height=100,width=100');

它可以正常打開,但下面沒有。

window.open('https://mydomain.com/support/sync_cluster.php?sync_cluster=mycluster','Synchronizing...', 'toolbar=0,scrollbars=0,location=0,statusbar=1,menubar=0,resizable=0,width=100,height=100');

doSync 是 function,不是 boolean; 只需創建一個變量並適當地設置它:

var sync = true;
window.onbeforeunload = doSync;

function doSync() {
  if (sync == true) {
    //do sync via popup
    window.open("http://mydomain.com/page.php?var=<?php=sync_var?>", "Synchronizing cluster....", "location=0,menubar=0,statusbar=1,width=10,height=10");
  }
  else {
    //somehow do nothing and allow user to leave
    return;
  }
}
function buttonPush(){
   var form = document.createElement('form');
   // form.setAttribute('method' bla bla

   //before submit set dosync to false
   sync = false;

   form.submit();
}

試試這個:

 var vals = 0; function displayMsg() { window.onbeforeunload = null; window.location = "https://www.google.com"; } 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()", 500); if (vals > 0) { displayMsg(); clearTimeout(t); } } $(document).ready(function() { $('a,input,button').attr('onClick', 'window.onbeforeunload = null;') });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <a href="https://en.wikipedia.org/wiki/Frame_(World_Wide_Web)">Leave</a>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM