DEV Community

Bartłomiej Stefański
Bartłomiej Stefański

Posted on • Originally published at bstefanski.com on

🐯 Opening New Tabs on Mobile Devices with JavaScript, Safari-Friendly

I recently encountered a situation where I needed to open a new tab on mobile devices using JavaScript. Initially, I used the following code:


window.open(url, '\_blank');

Enter fullscreen mode Exit fullscreen mode

It worked well, but when I tested it on Safari, I quickly discovered that Safari's security policies prevent opening a new tab within an asynchronous function, such as inside a promise. To address this issue, I had to find a workaround.

The most effective workaround I found involved the following steps:


var windowReference = window.open();

myService.getUrl().then(function(url) {

 windowReference.location = url;

});

Enter fullscreen mode Exit fullscreen mode

The key here is to declare a variable with a reference to the window.open() object outside of the asynchronous function. Then, reassign the location to the desired URL where you previously called the window.open function.

Top comments (0)