使用窗口的卸载事件,可以向用户显示一个确认对话框,假设有正在等待完成的持续请求的情况,导航离开页面将终止该请求。
有没有办法通过onpopstate的HTML5历史API实现这一目标?或者任何其他具有相同结果的方式?
答案 0 :(得分: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);
}
};
答案 1 :(得分:0)
我不知道它是否对你的情况有帮助,但Sammy.js,一个流行的哈希路由库有一个before处理程序。我已经在我的应用程序中使用它来记录以前访问过的哈希值,如果是哈希,我想阻止它们离开,返回false会将它们保留在该页面上。您仍然需要重写URL以显示上一页,但它似乎正在工作。
有关详细信息,请参阅my answer in this other thread。