Opening a New Window After an Async Operation

I was working on an OAuth implementation the other day and needed to open a third-party auth page in a new window.

However, I needed to fetch the target URL from the server first, then open the window. Kinda like this:

const button = document.getElementById('auth-button');

button.addEventListener('click', () => {
getAuthUrl().then(url => {
window.open(url);
});
});

Of course, this doesn't work in most browsers — the popup gets blocked because the window wasn't opened immediately after the click.

To work around this, we need to open the window immediately after the click, so let's use the well-supported about:blank URL to our advantage.

const button = document.getElementById('auth-button');

button.addEventListener('click', () => {
const win = window.open('about:blank');

getAuthUrl().then(url => {
win.location = url;
});
});

Now the window opens and redirects to the appropriate URL after the async function executes!

You can take it a step further by opening a special page that shows a loader instead. Just swap out about:blank with your own page.

Author avatar

About the author

New Hampshirite building web apps in Florida. Creator of Surreal CMS, Postleaf, and DirtyMarkup.

Need to get in touch? Catch me on Twitter.