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.

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay