Join our Newsletter — 33% off our NHI Course
Home› Guides› Mobile WebView Security Guide: Bridges, File Access and…
Guide Application Security

Mobile WebView Security Guide: Bridges, File Access and Content Loading

PDF for newsletter subscribers · free to read online

← All guides
By NHI Mgmt Group, edited by Lalit Choda Updated 27 October 2026 13 min read
On this page

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 loadUrl or load(_:) and in navigation callbacks, and send everything else to the external browser.
  • Bridges are the crown jewels. Android's addJavascriptInterface is exposed to every frame without origin control; prefer origin-scoped addWebMessageListener, and on iOS validate WKScriptMessage bodies and frameInfo.
  • Turn off file and content access. Serve local assets with WebViewAssetLoader over https://appassets.androidplatform.net, and on iOS keep allowingReadAccessTo to a single file or folder.
  • Production builds ship with debugging off and TLS errors fatal. setWebContentsDebuggingEnabled(false), no isInspectable in release, and never call SslErrorHandler.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.

ComponentApp can inject or read page content?Shares browser cookies?Address bar visible?Best use
Android WebViewYes (JavaScript, bridges, interception)No, own cookie storeNoFirst-party content that must integrate with native code
Android Custom TabsNoYes, with the user's browserYesThird-party pages, OAuth and OpenID Connect sign-in
iOS WKWebViewYes (evaluateJavaScript, message handlers)No, own data storeNoFirst-party hybrid content
iOS SFSafariViewControllerNo; JavaScript cannot be disabled and activity is not visible to the appYes, with SafariYes, read-only with security indicatorViewing external web content
iOS ASWebAuthenticationSessionNoCan share Safari sessionYesSign-in and consent flows
iOS UIWebViewYes, always runs JavaScriptn/aNoNone: 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.

  1. Validate before the first load: parse the URL with Uri or URLComponents, require https, and match the host against an exact allowlist (not a suffix match that accepts example.com.attacker.net).
  2. Validate on every navigation: implement shouldOverrideUrlLoading(WebView, WebResourceRequest) on Android and webView(_:decidePolicyFor:decisionHandler:) on iOS. Allow known hosts; hand other links to the system browser; block unexpected schemes such as javascript:, file:, content: and intent:.
  3. 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.
  4. Treat server-supplied URLs as untrusted: push notifications, remote config and API responses that carry URLs need the same allowlist.
  5. 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 mechanismPlatformOrigin controlGuidance
addJavascriptInterface with @JavascriptInterfaceAndroidNone; object is injected into every frame, including iframesLegacy. Use only when targeting API 21 or higher, remove with removeJavascriptInterface before untrusted content, never expose sensitive operations
WebViewCompat.addWebMessageListenerAndroid (AndroidX WebKit)Allowlist through allowedOriginRulesRecommended. Register before loadUrl(), keep rules exact, validate the sender in the callback
WebViewCompat.postWebMessage / WebMessagePortAndroidTarget origin per messageAlternative. Never use * as the target origin
WKUserContentController.add(_:name:) with WKScriptMessageHandleriOSNo built-in origin model; inspect WKScriptMessage.frameInfo and its security originValidate message type and structure, allow only named actions, remove handlers when done
WKScriptMessageHandlerWithReply in a WKContentWorldiOS 14 and laterRuns in an isolated content worldReturn data through the Promise rather than string-built evaluateJavaScript callbacks (MASTG-BEST-0061, MASTG-BEST-0062)
JSContext / JSExport on UIWebViewiOSNoneDo not use; deprecated platform

