简体   繁体   中英

how to capture open link in new tab or window using jquery?

Is it possible to capture the right click open in new window/tab or mouse wheel open in new window/tab event using jQuery?
UPDATE 1
Here is why I need it. I have codeigniter application which uses pagination class. I use this class to display a grid. The pagination links have been bind with a method that uses AJAX to load the next page in a container div. Now some one can right click and open the next page in new tab/window which I don't want. IMHO, the only way to handle this is to some how trap the (right click or mouse wheel button click) open in new window/tab event.
UPDATE 2
I just realised all my AJAX requests are being served by one CI controller which actually acts as a proxy to other classes/libs. In this controller I can look at the request and if it isn't an AJAX request I can redirect the user to another page.

A workaround solution is to replace all applicable <a> elements with buttons, where (obviously) the buttons would call JavaScript that does the appropriate navigation.

If you're really keen you can apply CSS to make the buttons look like <a> elements, though I don't recommend it because it confuses users who might try to treat them as standard links and right- or middle-click them.

(You could even get it to work for users that don't have JavaScript enabled by, eg, making each button a submit button in its own little form.)

At the very least you can catch a right-click, using .mousedown() (or, presumably, mouseup() ). See this StackOverflow answer about right clicks for more. And by catching it, you should be able to do a standard event.preventDefault() and then do as you like from there. That may be overkill, however, as it could prevent the user from doing other things you want to allow them to do.

I almost fixed a similar issue now for a page which I am working on. My fix was to do some changes in the page if that has been opened in a new window....

Assume that you open a page "B" from page "A" in a new window.

If you want to check the page "B" is opened in a new window from page "A", then follow the below steps..

If (document.referrer == "A" && window.history.length > 1) {
     alert("I am page 'B' and opened from page 'A' in a new window");
}

If you don't want people to access link the usual way or fallback when the JS is disabled, then it shouldn't be a link. Just use any element you like (span, div, button, whatever you like) and style it like a link. Then bind the action using JS. Or you can use a link with href="#" or href="javascript: void(0)" . That way if users right click it and choose to open in a new window, then they will end up in the same page they were before.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM