Avi
Avi

Reputation: 808

Click a link and use window.open() blocks one of the links

I'm trying to create a simple JS function that will open a new window/tab when clicking a specific button, so the user will actually open 2 windows/tabs, however no matter what I do, one of the links gets blocked by Chrome as a "popup-blocked".

I'd like to do something like this:

    $(document).ready(function(){
        $("a").mousedown(function(){
            window.open("https://stackoverflow.com/","_blank");
        });
    })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="https://google.com">Click Me!</a>

;

But when I do this, the button link doesn't work, but the JS does. If I change the JS and add a setTimeout() to it, the button URL goes through but the JS gets blocked. No matter what I do, I can't get both of them to go through.

Any help would be appreciated.

Upvotes: 2

Views: 1132

Answers (2)

Konstantin T.
Konstantin T.

Reputation: 72

The problem is caused by the mousedown() event you are using which is a part of down+up sequence to trigger the click() event of the <a> tag.

so opening a new window "breaks" the flow and browser is not tracking for the mouse-up event anymore to follow the original url.

so the solution is to attach the click() event instead without stopping propagation. this will fire the attached and original events and none of them will be blocked.

  $(document).ready(function(){
        $("a").click(function(){
            window.open("https://stackoverflow.com/","_blank");
        });
    })

you can try sample on this page as stackoverflow snippet is sandboxed and is blocking popups

Upvotes: -2

Quentin
Quentin

Reputation: 944300

Navigating to two places at once, with one in a new window, is really popular with people who want to show the user a massive advert in a new window.

Massive adverts are unpopular with users, so browsers take steps to prevent this behaviour.

Sometimes legitimate uses get caught in the crossfire. Blame the blackhat end of the advertising industry.


You'll need to find some other way to display… whatever it is you want to display… to the user that doesn't involve navigating to multiple webpages at the same time in separate windows.

Upvotes: 3

Related Questions