如何在javascript中的新标签事件中捕获打开的链接? [英] how to capture the open link in new tab event in javascript?

查看:59
本文介绍了如何在javascript中的新标签事件中捕获打开的链接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我能够捕获右键单击事件,但是我想知道的是如何捕获右键单击后发生的在新标签页中打开链接"

I am able to capture the right click event but what i want to know is how to capture the "open link in new tab" which happens after right click

推荐答案

我正面临着同样的问题.这是我想出的解决方案. 当我在感兴趣的链接上打开上下文菜单时,我会监听它,并更改href值

I was just facing the same problem. This is the work around I came up with. I listen to the context menu when it opens on the links I'm interested in, and I change the href value

$(".my-links").contextmenu(function(event){
        // your logic here 
        // for me it was to add the portocal + "://" + hostname + "/#" + value of the original link
        var $link = $(this);
        var href = $link.attr('href');
        // Check if I have already done this
        if(href.includes('/#'))
            return true; // return if it doesn't need editing
        var url = window.location.href;
        url = url.split("/");
        url = url[0]+'//'+url[2];
        $link.attr('href', url + '/#' + href);
    });

现在,您可以选择执行一些操作以从此操作中恢复.这完全取决于您的情况和您要执行的操作.对我来说,我需要将href恢复为正常点击的原始值,因为我使用Ajax加载页面,并且只需要"/#"之后的部分(这是加载功能所需要的,而且我无法控制更改该功能) 这就是我所做的.

Now you can optionally do something to recover from this operation. This totally depends on your case and what you are trying to do. For me i needed to put the href back to its original value for normal clicks, because I use ajax to load the page and I only need the part after "/#" (this is what the load function needs, and I have no control over changing that function) Here is what i did.

$(".my-links").click(function(event){
        // your logic goes here
        // for me it was to remove portocal + "://" + hostname + "/#" (if they exist)
        event.preventDefault();
        var $link = $(this);
        var href = $link.attr('href');
        if(!href.includes("/#"))
            return ajaxLoad(href); // the function used to load the page with ajax
        var url = href.split("/#");
        ajaxLoad(url[url.length-1]); // the function used to load the page with ajax
    });

这些行很长,应该适合您.

Something a long these lines should work for you.

  1. 收听contextmenu事件并执行您的逻辑.

  1. Listen to the contextmenu event and do your logic.

如果您需要恢复更改,请找出最合适的事件来恢复更改(如果已发生)并执行恢复过程.

If you need to recover your change figure out the most appropriate event to recover the change if they have occurred and carry out your recovery process.

这篇关于如何在javascript中的新标签事件中捕获打开的链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