JavaScript to open link in a new window without being popup blocked

To ensure security and reduce spamming, modern browsers have implemented very strict rules on when a new window can be opened in a web page. Currently browsers restrict that any new web page to be opened in a new window must be initiated with an user action. The action is usually an user click event. Otherwise, a popup blocker would show on the browser address bar which indicates that something is blocked.

To workaround this issue, normally you should implement the window open logic in a click event handler. An example code block would look like:

jQuery("#some_element").click(function(){
    var win = window.open();
    win.location = 'https://example.com';
    win.opener = null;
    win.blur();
    window.focus();
});

When the element with id some_element is clicked by the user, the window can open normally without being blocked. 

What if in some cases you want to open a new window without involving user action(This is not recommended normally)? One possible solution is to simulate the click event when the page is loaded or at some point of time. Hence some codes like below may work.

jQuery("#some_element").click(function(){
    var win = window.open();
    win.location = 'https://example.com';
    win.opener = null;
    win.blur();
    window.focus();
});
jQuery("#some_element").click();

But will it work indeed? No, it will not. This is not a true user action so browser will not allow it. Because whether something is a user action is solely determined by the browser and they know what is a true user action.

The working way to open a new window is to add a click listener to the document object and open the new window when the user clicks any part of the page.

let isTriggered = false;
jQuery(document).click(function(){
    if(!isTriggered){
        isTriggered = true;
        let win = window.open();
        win.location = 'https://example.com';
        win.opener = null;
        win.blur();
        window.focus();
    }
});

Another closer simulation to open a new window is to use iframe. The basic logic would be:

  1. Create a modal dialog which contains an iframe element
  2. Set the src property of iframe to the URL you want open(Some URLs have special security restrictions which prevent them from being loaded in iframe)
  3. Show the dialog.

This is not perfect but may work for some people. 

Finally we DO NOT recommend to workaround the security restriction the browser puts on us. This post serves the sole purpose of exploring something uneasy to achieve and it seems we failed.

Rate article
( 3 assessment, average 5 from 5 )
Legenki
Leave a Reply