Slide 1

Slide 1 text

Android and the WebView @ErikHellman speakerdeck.com/erikhellman/android-and-the-webview

Slide 2

Slide 2 text

If all you have is a hammer, everything looks like a nail!

Slide 3

Slide 3 text

What else would you really need?!? val webView = findViewById(R.id.webView) webView.loadUrl("https://dailykitten.com")

Slide 4

Slide 4 text

No content

Slide 5

Slide 5 text

Don't use the WebView!

Slide 6

Slide 6 text

Use Chrome Custom Tabs instead!

Slide 7

Slide 7 text

Chrome Custom Tabs Gradle: implementation 'androidx.browser:browser:x.y.z' Kotlin: val url = Uri.parse("https://dailykitten.com") CustomTabsIntent.Builder().build().launchUrl(this, url)

Slide 8

Slide 8 text

Customizing toolbar color val url = Uri.parse("https://dailykitten.com") CustomTabsIntent.Builder() .setToolbarColor(R.color.mainCoonGrey) .build().launchUrl(this, url)

Slide 9

Slide 9 text

Custom action button val icon = R.drawable.cat val description = R.string.send_to_cat val pendingIntent = PendingIntent.getActivity(...) val tint = true CustomTabsIntent.Builder() .setActionButton(icon, description, pendingIntent, tint) .build().launchUrl(this, url)

Slide 10

Slide 10 text

Customizing transitions CustomTabsIntent.Builder() .setStartAnimations(this, R.anim.fancy_in_anim, R.anim.fancy_out_anim) .setExitAnimations(this, R.anim.fancy_out_anim, R.anim.fancy_in_anim) .build().launchUrl(this, url)

Slide 11

Slide 11 text

Launch pages faster val connection = object : CustomTabsServiceConnection() { override fun onCustomTabsServiceConnected(name: ComponentName, client: CustomTabsClient) { client.warmup(0) client.newSession(CustomTabsCallback()) .mayLaunchUrl(Uri.parse("https://dailykitten.com"), Bundle.EMPTY, emptyList()) } override fun onServiceDisconnected(name: ComponentName) { } } CustomTabsClient.bindCustomTabsService(this, "com.android.chrome", connection)

Slide 12

Slide 12 text

android.webkit.WebView

Slide 13

Slide 13 text

Avoid WebView if possible!

Slide 14

Slide 14 text

When NOT to use WebView1 — Displaying SVG images — Login dialogs (Except when you must) — Wrapping your mobile website in an APK 1 Not a complete list...

Slide 15

Slide 15 text

When to use WebView2 — Displaying local HTML formatted content — Web-only authentication 2 Mostly complete list.

Slide 16

Slide 16 text

No content

Slide 17

Slide 17 text

No content

Slide 18

Slide 18 text

Getting Started 1. Enable Chrome Dev tools // Enable Chrome Dev Tools with chrome://inspect WebView.setWebContentsDebuggingEnabled(BuildConfig.DEBUG)

Slide 19

Slide 19 text

