I'm developing an OAuth authentication flow purely in JavaScript and I want to show the user the "grant access" window in a popup, but it gets blocked.
How can I prevent pop up windows created by either window.open
or window.showModalDialog
from being blocked by the different browsers' pop-up blockers?
The general rule is that popup blockers will engage if
window.open
or similar is invoked from javascript that is not invoked by direct user action. That is, you can callwindow.open
in response to a button click without getting hit by the popup blocker, but if you put the same code in a timer event it will be blocked. Depth of call chain is also a factor - some older browsers only look at the immediate caller, newer browsers can backtrack a little to see if the caller's caller was a mouse click etc. Keep it as shallow as you can to avoid the popup blockers.As a good practice I think it is a good idea to test if a popup was blocked and take action in case. You need to know that window.open has a return value, and that value may be null if the action failed. For example, in the following code:
if the popup is blocked, window.open will return null. So the function will return false.
If the popup does not open, you can:
Based on Jason Sebring's very useful tip, and on the stuff covered here and there, I found a perfect solution for my case:
Pseudo code with Javascript snippets:
immediately create a blank popup on user action
Optional: add some "waiting" info message. Examples:
a) An external HTML page: replace the above line with
b) Text: add the following line below the above one:
fill it with content when ready (when the AJAX call is returned, for instance)
Enrich the call to
window.open
with whatever additional options you need.I actually use this solution for a mailto redirection, and it works on all my browsers (windows 7, Android). The
_blank
bit helps for the mailto redirection to work on mobile, btw.Your experience? Any way to improve this?
I didn't want to make the new page unless the callback returned successfully, so I did this to simulate the user click:
I tried multiple solutions, but his is the only one that actually worked for me in all the browsers
let newTab = window.open(); newTab.location.href = url;
In addition Swiss Mister post, in my case the window.open was launched inside a promise, which turned the popup blocker on, my solution was: in angular:
browserService:
this is how you can open a new tab using the promise response and not invoking the popup blocker.