2011-12-30 81 views
6

通过窗口的卸载事件,可以向用户显示一个确认对话框,例如,在存在正在等待的正在进行的请求的情况下完成并从页面导航将终止该请求。取消/中止/确认HTML 5状态更改事件(onpopstate)

有没有一种方法可以用HTML5历史API的onpopstate来实现这一点?或者有相同结果的其他方式?

回答

0

我想你可以修改pushState的行为,要求确认推一个新状态之前:

// Store original pushState 
var _pushState = window.history.pushState; 
// Some bad global variable to determine if confirmation is needed 
var askForConfirm = true; 
// Modify pushState behavior 
window.history.pushState = function() { 
    if(!askForConfirm || confirm('Are you sure you want to quit this page ?')) { 
     // Call original pushState 
     _pushState.apply(window.history,arguments); 
    } 
}; 
+0

但是,这并不关心用户导致事件触发的情况(例如通过按下后退按钮) – Mansour 2011-12-30 12:23:28

+0

嗯。那么,也许可以在onpopstate事件上处理这个事情,通过存储之前的状态并在取消时将其推回来......看起来有点棘手。 – 2011-12-31 12:24:54

0

我不知道这是否有助于你的情况,但Sammy.js,一个流行的哈希-routing库有一个before处理程序。我在我的应用程序中使用它来记录先前访问过的散列,如果它是散列,我想阻止它们离开,那么返回false将使它们保留在该页面上。你仍然需要重写URL来显示前一页,但它似乎在工作。

查看my answer in this other thread了解更多信息。