[英]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
您無法在onbeforeunload
打開任何對話框。
因為你不需要onbeforeunload
的確認對話框。 如果函數在您嘗試離開頁面時返回的值不是null
或undefined
,瀏覽器將為您執行此操作。
現在,只要您在同一頁面上, 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.