Thibault Malbranche 6 years ago
parent
commit
2e3232caa0

+ 20
- 4
android/src/main/java/com/reactnativecommunity/webview/RCTWebViewManager.java View File

@@ -9,6 +9,7 @@ import java.util.regex.Pattern;
9 9
 import javax.annotation.Nullable;
10 10
 
11 11
 import java.io.UnsupportedEncodingException;
12
+import java.net.URLEncoder;
12 13
 import java.util.ArrayList;
13 14
 import java.util.HashMap;
14 15
 import java.util.Locale;
@@ -318,11 +319,24 @@ public class RCTWebViewManager extends SimpleViewManager<WebView> {
318 319
       }
319 320
     }
320 321
 
322
+    protected void evaluateJavascriptWithFallback(String script) {
323
+      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
324
+        evaluateJavascript(script, null);
325
+        return;
326
+      }
327
+       try {
328
+        loadUrl("javascript:" + URLEncoder.encode(script, "UTF-8"));
329
+      } catch (UnsupportedEncodingException e) {
330
+        // UTF-8 should always be supported
331
+        throw new RuntimeException(e);
332
+      }
333
+    }
334
+
321 335
     public void callInjectedJavaScript() {
322 336
       if (getSettings().getJavaScriptEnabled() &&
323 337
           injectedJS != null &&
324 338
           !TextUtils.isEmpty(injectedJS)) {
325
-        loadUrl("javascript:(function() {\n" + injectedJS + ";\n})();");
339
+        evaluateJavascriptWithFallback("(function() {\n" + injectedJS + ";\n})();");
326 340
       }
327 341
     }
328 342
 
@@ -341,7 +355,7 @@ public class RCTWebViewManager extends SimpleViewManager<WebView> {
341 355
           });
342 356
         }
343 357
 
344
-        loadUrl("javascript:(" +
358
+        evaluateJavascriptWithFallback("(" +
345 359
           "window.originalPostMessage = window.postMessage," +
346 360
           "window.postMessage = function(data) {" +
347 361
             BRIDGE_NAME + ".postMessage(String(data));" +
@@ -630,9 +644,10 @@ public class RCTWebViewManager extends SimpleViewManager<WebView> {
630 644
         break;
631 645
       case COMMAND_POST_MESSAGE:
632 646
         try {
647
+          ReactWebView reactWebView = (ReactWebView) root;
633 648
           JSONObject eventInitDict = new JSONObject();
634 649
           eventInitDict.put("data", args.getString(0));
635
-          root.loadUrl("javascript:(function () {" +
650
+          reactWebView.evaluateJavascriptWithFallback("(function () {" +
636 651
             "var event;" +
637 652
             "var data = " + eventInitDict.toString() + ";" +
638 653
             "try {" +
@@ -648,7 +663,8 @@ public class RCTWebViewManager extends SimpleViewManager<WebView> {
648 663
         }
649 664
         break;
650 665
       case COMMAND_INJECT_JAVASCRIPT:
651
-        root.loadUrl("javascript:" + args.getString(0));
666
+        ReactWebView reactWebView = (ReactWebView) root;
667
+        reactWebView.evaluateJavascriptWithFallback(args.getString(0));
652 668
         break;
653 669
     }
654 670
   }