侦听 HTML 导航事件

Listening for HTML navigation events

使用 DOM API and/or JQuery,有什么方法可以检测用户何时启动导航事件(例如通过单击 a 元素与有效的 href), 并绑定一个侦听器到它,它将在检索和呈现新的 HTML 页面之前执行?

Javascript onunload() 函数就是你要找的,这里是参考: http://www.w3schools.com/jsref/event_onunload.asp

演示http://jsfiddle.net/se8osjsj/1/

$(window).on("beforeunload", function() {
    // do stuff here
    return "You are leaving this page, are you sure?";
});

或简单地:

window.onbeforeunload = function(event) {
    // do stuff here
    return "You are leaving this page, are you sure?";
};

The onbeforeunload event occurs when the document is about to be unloaded.

This event allows you to display a message in a confirmation dialog box to inform the user whether he/she wants to stay or leave the current page.

The default message that appears in the confirmation box, is different in different browsers. However, the standard message is something like "Are you sure you want to leave this page?". This message cannot be removed.

However, you can write a custom message together with the default message. See the first example on this page.

Note: If the onbeforeunload event is not assigned to the element, you must assign/attach the event on the window object, and use the returnValue property to create a custom message (see syntax examples below).

Note: In Firefox, only the default message will be displayed (not the custom message (if any)).

来源:http://www.w3schools.com/jsref/event_onbeforeunload.asp