Same Code, Put It in an App, and It Behaves Differently
Why window.open() returns null inside an app: a WebView is a browser that the host app drives. How links, MRAID, and the host change what your code does.
On the web, your code runs in a browser that you know. Inside an app, the same code runs in a browser that the app controls. The code does not change. The host does.
A WebView is a browser that someone else drives
A WebView is a browser engine inside a native app. On iOS it is WKWebView. It has no tabs and no address bar. The app that holds it is the host. A page can ask for something that a browser normally does by itself. In a WebView, the host decides the result.
- Safari opens a new tab for
window.open(). - A WebView asks the host to make a new WebView. If the host does not implement that request (
webView:createWebViewWithConfiguration:on iOS),window.open()returnsnull. - A link tap is a separate path. The host sees each navigation request and can open the URL in its own way.
So the same code has two outcomes. On the web, you test in a browser that you know. In an app, the browser is whatever the host made it.
One more layer: the ad API
Ads inside apps often get a JavaScript API from the app’s SDK (software development kit, a code library inside the app). The common one is MRAID. With it, the ad calls mraid.open(url) and the SDK opens the URL with the app’s own code. But MRAID starts in a loading state, and the ad must not call mraid.open() until the SDK changes the state. A click script (the ad’s JavaScript that records the tap and opens the ad’s page) then falls back to window.open(). In the example, a log at the tap showed loading on every tap, so every tap took the fallback and got null.
In the example
- Every tap on the failing ad:
window.open()returnednullinside the app. - A control (a second test that differs in one known way): an ad from another ad network, with a plain
<a target="_blank">. It opened in in-app Safari (Safari shown inside the app). - When the link tap was allowed to go on, the SDK opened the advertised app.
The rule for code that runs inside apps: treat a null from window.open() as “not opened”, and let the link go on. Where the link then opens is Three Ways an iOS App Can Open a Link.
Always test inside the real host. Safari is not the app.
References
Related: see where the link lands in Three Ways an iOS App Can Open a Link, learn to peel the host apart in One Tap Passes Six Layers: Remove One Layer per Test, or jump to Takeaway: Check One Layer at a Time, and Test Each Guess with the Right Tool. Back to the series overview.