Bridge design rules

  • Narrow methods only: expose openSettings() or shareText(text), not exec(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 as WebView.getUrl() are not suitable for deciding which origin invoked an addJavascriptInterface method.

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 methodDefaultRecommended
setAllowFileAccesstrue up to API 29, false from API 30 (Android 11)Set false explicitly, especially if minSdk is 29 or lower
setAllowFileAccessFromFileURLsfalse from API 16; deprecated since API 30Never enable
setAllowUniversalAccessFromFileURLsfalse from API 16; deprecated since API 30Never enable; it lets file:// JavaScript bypass the same-origin policy for requests
setAllowContentAccesstrueSet false unless content:// loading is required (MASTG-BEST-0013)
setJavaScriptEnabledfalseEnable only for pages that need it
  • Serve assets over https: AndroidX WebViewAssetLoader with an AssetsPathHandler serves bundled files from https://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. allowFileAccessFromFileURLs and allowUniversalAccessFromFileURLs are not public WKWebView API and should stay off (MASTG-BEST-0033).
  • Origin of HTML strings: in WKWebView, loadHTMLString(_:baseURL:) with a nil base URL gives an opaque null origin. Do not set the base URL to a privileged origin just to make relative links work.
  • File choosers: WebChromeClient.onShowFileChooser lets 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 onReceivedSslError and calling SslErrorHandler.proceed() disables certificate validation (MASTG-TEST-0284). On iOS, review WKNavigationDelegate authentication challenge handling for the same mistake (MASTG-BEST-0073).
  • Cleartext: set android:usesCleartextTraffic="false" or a Network Security Config. On iOS, avoid NSAllowsArbitraryLoadsInWebContent, 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 on ApplicationInfo.FLAG_DEBUGGABLE (MASTG-BEST-0008, MASTG-TEST-0227). From iOS 16.4, WKWebView content is inspectable only if the app sets isInspectable = true; keep that out of release builds.
  • Cache and storage: sensitive responses should carry Cache-Control: no-store or no-cache. As a supplement, use LOAD_NO_CACHE or 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 testPlatformWhat it checks
MASTG-TEST-0031 Testing JavaScript Execution in WebViewsAndroidWhere JavaScript is enabled and what content those WebViews load
MASTG-TEST-0033 and MASTG-TEST-0334AndroidJava objects and native code exposed through bridges
MASTG-TEST-0252, 0253 (file) and 0250, 0251 (content provider)AndroidStatic references and runtime use of local file and content access
MASTG-TEST-0398 and 0400AndroidWebViewClient URL loading handlers, static and runtime
MASTG-TEST-0284AndroidIncorrect SSL error handling
MASTG-TEST-0227 and 0320AndroidWebView debugging enabled; sensitive data not cleaned up
MASTG-TEST-0332 Attacker-Controlled URI in WebViewsiOSURLs from links or inputs reaching load(_:)
MASTG-TEST-0333, 0335, 0336iOSOverly broad file read access and relaxed file origin policies
MASTG-TEST-0376, 0377, 0379, 0380iOSNative bridge APIs, evaluateJavaScript reply patterns, content world isolation, sensitive data written into the DOM
MASTG-TEST-0331iOSUse of deprecated WebView APIs
  • Automate the static half: lint rules or SAST queries for setJavaScriptEnabled(true), addJavascriptInterface, the file access setters, proceed() in onReceivedSslError, setWebContentsDebuggingEnabled(true) and isInspectable.
  • 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

  1. 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.
  2. Move the easy cases out: third-party pages and sign-in to Custom Tabs, SFSafariViewController or ASWebAuthenticationSession.
  3. 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.
  4. Migrate bridges: replace addJavascriptInterface with addWebMessageListener and exact origin rules; on iOS move to named handlers with validation and content worlds.
  5. 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.
  6. 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.
MetricTarget
WebViews built through the secure wrapper100% of first-party WebViews
Bridges using addJavascriptInterface0, or each with a documented exception
WebViews with file access or universal file access enabled0
Release builds with WebView debugging or isInspectable enabled0
Sign-in or payment flows inside an embedded WebView0
Applicable MASTG WebView tests passing at releaseAll

Framework mapping

FrameworkReferenceHow it applies
OWASP MASVSMASVS-PLATFORM-2 (uses WebViews securely); MASVS-CODE-4; MASVS-NETWORK-1WebView configuration; input validation; secure transport
OWASP Mobile Top 10 2024M4 Insufficient Input/Output Validation; M8 Security MisconfigurationURL and message validation; unsafe defaults and debug settings
NIST SP 800-53 Rev 5SI-10 Information Input Validation; SA-11 Developer Testing and Evaluation; SC-8 Transmission Confidentiality and IntegrityValidation, test evidence, TLS enforcement
NIST CSF 2.0PR.PS-06Secure development integrated into the life cycle
ISO/IEC 27001:2022 Annex AA.8.28 Secure coding; A.8.29 Security testing in development and acceptanceWrapper standard and release testing
CIS Controls v8.1Control 16 Application Software SecuritySecure configuration and testing of in-house apps

Common failure patterns

  • Bridge plus third-party content: an addJavascriptInterface object 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") accepts badexample.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 evaluateJavaScript so 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 setAllowFileAccess at true.
  • 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, SFSafariViewController or ASWebAuthenticationSession.
  • Enforce an exact https host allowlist on first load and in navigation callbacks.
  • Replace addJavascriptInterface with addWebMessageListener and exact allowedOriginRules; 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 iOS allowingReadAccessTo tightly.
  • Make TLS errors fatal and block cleartext; remove NSAllowsArbitraryLoadsInWebContent.
  • Disable WebView debugging and isInspectable in 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

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

PDF for subscribers

Take this guide with you

Every section, table and checklist in one PDF, with links to the sources and related guides. Subscribe to our weekly NHI & AI Identity Journal and we’ll email you a download link.

Free weekly newsletter

Subscribe to the NHI & AI Identity Journal

The latest on NHI and Agentic AI security – articles, research, breaches, news and events every week.

Bonus 33% off our NHI Course when you subscribe.

NHIMG Editorial Note
Researched and written by the NHI Mgmt Group editorial team using AI tools, under the editorial direction of Lalit Choda. Facts are drawn from the sources listed on this page and checked by our automated quality process. Last updated 27 October 2026. Spotted an error? Use our contact page.
NHI Mgmt Group, the independent authority on Non-Human Identity, IAM and Agentic AI security. nhimg.org

PDF Downloads for Newsletter Subscribers

Get the guide

Enter your details and we’ll email you a download link.

The full guide is free to read online. The PDF is a thank you for subscribing.

Fill in all fields marked * and tick the PDF box to continue.