3

可能重复:
如何在 javascript onbeforeunload 事件中获取目标 URL?

有没有办法从 onunload 事件中识别待处理的导航 uri?我想根据用户在页面上导航的位置(特定链接、后退导航、刷新等)采取特定操作。是否有更好的方法来处理任务?

为了做到包罗万象,我避免向链接添加侦听器,同样不想使用 popstate、hashchange 等。onunload 似乎是捕捉几乎任何场景的最简单方法,但我没有能够找到一种方法来查看在此范围内将加载新页面的位置。可以做到吗?


正如评论中提到的,我不完全同意这是上面帖子的副本。我绝对不认为它应该被关闭,因为现在没有人能提供任何答案,包括我自己。无论如何,这是我使用的解决方案:

$(document).ready(function() {
    var newUri;
    $(document).on("click", "*", function(e) {
        var thisElement = $(this)[0];
        if (thisElement.onclick) {
            // Handle special case situations.
        }
        if (thisElement.href) {
            newUri = thisElement.href;
            console.log(thisElement);
        }
    });
    window.onbeforeunload = function(e) {
        console.log("Client navigating to "+newUri);
        // Perform final handling steps.
    };
});
4

0 回答 0