18
18
import android .graphics .Bitmap ;
19
19
import android .os .Build ;
20
20
import android .text .TextUtils ;
21
+ import android .webkit .JavascriptInterface ;
21
22
import android .webkit .WebView ;
22
23
import android .webkit .WebViewClient ;
23
24
import android .webkit .WebChromeClient ;
@@ -180,6 +181,9 @@ private WritableMap createWebViewEvent(WebView webView, String url) {
180
181
* to call {@link WebView#destroy} on activty destroy event and also to clear the client
181
182
*/
182
183
private static class ReactWebView extends WebView implements LifecycleEventListener {
184
+ public static final String JAVASCRIPT_INTERFACE_NAME = "JS_INTERFACE" ;
185
+ private static final String JAVASCRIPT_INTERFACE_METHOD = "processInjectedJavaScript" ;
186
+
183
187
private @ Nullable String injectedJS ;
184
188
185
189
/**
@@ -216,14 +220,41 @@ public void callInjectedJavaScript() {
216
220
if (getSettings ().getJavaScriptEnabled () &&
217
221
injectedJS != null &&
218
222
!TextUtils .isEmpty (injectedJS )) {
219
- loadUrl ("javascript:(function() {\n " + injectedJS + ";\n })();" );
223
+ loadUrl ("javascript:window."
224
+ + JAVASCRIPT_INTERFACE_NAME + "." + JAVASCRIPT_INTERFACE_METHOD
225
+ + "(" + injectedJS + ");" );
220
226
}
221
227
}
222
228
223
229
private void cleanupCallbacksAndDestroy () {
224
230
setWebViewClient (null );
225
231
destroy ();
226
232
}
233
+
234
+ @ JavascriptInterface
235
+ @ SuppressWarnings ("unused" )
236
+ public void processInjectedJavaScript (final String jsEvaluationValue ) {
237
+ dispatchEvent (
238
+ this ,
239
+ new TopLoadingFinishEvent (
240
+ getId (),
241
+ SystemClock .nanoTime (),
242
+ createWebViewEvent (this , jsEvaluationValue )));
243
+ }
244
+
245
+ private static void dispatchEvent (WebView webView , Event event ) {
246
+ ReactContext reactContext = (ReactContext ) webView .getContext ();
247
+ EventDispatcher eventDispatcher =
248
+ reactContext .getNativeModule (UIManagerModule .class ).getEventDispatcher ();
249
+ eventDispatcher .dispatchEvent (event );
250
+ }
251
+
252
+ private WritableMap createWebViewEvent (WebView webView , String jsEvaluationValue ) {
253
+ WritableMap event = Arguments .createMap ();
254
+ event .putDouble ("target" , webView .getId ());
255
+ event .putString ("jsEvaluationValue" , jsEvaluationValue );
256
+ return event ;
257
+ }
227
258
}
228
259
229
260
public ReactWebViewManager () {
@@ -246,6 +277,7 @@ public String getName() {
246
277
protected WebView createViewInstance (ThemedReactContext reactContext ) {
247
278
ReactWebView webView = new ReactWebView (reactContext );
248
279
webView .setWebChromeClient (new WebChromeClient ());
280
+ webView .addJavascriptInterface (webView , ReactWebView .JAVASCRIPT_INTERFACE_NAME );
249
281
reactContext .addLifecycleEventListener (webView );
250
282
mWebViewConfig .configWebView (webView );
251
283
0 commit comments