| Shimi Zhang | da40d0f | 2020-09-03 20:17:27 | [diff] [blame] | 1 | # WebView Java Bridge (WebView#addJavascriptInterface()) |
| 2 | |
| 3 | [TOC] |
| 4 | |
| 5 | ## Overview |
| 6 | |
| 7 | This page explains ideas behind the Java ↔ JavaScript bridge |
| 8 | implementation. This is to ensure that important use cases and scenarios, which |
| 9 | must be preserved regardless of how the bridge is implemented, are captured. The |
| 10 | need for this description arose while migrating the NPAPI-based implementation |
| 11 | to a [Gin](/gin/)-based implementation. Although a vast number of unit tests |
| 12 | already existed, they still didn't cover all important aspects of the bridge |
| 13 | behavior and we had to add some new tests to ensure we are preserving |
| 14 | compatibility. |
| 15 | |
| Shimi Zhang | da40d0f | 2020-09-03 20:17:27 | [diff] [blame] | 16 | ## The API |
| 17 | |
| 18 | An API for embedders is exposed on |
| 19 | [android.webkit.WebView](https://developer.android.com/reference/android/webkit/WebView.html) |
| 20 | class: |
| 21 | |
| 22 | - [public void **addJavascriptInterface**(Object **object**, String |
| 23 | **name**)](https://developer.android.com/reference/android/webkit/WebView.html#addJavascriptInterface(java.lang.Object,%20java.lang.String)) |
| 24 | -- injects a Java **object** into a WebView under the given **name**; |
| 25 | - [public void **removeJavascriptInterface**(String |
| 26 | **name**)](https://developer.android.com/reference/android/webkit/WebView.html#removeJavascriptInterface(java.lang.String)) |
| 27 | -- removes an object previously injected under the **name**. |
| 28 | |
| 29 | Important notes as defined by the API: |
| 30 | - adding or removing an injected object is not reflected on the JavaScript side |
| 31 | until the next page load; |
| 32 | - only methods annotated as |
| 33 | [`@JavascriptInterface`](https://developer.android.com/reference/android/webkit/JavascriptInterface.html) |
| 34 | are exposed to JavaScript code; Java object fields are never exposed; |
| 35 | - methods of Java objects are invoked on a private, background thread of |
| 36 | WebView; this effectively means, that the interaction originated by the page |
| 37 | must be served entirely on the background thread, while the main application |
| 38 | thread (browser UI thread) is blocked; |
| 39 | |
| 40 | Argument and return values conversions are handled after [Sun Live Connect 2 |
| 41 | spec](https://www.oracle.com/java/technologies/javase/liveconnect-docs.html). In |
| 42 | fact, there are lots of deviations from it (probably, to preserve compatibility |
| 43 | with earlier WebView versions). What can pass the boundary between VMs is |
| 44 | somewhat limited. This is what is allowed: |
| 45 | - primitive values; |
| 46 | - single-dimentional arrays; |
| 47 | - "array-like" JavaScript objects (possessing "length" property, and also typed |
| 48 | arrays from ES6); |
| 49 | - previously injected Java objects (from JS to Java); |
| 50 | - new Java objects (from Java to JS), those are "injected" into JavaScript as if |
| 51 | one called **addJavascriptInterface**, but w/o providing a name; also, the |
| 52 | lifecycle of such transient objects is different (see below). |
| 53 | |
| 54 | ## Objects Lifecycle |
| 55 | |
| 56 | The purpose of Java bridge is to establish interaction between two virtual |
| 57 | machines (VMs): Java and JavaScript. Both VMs employ a similar approach to |
| Nate Fischer | b84a88e | 2022-03-10 17:11:00 | [diff] [blame] | 58 | managing objects lifetime—VMs gather and dispose unreferenced objects during |
| Shimi Zhang | da40d0f | 2020-09-03 20:17:27 | [diff] [blame] | 59 | garbage collection (GC) cycles. The twist that Java bridge adds is that objects |
| 60 | in one VM can now virtually reference (and prevent from being disposed) objects |
| 61 | from another VM. Let us consider the following Java code: |
| 62 | |
| 63 | ```Java |
| 64 | // in Java |
| 65 | webView.addJavascriptInterface(new MyObject(), "myObject"); |
| 66 | ``` |
| 67 | |
| 68 | The instantiated MyObject is now being virtually hold by its JavaScript |
| 69 | counterpart, and is not garbage-collected by Java VM despite the fact that there |
| 70 | are no explicit references to it on the Java side. The MyObject instance is kept |
| 71 | referenced until the action of the **addJavascriptInterface** call is cancelled |
| 72 | by a call to **removeJavascriptInterface**: |
| 73 | |
| 74 | ```Java |
| 75 | // in Java |
| 76 | webView.removeJavascriptInterface("myObject"); |
| 77 | ``` |
| 78 | |
| 79 | A more interesting situation is with transient objects returned from methods of |
| 80 | an injected Java object. Consider the following example: |
| 81 | |
| 82 | ```Java |
| 83 | // in Java |
| 84 | class MyObject { |
| 85 | class Handler { |
| 86 | } |
| 87 | |
| 88 | @JavascriptInterface |
| 89 | public Object getHandler() { return new Handler(); } |
| 90 | } |
| 91 | ``` |
| 92 | |
| 93 | Again, the object returned from **`getHandler`** method is not explicitly |
| 94 | referenced on the Java side, albeit it should not be disposed until it is in use |
| 95 | on the JavaScript side. The "in use" period is determined by the lifetime of the |
| 96 | JavaScript interface object that has been implicitly created as a result of a |
| 97 | call to **getHandler** from JavaScript. That means, the instance of Handler on |
| 98 | the Java side should be kept alive during the period while the corresponding |
| 99 | JavaScript interface object is still referenced: |
| 100 | |
| 101 | ```JavaScript |
| 102 | // in JavaScript |
| 103 | { |
| 104 | ... |
| 105 | let handler = myObject.getHandler(); |
| 106 | ... |
| 107 | } |
| 108 | ``` |
| 109 | |
| 110 | The following figure illustrates relationships between Java and JavaScript |
| 111 | objects created in the previous examples: |
| 112 | |
| 113 |  |
| 115 | |
| 116 | Note that Java and JavaScript VMs are absolutely independent and unaware of each |
| 117 | other's existence. They can work in different processes and, in theory, even on |
| 118 | different physical machines. Thus, the depicted references from JavaScript |
| 119 | objects to Java objects are virtual—they don't exist directly. Instead, it is |
| 120 | the Java bridge who holds the Java objects for as long as it is needed. We would |
| 121 | like to depict that, but first we need to consider the whole picture. |
| 122 | |
| 123 | So far, we were thinking about Java bridge in abstract terms. But in fact, it is |
| 124 | used in the context of a WebView-based application. The Java side of the bridge |
| 125 | is tightly coupled to an instance of WebView class, while bridge's JavaScript |
| 126 | side is bound to a HTML rendering engine. This is further complicated by the |
| 127 | facts that in the Chromium architecture renderers are isolated from their |
| 128 | controlling entities, and that Chromium is mainly implemented in C++, but needs |
| 129 | to interact with Android framework which is implemented in Java. |
| 130 | |
| 131 | Thus, if we want to depict the architecture of Java bridge, we also need to |
| 132 | include parts of the Chromium framework that are glued to Java bridge: |
| 133 | |
| 134 |  |
| 135 | |
| 136 | The figure is now much scarier. Let's figure out what is what here: |
| 137 | - In Java VM (browser side): |
| 138 | **WebView** is android.webkit.WebView class. It is exposed to the embedder and |
| 139 | interacts with Chromium rendering machinery. WebView owns a retaining set |
| 140 | (**`Set<Object>`**) that holds all injected objects to prevent their |
| 141 | collection. Note that WebView class manages a C++ object called |
| 142 | **WebContents** (in fact, the relationship is more complex, but these details |
| 143 | are not relevant for us). As Java Bridge implementation is in C++, the |
| 144 | retaining set is actually managed by the C++ side, but objects from the |
| 145 | native side do not hold any strong references to it, as that would create a |
| 146 | cyclic reference and will prevent the WebView instance from being collected. |
| 147 | - On the C++ browser side: |
| 148 | Here we have the aforementioned **WebContents** object which delegates Java |
| 149 | Bridge-related requests to **JavaBridgeHost**. WebContents talks to the |
| Nate Fischer | ff389b6 | 2021-11-25 11:28:38 | [diff] [blame] | 150 | objects on the renderer side via Chromium's IPC mechanism. |
| Shimi Zhang | da40d0f | 2020-09-03 20:17:27 | [diff] [blame] | 151 | - On the C++ renderer side: |
| 152 | **RenderFrame** corresponds to a single HTML frame and it "owns" a JavaScript |
| 153 | global context object (aka **window**). For each JavaScript interface object, |
| Nate Fischer | ff389b6 | 2021-11-25 11:28:38 | [diff] [blame] | 154 | a corresponding **JavaBridgeObject** instance is maintained. In Chromium |
| Shimi Zhang | da40d0f | 2020-09-03 20:17:27 | [diff] [blame] |
|