2016-06-13 30 views
0

我已經閱讀並搜索到這個,發現變化(例如,點擊),但不適用於瀏覽器重新加載/刷新工作。Angular UI路由器在刷新/重新加載時用ngSweetAlert替換瀏覽器警報

基本上,我想要的是當用戶在瀏覽器中重新加載,刷新或F5而不是常規的警報確認時,sweetalert對話框會彈出詢問用戶是否想刷新,失去他們查看的任何信息,確定/取消。

在我的控制,我有這樣的:

$scope.$on('$destroy', function() { 
    window.onbeforeunload = undefined; 
}); 

window.onbeforeunload = function (e) { 
    e.preventDefault(); 
    SweetAlert.swal({ 
     title: "I display correctly but....", 
     text: "before page refreshes and do not wait for user to click ok", 
     type: "warning", 
     showCancelButton: true, 
     confirmButtonColor: "#DD6B55",confirmButtonText: "Ok", 
     cancelButtonText: "Cancel", 
     closeOnConfirm: true, 
     closeOnCancel: true }, 
     function(isConfirm){ 
      if (isConfirm) { 
       console.log('do something...') 
      } 
     }); 
    return undefined; 
}; 

$scope.$on('$locationChangeStart', function(event, toState, toParams, fromState, fromParams) { 
    SweetAlert.swal({ 
     title: "I display and wait for the user to click but too late", 
     text: "...after the page refreshes", 
     type: "warning", 
     showCancelButton: true, 
     confirmButtonColor: "#DD6B55",confirmButtonText: "Ok", 
     cancelButtonText: "Cancel", 
     closeOnConfirm: true, 
     closeOnCancel: true }, 
     function(isConfirm){ 
      if (isConfirm) { 
       console.log('do something...') 
      } 
     }); 
}); 

的「window.onbeforeunload」部分負載在正確的時間(在頁面重新加載前/刷新),但不會等待用戶選擇。

的「$範圍。在$(‘$ locationChangeStart’,......」部分負荷太晚了(之後在頁面重載/刷新),但並等待用戶選擇。

除了「$ locationChangeStart 」我也試着‘$ stateChangeStart’和‘$ routeChangeStart’無濟於事。

我缺少什麼,使這項工作?任何幫助或方向將不勝感激。

+0

我很樂意使用SweetAlert2如果它使這更容易... (但是從查看文檔,我不確定它的確如此)。 – purplerice

+0

在我看來,你應該保持本地警報()或確認(),因爲它們被阻止。 Sweetalert等只是一種div /彈出式對話框。所以用戶仍然可以離開頁面而不選擇他是否想要保存他的數據,對吧? –

+0

David Votrubec:謝謝你的迴應。本地警報/確認附帶了允許用戶禁用警報的複選框 - 這是我無法實現的關鍵功能。如果用戶即將失去他們已經構建的內容,我必須始終向他們提供此警報。 – purplerice

回答

0

你不應該覆蓋原生功能alert()confirm() becau如果他們被阻擋,並且他們被阻擋是有原因的。

但如果你真的想這樣做,有可能這樣

/** 
* Definition of global attached to window properties <br/> 
*/ 
    (function() { 
     nalert = window.alert; 
     Type = { 
      native: 'native', 
      custom: 'custom' 
     }; 
    })(); 

/** 
* Factory method for calling alert(). 
* It will be call a native alert() or a custom redefined alert() by a Type param. 
* This defeinition need for IE 
*/ 
    (function(proxy) { 

      proxy.alert = function() { 
      var message = (!arguments[0]) ? 'null': arguments[0]; 
      var type = (!arguments[1]) ? '': arguments[1]; 

      if(type && type == 'native') { 
      nalert(message); 
      } 
      else { 
       // TODO: Call to SweetAlert() 
       document.write('<h1>I am redefiend alert()<br/>Alert say: '+message+'</h1>'); 
      }  
     }; 
    })(this); 

更多關於此這裏 JavaScript: Overriding alert()

相關問題