Commit 0c49b45b authored by pichillilorenzo's avatar pichillilorenzo

moved json serialization for JavaScriptBridgeInterface to dart side, fix #64, fix #46

parent a480ebf6
This diff is collapsed.
...@@ -53,5 +53,4 @@ dependencies { ...@@ -53,5 +53,4 @@ dependencies {
implementation 'androidx.browser:browser:1.0.0' implementation 'androidx.browser:browser:1.0.0'
implementation 'androidx.appcompat:appcompat:1.0.2' implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'com.squareup.okhttp3:mockwebserver:3.11.0' implementation 'com.squareup.okhttp3:mockwebserver:3.11.0'
implementation 'com.google.code.gson:gson:2.8.5'
} }
...@@ -4,6 +4,7 @@ import android.app.Activity; ...@@ -4,6 +4,7 @@ import android.app.Activity;
import android.content.Context; import android.content.Context;
import android.util.Log; import android.util.Log;
import android.view.View; import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebChromeClient; import android.webkit.WebChromeClient;
import android.webkit.WebView; import android.webkit.WebView;
import android.webkit.WebViewClient; import android.webkit.WebViewClient;
...@@ -129,6 +130,7 @@ public class FlutterWebView implements PlatformView, MethodCallHandler { ...@@ -129,6 +130,7 @@ public class FlutterWebView implements PlatformView, MethodCallHandler {
if (webView != null) { if (webView != null) {
source = call.argument("source").toString(); source = call.argument("source").toString();
webView.injectScriptCode(source, result); webView.injectScriptCode(source, result);
// ((InputMethodManager) this.activity.getSystemService(Context.INPUT_METHOD_SERVICE)).toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY);
} }
else { else {
result.success(""); result.success("");
......
...@@ -4,7 +4,6 @@ import android.os.Build; ...@@ -4,7 +4,6 @@ import android.os.Build;
import android.util.Log; import android.util.Log;
import android.webkit.JavascriptInterface; import android.webkit.JavascriptInterface;
import com.google.gson.Gson;
import com.pichillilorenzo.flutter_inappbrowser.InAppWebView.InAppWebView; import com.pichillilorenzo.flutter_inappbrowser.InAppWebView.InAppWebView;
import java.util.HashMap; import java.util.HashMap;
...@@ -43,13 +42,12 @@ public class JavaScriptBridgeInterface { ...@@ -43,13 +42,12 @@ public class JavaScriptBridgeInterface {
getChannel().invokeMethod("onCallJsHandler", obj, new MethodChannel.Result() { getChannel().invokeMethod("onCallJsHandler", obj, new MethodChannel.Result() {
@Override @Override
public void success(Object o) { public void success(Object json) {
String json = new Gson().toJson(o);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
flutterWebView.webView.evaluateJavascript("window." + name + "[" + _callHandlerID + "](" + json + ");", null); flutterWebView.webView.evaluateJavascript("window." + name + "[" + _callHandlerID + "](" + json + "); delete window." + name + "[" + _callHandlerID + "];", null);
} }
else { else {
flutterWebView.webView.loadUrl("javascript:window." + name + "[" + _callHandlerID + "](" + json + ");"); flutterWebView.webView.loadUrl("javascript:window." + name + "[" + _callHandlerID + "](" + json + "); delete window." + name + "[" + _callHandlerID + "];");
} }
} }
......
...@@ -32,6 +32,7 @@ ...@@ -32,6 +32,7 @@
window.flutter_inappbrowser.callHandler('handlerTest', 1).then(function(result) { window.flutter_inappbrowser.callHandler('handlerTest', 1).then(function(result) {
console.log(result, typeof result); console.log(result, typeof result);
console.log(JSON.stringify(result));
}); });
}); });
......
...@@ -6,6 +6,20 @@ class InlineExampleScreen extends StatefulWidget { ...@@ -6,6 +6,20 @@ class InlineExampleScreen extends StatefulWidget {
_InlineExampleScreenState createState() => new _InlineExampleScreenState(); _InlineExampleScreenState createState() => new _InlineExampleScreenState();
} }
class User {
String username;
String password;
User({this.username, this.password});
Map<String, dynamic> toJson() {
return {
'username': this.username,
'password': this.password
};
}
}
class _InlineExampleScreenState extends State<InlineExampleScreen> { class _InlineExampleScreenState extends State<InlineExampleScreen> {
InAppWebViewController webView; InAppWebViewController webView;
String url = ""; String url = "";
...@@ -40,15 +54,18 @@ class _InlineExampleScreenState extends State<InlineExampleScreen> { ...@@ -40,15 +54,18 @@ class _InlineExampleScreenState extends State<InlineExampleScreen> {
decoration: decoration:
BoxDecoration(border: Border.all(color: Colors.blueAccent)), BoxDecoration(border: Border.all(color: Colors.blueAccent)),
child: InAppWebView( child: InAppWebView(
initialUrl: "https://flutter.dev/", //initialUrl: "https://mottie.github.io/Keyboard/",
//initialFile: "assets/index.html", initialFile: "assets/index.html",
initialHeaders: {}, initialHeaders: {},
initialOptions: { initialOptions: {
"useShouldOverrideUrlLoading": true, //"useShouldOverrideUrlLoading": true,
"useOnLoadResource": true //"useOnLoadResource": true
}, },
onWebViewCreated: (InAppWebViewController controller) { onWebViewCreated: (InAppWebViewController controller) {
webView = controller; webView = controller;
controller.addJavaScriptHandler('handlerTest', (args) {
return new User(username: 'user', password: 'secret');
});
}, },
onLoadStart: (InAppWebViewController controller, String url) { onLoadStart: (InAppWebViewController controller, String url) {
print("started $url"); print("started $url");
......
...@@ -722,12 +722,9 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi ...@@ -722,12 +722,9 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi
else { else {
var json = "null" var json = "null"
if let r = result { if let r = result {
json = JSONSerializer.toJson(r) json = r as! String
if json == "{}" {
json = "\(r)"
} }
} self.evaluateJavaScript("window.\(JAVASCRIPT_BRIDGE_NAME)[\(_callHandlerID)](\(json)); delete window.\(JAVASCRIPT_BRIDGE_NAME)[\(_callHandlerID)];", completionHandler: nil)
self.evaluateJavaScript("window.\(JAVASCRIPT_BRIDGE_NAME)[\(_callHandlerID)](\(json));", completionHandler: nil)
} }
}) })
} }
......
This diff is collapsed.
...@@ -34,6 +34,17 @@ import 'package:uuid/uuid.dart'; ...@@ -34,6 +34,17 @@ import 'package:uuid/uuid.dart';
import 'package:mime/mime.dart'; import 'package:mime/mime.dart';
typedef Future<dynamic> ListenerCallback(MethodCall call); typedef Future<dynamic> ListenerCallback(MethodCall call);
///This type represents a callback, added with [addJavaScriptHandler], that listens to post messages sent from JavaScript.
///
///The Android implementation uses [addJavascriptInterface](https://developer.android.com/reference/android/webkit/WebView#addJavascriptInterface(java.lang.Object,%20java.lang.String)).
///The iOS implementation uses [addScriptMessageHandler](https://developer.apple.com/documentation/webkit/wkusercontentcontroller/1537172-addscriptmessagehandler?language=objc)
///
///The JavaScript function that can be used to call the handler is `window.flutter_inappbrowser.callHandler(handlerName <String>, ...args);`, where `args` are [rest parameters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters).
///The `args` will be stringified automatically using `JSON.stringify(args)` method and then they will be decoded on the Dart side.
///
///Also, a [JavaScriptHandlerCallback] can return json data to the JavaScript side.
///In this case, simply return data that you want to send and it will be automatically json encoded using [jsonEncode] from the `dart:convert` library.
typedef dynamic JavaScriptHandlerCallback(List<dynamic> arguments); typedef dynamic JavaScriptHandlerCallback(List<dynamic> arguments);
var _uuidGenerator = new Uuid(); var _uuidGenerator = new Uuid();
...@@ -849,7 +860,13 @@ class InAppWebViewController { ...@@ -849,7 +860,13 @@ class InAppWebViewController {
String handlerName = call.arguments["handlerName"]; String handlerName = call.arguments["handlerName"];
List<dynamic> args = jsonDecode(call.arguments["args"]); List<dynamic> args = jsonDecode(call.arguments["args"]);
if (javaScriptHandlersMap.containsKey(handlerName)) { if (javaScriptHandlersMap.containsKey(handlerName)) {
return await javaScriptHandlersMap[handlerName](args); // convert result to json
try {
return jsonEncode(await javaScriptHandlersMap[handlerName](args));
} catch (error) {
print(error);
return null;
}
} }
break; break;
default: default:
...@@ -1145,6 +1162,9 @@ class InAppWebViewController { ...@@ -1145,6 +1162,9 @@ class InAppWebViewController {
/// ///
///The JavaScript function that can be used to call the handler is `window.flutter_inappbrowser.callHandler(handlerName <String>, ...args);`, where `args` are [rest parameters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters). ///The JavaScript function that can be used to call the handler is `window.flutter_inappbrowser.callHandler(handlerName <String>, ...args);`, where `args` are [rest parameters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters).
///The `args` will be stringified automatically using `JSON.stringify(args)` method and then they will be decoded on the Dart side. ///The `args` will be stringified automatically using `JSON.stringify(args)` method and then they will be decoded on the Dart side.
///
///Also, a [JavaScriptHandlerCallback] can return json data to the JavaScript side.
///In this case, simply return data that you want to send and it will be automatically json encoded using [jsonEncode] from the `dart:convert` library.
void addJavaScriptHandler(String handlerName, JavaScriptHandlerCallback callback) { void addJavaScriptHandler(String handlerName, JavaScriptHandlerCallback callback) {
this.javaScriptHandlersMap[handlerName] = (callback); this.javaScriptHandlersMap[handlerName] = (callback);
} }
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment