Open a new tab in Safari programmatically using JS

18,464

This might be of some help.

window.open(url, '_blank'); not working on iMac/Safari

(I would share this as a comment but don't have enough rep yet.)

Share:
18,464
Darshan
Author by

Darshan

Updated on June 04, 2022

Comments

  • Darshan
    Darshan almost 2 years

    I am developing on an Ember.js platform with an Microsoft Azure database for uploaded files. Since the content of these files are sensitive, we're relying on Azure's secure access api to allow our users to view the file for about 2 minutes, then expiring the access link. This secure access link is returned to my application as response.fileURL.

    The problem is that I need to open this link in a new tab, and the methods I've tried work on every browser so far except for Safari.

    Now, after searching for "open new tab on safari programmatically" for a while, every result I've found online so far (for example, http://whoknew.dk/programmatically-opening-a-new-tab-window-on-mobile-safari-55.htm) has an implementation that has some interpretation of the following code:

    function openURL(){
        var a = window.document.createElement("a");
        a.target = '_blank';
        a.href = response.fileURL;
    
        // Dispatch fake click
        var e = window.document.createEvent("MouseEvents");
        // e.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
        e.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, true, false, false, false, 0, null); 
        a.dispatchEvent(e);
    }
    
    openURL();
    

    Since a simple

    <a target="_blank" href='link.com'>link</a>
    

    won't work and I am required to open this tab programmatically anyway, I have tried the above function to no avail. This issue is keeping our application from being able to open files on apple smartphones and tablets. And to make matters worse, Safari doesn't even notify the user that the 'popup' was blocked, so our users simple think this feature is broken when in fact it works in other browsers.

    How do I open any link/file in a new tab in safari?

  • Sassan
    Sassan over 4 years
    It doesn't work in Safari, the popup will get blocked by the browser and needs user interaction to open it.