Getting Started 1.2 Chrome Dev Tools (chrome://inspect)

Slide 20

Slide 20 text

Getting Started 1.3 Chrome Dev Tools

Slide 21

Slide 21 text

Getting Started 2. Add compat library dependencies { ... implementation 'androidx.webkit:webkit:x.y.z' ... }

Slide 22

Slide 22 text

Getting Started 3. Configure your WebView val webView = findViewById(R.id.webView) webView.settings.apply { ... }

Slide 23

Slide 23 text

Getting Started 3.1 Basic settings // Enable if your content uses JavaScript javaScriptEnabled = true // For localStorage or sessionStorage domStorageEnabled = true // Web Database API support (IndexedDB) databaseEnabled = true // true if the WebView supports the viewport meta tag useWideViewPort = true // Support zooming displayZoomControls = false builtInZoomControls = false

Slide 24

Slide 24 text

Getting Started 3.2 Caching // Overrides the way the cache is used cacheMode = WebSettings.LOAD_NO_CACHE

Slide 25

Slide 25 text

Getting Started 3.3 File and content URLs // How to support file:/// URLs (Don't!) allowFileAccess = false allowFileAccessFromFileURLs = false allowUniversalAccessFromFileURLs = false // Allow access to ContentProvider URLs allowContentAccess = false

Slide 26

Slide 26 text

Getting Started 4.1 Load your remote content3 val webView = findViewById(R.id.webView) val url = "https://api.catz.com/news/content/12345" webView.loadUrl(url) 3 Don't do this - see later slides.

Slide 27

Slide 27 text

Getting Started 4.2 Load generated content val html = """ Cats!

Cats are awesome!

""" val htmlBytes = html.toByteArray(charset("UTF-8")) val encodedHtml = Base64.encodeToString(htmlBytes, Base64.NO_WRAP) webView.loadData(encodedHtml, "text/html", "base64")

Slide 28

Slide 28 text

Getting Started 4.3 Loading local content (the right way!) val url = "https://catz.androidplatform.net/index.html" val webView = findViewById(R.id.webView) webView.loadUrl(url)

Slide 29

Slide 29 text

WebViewClient

Slide 30

Slide 30 text

WebViewClient

Slide 31

Slide 31 text

WebViewClient

Slide 32

Slide 32 text

WebViewClient usage — Intercept WebView requests — Override network response with custom content — Always use WebViewClientCompat!

Slide 33

Slide 33 text

shouldOverrideUrlLoading() — Only for GET requests — Don't call WebView.loadUrl() or WebView.loadData() here — Useful for capturing auth tokens

Slide 34

Slide 34 text

Capturing OAuth 2 auth code val webView = findViewById(R.id.webView) webView.webViewClient = object : WebViewClientCompat() { override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean { if (request.url.toString().startsWith(REDIRECT_URL)) { return handleLoginSuccess(request) } return false } } val loginUrl = ... // Login URL with redirect URL webView.loadUrl(loginUrl)

Slide 35

Slide 35 text

androidplatform.net One potential problem of hosting local resources on a http(s):// URL is that doing so may conflict with a real website... The androidplatform.net domain has been specifically reserved for this purpose and you are free to use it. — https://github.com/google/webview-local-server

Slide 36

Slide 36 text

Loading local content safely webView.webViewClient = object : WebViewClientCompat() { override fun shouldInterceptRequest(view: WebView?, request: WebResourceRequest?): WebResourceResponse? { // Read local content and return a WebResourceResponse return createResponse(request) } } webView.loadUrl("https://catz.androidplatform.net/index.html)

Slide 37

Slide 37 text

Loading local content safely fun createResponse(request: WebResourceRequest): WebResourceResponse { val path = request.url.path val file = fileFromUrlPath(path) if (!file.exists()) { return WebResourceResponse("text/plain", "utf-8", 404, "Not Found", emptyMap(), ByteArrayInputStream(ByteArray(0))) } val (mimeType, encoding) = mimeTypeAndEncodingForFile(file) return WebResourceResponse(mimeType, encoding, 200, "OK", emptyMap(), FileInputStream(file)) }

Slide 38

Slide 38 text

WebViewServer.kt - http://bit.ly/2xkYMGD open class FileRequestHandler(file: File, private val requestPath: String, private val mimeType: String, private val encoding: String) : RequestHandler { private val bytes = FileInputStream(file).use { it.readBytes() } override fun shouldHandleRequest(request: Request): Boolean { val uri = Uri.parse(requestPath) return uri.path == request.path } override fun handleRequest(request: Request): Response { return Response(200, "OK", emptyMap(), mimeType, encoding, ByteArrayInputStream(bytes)) } }

Slide 39

Slide 39 text

Bridging Android and JavaScript

Slide 40

Slide 40 text

Bridging Android and JavaScript (old version) class MyJavaScriptInterface(private val handler: Handler) { fun onEvent(data: String) { val json = JSONObject(data) Message.obtain(handler, JS_MSG, json).sendToTarget() } companion object { const val JS_MSG = 10 } }

Slide 41

Slide 41 text

Bridging Android and JavaScript (old version) val webView = findViewById(R.id.webView) val jsInterface = MyJavaScriptInterface(jsHandler) webView.addJavascriptInterface(jsInterface, "android")

Slide 42

Slide 42 text

Bridging Android and JavaScript (old version) function emitEventToAndroid(data) { if (android && typeof android.onEvent === 'function') { android.onEvent(JSON.stringify(data)); } }

Slide 43

Slide 43 text

Bridging Android and JavaScript (old version) // JavaScript function we will call from Android function performAction(name, age) { return `${name} is ${age} years old!` } val name = Erik val age = 42 webView.evaluateJavascript("performAction($name, $age)") { value -> // value will be "Erik is 42 years old!" }

Slide 44

Slide 44 text

Bridging Android and JavaScript (old version) — Threading — Binding native objects — Calling function by strings

Slide 45

Slide 45 text

Better solution: MessageChannel!

Slide 46

Slide 46 text

Bridging Android and JavaScript (new version) // Creates two MessageChannel ports val (port1, port2) = WebViewCompat.createWebMessageChannel(webView) port1.setWebMessageCallback(object: WebMessagePortCompat.WebMessageCallbackCompat() { override fun onMessage(port: WebMessagePortCompat, message: WebMessageCompat?) { message?.data?.also{ val data = JSONObject(it) handleWebEvent(data); } } }) // Send init message to JS side val initMsg = WebMessageCompat("""{type: "init"}""", arrayOf(port2)) WebViewCompat.postWebMessage(webView, initMsg, Uri.parse("*"))

Slide 47

Slide 47 text

Bridging Android and JavaScript (new version) let nativePort = null; window.addEventListener('message', message => { if (e.data) { val msg = JSON.parse(e.data); if (msg.type === 'init') { nativePort = e.ports[0]; } else { onNativeMessage(msg); } } }); function sendMessageToNative(data) { nativePort.postMessage(JSON.stringify(data)); }

Slide 48

Slide 48 text

Customizing local web content

Slide 49

Slide 49 text

ePub standard

Slide 50

Slide 50 text

ePub in 1 slide — W3C standards (2.0, 3.x) — ZIP file (or directory) structure — Self-contained web content — Requires custom JS and CSS for rendering

Slide 51

Slide 51 text

ePub structure

Slide 52

Slide 52 text

ePub structure

Slide 53

Slide 53 text

Package document The Dark World ... ... ... ...

Slide 54

Slide 54 text

ePub scrolling

Slide 55

Slide 55 text

Wrapping web content (HTML)

Slide 56

Slide 56 text

Wrapping web content (HTML) ePub Reader

Slide 57

Slide 57 text

Injecting CSS fun loadEpub(spineItems) { const resourceRoot = document.querySelector('#resourceRoot'); spineItems.forEach(item => { const iframe = document.createElement('iframe'); iframe.addEventListener('load', () => { const cssLink = document.createElement('link'); cssLink.rel = 'stylesheet'; cssLink.type = 'text/css'; cssLink.addEventListener('load', () => { console.log('Chapter loaded with custom CSS!'); }); cssLink.href = '/chapter.css' // Add custom CSS to this chapter const head = iframe.contentDocument.querySelector('head') head.appendChild(cssLink); }); resourceRoot.appendChild(iframe); // Start loading chapter in iframe iframe.src = item.href; }); }

Slide 58

Slide 58 text

Injected CSS :root { column-gap: 20px; column-width: 45em; column-count: 1; column-fill: auto; will-change: transform; } body { overflow: hidden !important; column-span: none !important; box-sizing: border-box !important; break-inside: avoid !important; }

Slide 59

Slide 59 text

Demo!

Slide 60

Slide 60 text

Dos and Donts 1. Don't run a local web server for local web content 2. Don't scroll web content from native 3. Avoid multiple WebViews 4. Use MessageChannel for bridging 5. Use WebViewClientCompat for loading local content 6. WebView is auto-updated with Chrome (except on Android 5!)

Slide 61

Slide 61 text

WebView resources - Native Bridge Android A lightweight and efficient bridge between webview and native apps (Android & iOS). github.com/nrkno/nativebridge-android - WebViewServer.kt A customizable "server" for Android WebView: http://bit.ly/2xkYMGD - WebView Local Server from Google A simple implementation for loading local content.

Slide 62

Slide 62 text

Thank you for listening! @ErikHellman speakerdeck.com/erikhellman/android-and-the-webview