Menü schliessen
Created: August 25th 2021
Last updated: August 25th 2021
Categories: IT Development,  JavaScript Development
Author: Marcus Fleuti

FIX: How to use window.open() in safari inside async call

Tags:  Ajax,  async,  Javascript,  jQuery,  js,  problem,  safari,  url,  window
Donation Section: Background
Monero Badge: QR-Code
Monero Badge: Logo Icon Donate with Monero Badge: Logo Text
82uymVXLkvVbB4c4JpTd1tYm1yj1cKPKR2wqmw3XF8YXKTmY7JrTriP4pVwp2EJYBnCFdXhLq4zfFA6ic7VAWCFX5wfQbCC

Why is window.open() not working inside an async call in Safari?

Safari blocks any window.open() function during an async call to provide "better" security. If you are using window.open() anyways inside an async call, Safari users will get a popup with the message, that a popup gets blocked.

The workaround

To prevent this popup from appearing on Safari you need to open the window right before you start the async call but not inside the call. Now Safari is not preventing the window from opening and you can set it's location inside the async call to the URL you wish to redirect.

Example:

//Open the window before you start an async call
let window = window.open();

//Now you can start an async call
$.ajax({
   url: "www.yourdomain.tld",
   type: "POST",
   data: {
      "action": "buy_new_car"
   },
   success: function(data) {
      //Set the location of the window to the URL you wish to redirect
      win.location = "www.yourdomain.tld";
   }
})