簡體   English   中英

如何在后退按鈕點擊時警告用戶?

[英]How can I warn user on back button click?

www.example.com/templates/create-template

如果他們離開create-template頁面,我想警告用戶。 我的意思是他們是去另一個頁面還是templates


我使用此代碼警告用戶重新加載頁面並在表單變臟時路由更改。

 function preventPageReload() { var warningMessage = 'Changes you made may not be saved'; if (ctrl.templateForm.$dirty && !confirm(warningMessage)) { return false } } $transitions.onStart({}, preventPageReload); window.onbeforeunload = preventPageReload 

如果通過單擊菜單或手動更改頁面重新加載和路由更改,它將按預期工作。 但是,當我單擊后退按鈕時,它不會觸發警告。 只有當我第二次單擊后退按鈕,重新加載頁面或手動更改路徑時才會這樣做。

我正在使用ui-router 單擊back按鈕時,您將從app.templates.create-template狀態轉到app.templates狀態。

如果按回按鈕怎么警告?

首先,你錯了:

來自https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload

Note: To combat unwanted pop-ups, some browsers don't display prompts
created in beforeunload event handlers unless the page has been interacted 
with; some don't display them at all. For a list of specific browsers, see the 
Browser_compatibility section.

window.onbeforeunload = funcRef
  • funcRef是對函數或函數表達式的引用。
  • 該函數應將字符串值賦給Event對象的returnValue屬性並返回相同的字符串。

您無法在onbeforeunload打開任何對話框。

因為你不需要onbeforeunload的確認對話框。 如果函數在您嘗試離開頁面時返回的值不是nullundefined ,瀏覽器將為您執行此操作。

現在,只要您在同一頁面上, onbeforeunload就不會觸發,因為從技術上講,您仍然在同一頁面上。 在這種情況下,您需要一些在狀態更改之前觸發的函數,您可以在其中放置確認對話框。

如何執行此操作取決於您使用的路由器。 我在我當前的項目中使用ui-router,我在uiCanExit函數中進行了檢查。


編輯

您可以將preventPageReload保持為角度狀態更改。 但是當用戶輸入新地址或嘗試通過鏈接等離開頁面時,您需要一個不同的功能。

例:

window.onbeforeunload = function(e) {
  if (ctrl.templateForm.$dirty) {
    // note that most broswer will not display this message, but a builtin one instead
    var message = 'You have unsaved changes. Do you really want to leave the site?';
    e.returnValue = message;
    return message;  
  }
}

但是,你可以使用如下:(使用$transitions

$transitions.onBefore({}, function(transition) {
    return confirm("Are you sure you want to leave this page?");
});

使用$transitions.onBefore代替$transitions.onStart

希望這可以幫到你。 我還沒有測試過解決方案。 這個也可以幫到你。

暫無
暫無

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

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