开发者

Canceling a back or forward event that causes a hash change or an HTML 5 history change

Is it possible to cancel a browser back or forward event that causes a hash change or an HTML 5 history change in the same way that one can cancel a开发者_Python百科 page-loading back or forward event through window.onbeforeunload?


I don't know if it helps in your situation but Sammy.js, a popular hash-routing library, has a before handler. I've used it in my application to record the previously accessed hash, and if it's the hash I want to stop them from leaving, return false will keep them on that page. You still need to rewrite the URL to display the previous page, but it seems to be working. Here's a little sample of what I did:

app.before(function (context) {
    if (context.path === lastRoute) return false; // Was fired from our app.setLocation below.
    if (lastRoute === "/#MyHashWhereIFirstWantToConfirm") {
        if (!confirm("Are you sure you wish to leave this page?")) {
            app.setLocation(lastRoute); // Send them back to /#MyHashWhereIFirstWantToConfirm
            return false; // Keep the handler for the destination page from firing.
        }
    }
    lastRoute = context.path;
    return true;
});

Used in conjunction with window.onbeforeunload you could pretty well keep the user from leaving the page without a confirmation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