Javascript-获取导航到的URL

Javascript - Get URL being navigated to

本文关键字:URL 导航 获取 Javascript-      更新时间:2023-09-26

有没有办法使用JavaScript的OnUnload()函数来找出用户要导航到的URL?

例如,如果我的代码在page1.html中,并且用户单击指向http://example.com的链接,那么page1.html中的JavaScript代码是否有任何方法可以在页面卸载之前检索URL "http://example.com"并显示/存储它?

如果我使用OnClick通过链接调用函数,我可以做到这一点,但我找不到其他方法。(如果需要,我可以发布我的代码,但它确实符合我的业务要求)

编辑:这看起来是不可能的,因为我的业务需求要求我不要对页面的内容进行任何更改,除非添加存在此代码的javascript文件

忽略onBeforeUnload/onUnload,您不需要它。你可以用这样一个简单的点击处理程序:

$('a').on('click', function(e)
{
    e.preventDefault();
    var destinationLink = $(this).attr('href');
    $.post('/your/analytics/url', {link:destinationLink}, function()
    {
        // Success
        window.location.href = destinationLink;
    });
});

这将阻止任何链接工作,直到它被提交到您的分析中,所以这并不理想——您需要确保接收数据的人尽快这样做。

您可以替换单击链接的当前url。这将允许你调用你的服务器来检查点击的url,然后重定向它

下面的代码只更改了点击链接的url几微秒的

$("a").on("click",function(e){
    // Save the current link
    var h = this.href;
    //Change the link of the current a
    this.href = "http://www.example1.com/redirect.php?url="+encodeURI(h);
    // replace the href with the original value on the next stack
    setTimeout((function(my_link){
        return function(){
            my_link.href = h;
        };
    })(this),0);
});
<a href="http://www.example.com">my link</a>