A WebView puts a web page inside a native app's trust boundary, so a single cross-site scripting bug or an unvalidated URL can reach native bridges, local files and session tokens that a browser tab would never expose. Hybrid apps, embedded help centres, payment pages and sign-in screens all use WebViews, and the OWASP Mobile Application Security Testing Guide (MASTG) treats WebView configuration as one of its largest test areas under MASVS-PLATFORM-2. This guide covers Android WebView and iOS WKWebView: what to load, JavaScript and bridge design, file and content access, transport security, debugging and data cleanup, with the MASTG tests that verify each control. It is written for mobile engineers, hybrid framework teams and mobile security testers.
Key takeaways
- Decide first whether you need a WebView at all. For third-party pages and sign-in, the system browser or an in-app browser tab (Custom Tabs,
SFSafariViewController,ASWebAuthenticationSession) keeps the page outside the app's trust boundary. - Allowlist what loads. Validate scheme, host and path before
loadUrlorload(_:)and in navigation callbacks, and send everything else to the external browser. - Bridges are the crown jewels. Android's
addJavascriptInterfaceis exposed to every frame without origin control; prefer origin-scopedaddWebMessageListener, and on iOS validateWKScriptMessagebodies andframeInfo. - Turn off file and content access. Serve local assets with
WebViewAssetLoaderoverhttps://appassets.androidplatform.net, and on iOS keepallowingReadAccessToto a single file or folder. - Production builds ship with debugging off and TLS errors fatal.
setWebContentsDebuggingEnabled(false), noisInspectablein release, and never callSslErrorHandler.proceed().
Choosing the right web component
Most WebView risk is avoided by not using one for the wrong job. The component determines whether the app can see the page's DOM, cookies and credentials, and whether the user can see the real address.
| Component | App can inject or read page content? | Shares browser cookies? | Address bar visible? | Best use |
|---|---|---|---|---|
Android WebView | Yes (JavaScript, bridges, interception) | No, own cookie store | No | First-party content that must integrate with native code |
| Android Custom Tabs | No | Yes, with the user's browser | Yes | Third-party pages, OAuth and OpenID Connect sign-in |
iOS WKWebView | Yes (evaluateJavaScript, message handlers) | No, own data store | No | First-party hybrid content |
iOS SFSafariViewController | No; JavaScript cannot be disabled and activity is not visible to the app | Yes, with Safari | Yes, read-only with security indicator | Viewing external web content |
iOS ASWebAuthenticationSession | No | Can share Safari session | Yes | Sign-in and consent flows |
iOS UIWebView | Yes, always runs JavaScript | n/a | No | None: deprecated since iOS 12; migrate to WKWebView (MASTG-BEST-0032) |
- Sign-in never goes in a WebView: RFC 8252 Section 8.12 says native apps must not use embedded user agents for OAuth authorisation requests. See the OAuth for Native and Mobile Apps Guide.
- Hybrid frameworks inherit everything here: Cordova, Capacitor, React Native WebView and similar frameworks are WebViews with a large bridge. Their plugin surface is the bridge surface.
Controlling what the WebView loads
MASTG notes that on Android, once a WebViewClient is set, all navigation is handled inside the WebView, so any resource can load unless the app validates URLs. Without a WebViewClient, navigation goes to the default browser, which does not share the WebView's cookies or bridges. The same principle applies on iOS through WKNavigationDelegate.
- Validate before the first load: parse the URL with
UriorURLComponents, requirehttps, and match the host against an exact allowlist (not a suffix match that acceptsexample.com.attacker.net). - Validate on every navigation: implement
shouldOverrideUrlLoading(WebView, WebResourceRequest)on Android andwebView(_:decidePolicyFor:decisionHandler:)on iOS. Allow known hosts; hand other links to the system browser; block unexpected schemes such asjavascript:,file:,content:andintent:. - Never forward link parameters: MASTG-BEST-0034 says deep links and custom URL schemes should only accept known commands and fixed destinations, and must not pass arbitrary parameters into
WKWebView.load(_:). See the Mobile Deep Link and App Link Security Guide. - Treat server-supplied URLs as untrusted: push notifications, remote config and API responses that carry URLs need the same allowlist.
- Use Safe Browsing where it fits: Android 8.1 (API 27) added Safe Browsing support in WebView, which warns on URLs Google classifies as known threats. It is a backstop, not an allowlist.
JavaScript and native bridges
JavaScript is off by default in Android WebView and on by default in WKWebView. MASTG-BEST-0012 is clear that enabling JavaScript is not a vulnerability by itself; severe cases happen when JavaScript is combined with untrusted content, bridges or file access. Keep it disabled for static help, legal and release-note pages.
| Bridge mechanism | Platform | Origin control | Guidance |
|---|---|---|---|
addJavascriptInterface with @JavascriptInterface | Android | None; object is injected into every frame, including iframes | Legacy. Use only when targeting API 21 or higher, remove with removeJavascriptInterface before untrusted content, never expose sensitive operations |
WebViewCompat.addWebMessageListener | Android (AndroidX WebKit) | Allowlist through allowedOriginRules | Recommended. Register before loadUrl(), keep rules exact, validate the sender in the callback |
WebViewCompat.postWebMessage / WebMessagePort | Android | Target origin per message | Alternative. Never use * as the target origin |
WKUserContentController.add(_:name:) with WKScriptMessageHandler | iOS | No built-in origin model; inspect WKScriptMessage.frameInfo and its security origin | Validate message type and structure, allow only named actions, remove handlers when done |
WKScriptMessageHandlerWithReply in a WKContentWorld | iOS 14 and later | Runs in an isolated content world | Return data through the Promise rather than string-built evaluateJavaScript callbacks (MASTG-BEST-0061, MASTG-BEST-0062) |
JSContext / JSExport on UIWebView | iOS | None | Do not use; deprecated platform |
Bridge design rules
- Narrow methods only: expose
openSettings()orshareText(text), notexec(command), generic dispatchers or file write helpers. - No secrets across the bridge: do not return access tokens, refresh tokens, API keys or device identifiers to JavaScript. If page code needs an authenticated call, have native code make it and return only the result the page needs. See the OWASP Mobile Top 10 M1 Improper Credential Usage Guide.
- Validate every message: expected type, length and allowed values, exactly as for any API input.
- Keep sensitive UI native: MASTG-BEST-0059 and MASTG-BEST-0060 recommend rendering credential pickers, payment confirmations and sensitive text entry as native views over the WebView, so page JavaScript cannot read them.
- Do not trust
getUrl()to identify the caller: MASTG records Android's note that methods such asWebView.getUrl()are not suitable for deciding which origin invoked anaddJavascriptInterfacemethod.
Because the page's own scripts can call the bridge, an XSS bug in your web content becomes native code access. Apply output encoding and a Content Security Policy to WebView-served pages as you would for the web. See the Cross-Site Scripting (XSS) Prevention Guide and the Content Security Policy Guide.
Local file and content provider access
Android's guidance on unsafe file inclusion explains that file:// access lets WebView content read files the app can access, including WebView cookies and app-private data, and that combining it with JavaScript enables file-based XSS.
Android WebSettings method | Default | Recommended |
|---|---|---|
setAllowFileAccess | true up to API 29, false from API 30 (Android 11) | Set false explicitly, especially if minSdk is 29 or lower |
setAllowFileAccessFromFileURLs | false from API 16; deprecated since API 30 | Never enable |
setAllowUniversalAccessFromFileURLs | false from API 16; deprecated since API 30 | Never enable; it lets file:// JavaScript bypass the same-origin policy for requests |
setAllowContentAccess | true | Set false unless content:// loading is required (MASTG-BEST-0013) |
setJavaScriptEnabled | false | Enable only for pages that need it |
- Serve assets over https: AndroidX
WebViewAssetLoaderwith anAssetsPathHandlerserves bundled files fromhttps://appassets.androidplatform.net/assets/, so pages get a normal web origin and file access can be switched off (MASTG-BEST-0011). - Content providers are reachable even when unexported: MASTG-BEST-0013 notes that a WebView with content access can reach the app's own providers, which may expose private storage if chained with XSS.
- iOS file scope:
loadFileURL(_:allowingReadAccessTo:)limits reads to the given file or directory. Point it at the single file or a dedicated folder, never at Documents or Library as a whole.allowFileAccessFromFileURLsandallowUniversalAccessFromFileURLsare not publicWKWebViewAPI and should stay off (MASTG-BEST-0033). - Origin of HTML strings: in
WKWebView,loadHTMLString(_:baseURL:)with anilbase URL gives an opaquenullorigin. Do not set the base URL to a privileged origin just to make relative links work. - File choosers:
WebChromeClient.onShowFileChooserlets the page request user files; treat uploads as untrusted on the server.
Transport security, debugging and data cleanup
- TLS errors: by default an Android WebView cancels a request on a certificate error. Overriding
onReceivedSslErrorand callingSslErrorHandler.proceed()disables certificate validation (MASTG-TEST-0284). On iOS, reviewWKNavigationDelegateauthentication challenge handling for the same mistake (MASTG-BEST-0073). - Cleartext: set
android:usesCleartextTraffic="false"or a Network Security Config. On iOS, avoidNSAllowsArbitraryLoadsInWebContent, the App Transport Security exception that relaxes ATS for web content only. WebKit still blocks active mixed content on HTTPS pages. - Debugging:
WebView.setWebContentsDebuggingEnabled(true)lets anyone with USB access inspect and modify the page through DevTools. Disable it in release or gate it onApplicationInfo.FLAG_DEBUGGABLE(MASTG-BEST-0008, MASTG-TEST-0227). From iOS 16.4,WKWebViewcontent is inspectable only if the app setsisInspectable = true; keep that out of release builds. - Cache and storage: sensitive responses should carry
Cache-Control: no-storeorno-cache. As a supplement, useLOAD_NO_CACHEor clear cache, cookies and web storage when the user signs out (MASTG-BEST-0028, MASTG-TEST-0320). Clearing on exit is not guaranteed if the process is killed, so also clear at next start.
Testing and verification
| MASTG test | Platform | What it checks |
|---|---|---|
| MASTG-TEST-0031 Testing JavaScript Execution in WebViews | Android | Where JavaScript is enabled and what content those WebViews load |
| MASTG-TEST-0033 and MASTG-TEST-0334 | Android | Java objects and native code exposed through bridges |
| MASTG-TEST-0252, 0253 (file) and 0250, 0251 (content provider) | Android | Static references and runtime use of local file and content access |
| MASTG-TEST-0398 and 0400 | Android | WebViewClient URL loading handlers, static and runtime |
| MASTG-TEST-0284 | Android | Incorrect SSL error handling |
| MASTG-TEST-0227 and 0320 | Android | WebView debugging enabled; sensitive data not cleaned up |
| MASTG-TEST-0332 Attacker-Controlled URI in WebViews | iOS | URLs from links or inputs reaching load(_:) |
| MASTG-TEST-0333, 0335, 0336 | iOS | Overly broad file read access and relaxed file origin policies |
| MASTG-TEST-0376, 0377, 0379, 0380 | iOS | Native bridge APIs, evaluateJavaScript reply patterns, content world isolation, sensitive data written into the DOM |
| MASTG-TEST-0331 | iOS | Use of deprecated WebView APIs |
- Automate the static half: lint rules or SAST queries for
setJavaScriptEnabled(true),addJavascriptInterface, the file access setters,proceed()inonReceivedSslError,setWebContentsDebuggingEnabled(true)andisInspectable. - Test the dynamic half per release: drive each WebView with an off-allowlist URL, an iframe from another origin and a
file://URL, and confirm each is blocked or sent to the browser.
See the Mobile App Security Testing Guide for running these tests within a wider MASTG programme.
Rolling out WebView hardening
- Inventory every WebView: list each screen, what it loads (bundled, first-party remote, third-party), whether JavaScript is on, and which bridges it has. Include WebViews inside third-party SDKs, which you can find through the same static checks.
- Move the easy cases out: third-party pages and sign-in to Custom Tabs,
SFSafariViewControllerorASWebAuthenticationSession. - Apply a shared secure WebView wrapper: one internal component with file and content access off, debugging gated, TLS errors fatal, navigation allowlist and logging. Ban direct construction through lint.
- Migrate bridges: replace
addJavascriptInterfacewithaddWebMessageListenerand exact origin rules; on iOS move to named handlers with validation and content worlds. - Ship in monitor mode first: log navigations that the new allowlist would block for one release, fix legitimate gaps, then enforce. Keep the allowlist in remote config so a missed host can be added without a release, with changes reviewed like code.
- Gate releases on the MASTG tests above and on a review of any new bridge method.
A small team with one hybrid screen can apply the wrapper in days. A large organisation with web teams shipping into native shells needs a joint web and mobile security review, because a web deploy can change what runs behind the bridge without a store release.
Detection and measurement
- Blocked navigations: count and sample (without query strings) navigations blocked by the allowlist, by screen and app version.
- Bridge rejections: messages rejected for origin, type or action. Repeated rejections from one origin suggest injected script.
- CSP reports: collect Content Security Policy violation reports from WebView-served pages.
| Metric | Target |
|---|---|
| WebViews built through the secure wrapper | 100% of first-party WebViews |
Bridges using addJavascriptInterface | 0, or each with a documented exception |
| WebViews with file access or universal file access enabled | 0 |
Release builds with WebView debugging or isInspectable enabled | 0 |
| Sign-in or payment flows inside an embedded WebView | 0 |
| Applicable MASTG WebView tests passing at release | All |
Framework mapping
| Framework | Reference | How it applies |
|---|---|---|
| OWASP MASVS | MASVS-PLATFORM-2 (uses WebViews securely); MASVS-CODE-4; MASVS-NETWORK-1 | WebView configuration; input validation; secure transport |
| OWASP Mobile Top 10 2024 | M4 Insufficient Input/Output Validation; M8 Security Misconfiguration | URL and message validation; unsafe defaults and debug settings |
| NIST SP 800-53 Rev 5 | SI-10 Information Input Validation; SA-11 Developer Testing and Evaluation; SC-8 Transmission Confidentiality and Integrity | Validation, test evidence, TLS enforcement |
| NIST CSF 2.0 | PR.PS-06 | Secure development integrated into the life cycle |
| ISO/IEC 27001:2022 Annex A | A.8.28 Secure coding; A.8.29 Security testing in development and acceptance | Wrapper standard and release testing |
| CIS Controls v8.1 | Control 16 Application Software Security | Secure configuration and testing of in-house apps |
Common failure patterns
- Bridge plus third-party content: an
addJavascriptInterfaceobject exposed in a WebView that also renders adverts, embedded videos or user-generated content, so any iframe can call native code. - Suffix host checks:
host.endsWith("example.com")acceptsbadexample.com; compare against exact hosts or a parsed registrable domain plus dot. - "Temporary" SSL bypass:
proceed()added to get past a staging certificate and shipped to production. - Tokens in the DOM: native code writes an access token into the page with
evaluateJavaScriptso the web app can call APIs, making every XSS a token theft (MASTG-TEST-0380). - Old minSdk defaults: apps supporting API 29 or lower rely on defaults and leave
setAllowFileAccessattrue. - Login in a WebView: embedded sign-in pages that let the app read credentials and train users to trust screens without an address bar.
Practitioner checklist
- Inventory every WebView, including those inside SDKs, with content source, JavaScript state and bridges.
- Move sign-in and third-party pages to Custom Tabs,
SFSafariViewControllerorASWebAuthenticationSession. - Enforce an exact https host allowlist on first load and in navigation callbacks.
- Replace
addJavascriptInterfacewithaddWebMessageListenerand exactallowedOriginRules; validate every iOS script message. - Expose no tokens, keys or generic command dispatchers through bridges.
- Disable file, universal file and content access; serve assets via
WebViewAssetLoader; scope iOSallowingReadAccessTotightly. - Make TLS errors fatal and block cleartext; remove
NSAllowsArbitraryLoadsInWebContent. - Disable WebView debugging and
isInspectablein release builds. - Clear WebView cache, cookies and storage at sign-out and set no-store on sensitive responses.
- Run the MASTG WebView tests at every release and on every new bridge method.
Standards and references
- OWASP: Mobile Application Security Verification Standard (MASVS)
- OWASP MASTG: WebViews (Android)
- OWASP MASTG: WebViews (iOS)
- OWASP MASTG: Prefer Origin Scoped Messaging Over Legacy JavaScript Bridges
- Android Developers: WebView native bridges
- Android Developers: WebViews unsafe file inclusion
- IETF: RFC 8252 OAuth 2.0 for Native Apps
Related NHI Mgmt Group resources: Mobile Deep Link and App Link Security Guide · OWASP Mobile Top 10 M4 Insufficient Input and Output Validation Guide · Cross-Site Scripting (XSS) Prevention Guide · Mobile App Security Guide