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
-
5Not possible I'm afraid. Events in the context menu itself is it a lower level than JS has access to. – Rory McCrossan Oct 27 '17 at 10:09
-
What do you suggest ? Basically the link that is opened on left click is created dynamically using js. But on right click and open in new tab , the link is not updated. The original href attribute has "#" as its value – Danysh Mushtaq Oct 27 '17 at 10:12
-
In that case you need to set the actual `href` attribute in the DOM, not calculate it on `click()` of the element. Alternatively you could set the `href` in both the `click` and `contextmenu` event handlers. – Rory McCrossan Oct 27 '17 at 10:12
-
possible duplicate with https://stackoverflow.com/questions/850058/is-it-possible-to-detect-if-a-user-has-opened-a-link-in-a-new-tab – RamaKrishna Oct 27 '17 at 10:14
1 Answers
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);
});
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.
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.

- 212
- 1
- 3
- 8