Android WebView JavaScript interface exposure

Android WebView JavaScript interface exposure

Description

addJavascriptInterface exposes a Java or Kotlin object to JavaScript in WebView. If untrusted pages or HTML built from external input can use this interface, their scripts may call internal app methods.

Potential impact

  • Misuse of internal app functionality.
  • Disclosure of sensitive data.
  • Increased risk of remote code execution on older Android versions.

Remediation

  1. Do not add a JavaScript interface to a WebView that loads untrusted content.
  2. Expose as few methods as possible and validate permissions and input in @JavascriptInterface methods.
  3. Load only app-controlled static content instead of external URLs.

Examples

Before

java
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(new Bridge(), "bridge");
webView.loadUrl(userControlledUrl);

After

java
webView.getSettings().setJavaScriptEnabled(false);
webView.loadUrl("file:///android_asset/help.html");

Explanation:

  • Before: Exposing a Java object through addJavascriptInterface lets page scripts call the object's methods.
  • After: Do not use addJavascriptInterface in a WebView that loads untrusted content. This example disables JavaScript and loads a bundled help page.

References