'capture "open link in new tab" and "Open link in new window" event

This is my code

<a href="javascript:void(0)" onclick="myFun('www.google.com');" onmousedown="myFun('www.google.com');">

whenever I am clicking on this link my function gets called using onclick event. I added onmousedown event for right-click capturing. But the problem is, this function gets called before selecting "Open in new tab" or "Open in new window" options. When the user uses right-click and before selecting the right-click options, the function gets called. I don't want this behavior. I want to call this function when the user actually selects "Open link in new tab" or "Open link in new window" options.

I don't want to show links in the status bar and also don't want to allow the user to copy the link address. That is why I used onclick and onmousedown events.

Please help me out. Thanks



Solution 1:[1]

The problem you have is that both, right and left click is handled with the onclick function. Another possibility would be to use oncontextmenu (as mentioned here).

But I think you need to handle right click and left click differently, so onclick is the right event, just check there if it was the primary (0) or secondary (2) mouseButton (see here). So you solution could be something like this:

myFun(link) {
    var buttonPressed = instanceOfMouseEvent.button;
    if (buttonPressed == 0) {
         //Handle normal click
    } else if (buttonPressed == 2) {
         //Handle right click 
    }
}

Solution 2:[2]

It sounds like you're looking for something like this, that will change the link once the context menu is launched:

function myFun2(url) {
   linkEl.href = url;
}

Then assign the a element an ID (i.e. "linkEl"), remove the onmousedown handler, and assign an oncontextmenu handler, like:

oncontextmenu="myFun2('www.google.com');"

Then when the context menu is launched, the link will change, so if "Open in New Tab" or "Open in New Window" is selected, it will go to Google (in this example) instead of whatever the link was set to previously.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Community
Solution 2