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 {
implementation 'androidx.browser:browser:1.0.0'
implementation 'androidx.appcompat:appcompat:1.0.2'
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;
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
......@@ -129,6 +130,7 @@ public class FlutterWebView implements PlatformView, MethodCallHandler {
if (webView != null) {
source = call.argument("source").toString();
webView.injectScriptCode(source, result);
// ((InputMethodManager) this.activity.getSystemService(Context.INPUT_METHOD_SERVICE)).toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY);
}
else {
result.success("");
......
......@@ -4,7 +4,6 @@ import android.os.Build;
import android.util.Log;
import android.webkit.JavascriptInterface;
import com.google.gson.Gson;
import com.pichillilorenzo.flutter_inappbrowser.InAppWebView.InAppWebView;
import java.util.HashMap;
......@@ -43,13 +42,12 @@ public class JavaScriptBridgeInterface {
getChannel().invokeMethod("onCallJsHandler", obj, new MethodChannel.Result() {
@Override
public void success(Object o) {
String json = new Gson().toJson(o);
public void success(Object json) {
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 {
flutterWebView.webView.loadUrl("javascript:window." + name + "[" + _callHandlerID + "](" + json + ");");
flutterWebView.webView.loadUrl("javascript:window." + name + "[" + _callHandlerID + "](" + json + "); delete window." + name + "[" + _callHandlerID + "];");
}
}
......
......@@ -32,6 +32,7 @@
window.flutter_inappbrowser.callHandler('handlerTest', 1).then(function(result) {
console.log(result, typeof result);
console.log(JSON.stringify(result));
});
});
......
......@@ -6,6 +6,20 @@ class InlineExampleScreen extends StatefulWidget {
_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> {
InAppWebViewController webView;
String url = "";
......@@ -40,15 +54,18 @@ class _InlineExampleScreenState extends State<InlineExampleScreen> {
decoration:
BoxDecoration(border: Border.all(color: Colors.blueAccent)),
child: InAppWebView(
initialUrl: "https://flutter.dev/",
//initialFile: "assets/index.html",
//initialUrl: "https://mottie.github.io/Keyboard/",
initialFile: "assets/index.html",
initialHeaders: {},
initialOptions: {
"useShouldOverrideUrlLoading": true,
"useOnLoadResource": true
//"useShouldOverrideUrlLoading": true,
//"useOnLoadResource": true
},
onWebViewCreated: (InAppWebViewController controller) {
webView = controller;
controller.addJavaScriptHandler('handlerTest', (args) {
return new User(username: 'user', password: 'secret');
});
},
onLoadStart: (InAppWebViewController controller, String url) {
print("started $url");
......
......@@ -722,12 +722,9 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi
else {
var json = "null"
if let r = result {
json = JSONSerializer.toJson(r)
if json == "{}" {
json = "\(r)"
}
json = r as! String
}
self.evaluateJavaScript("window.\(JAVASCRIPT_BRIDGE_NAME)[\(_callHandlerID)](\(json));", completionHandler: nil)
self.evaluateJavaScript("window.\(JAVASCRIPT_BRIDGE_NAME)[\(_callHandlerID)](\(json)); delete window.\(JAVASCRIPT_BRIDGE_NAME)[\(_callHandlerID)];", completionHandler: nil)
}
})
}
......
This diff is collapsed.
......@@ -34,6 +34,17 @@ import 'package:uuid/uuid.dart';
import 'package:mime/mime.dart';
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);
var _uuidGenerator = new Uuid();
......@@ -849,7 +860,13 @@ class InAppWebViewController {
String handlerName = call.arguments["handlerName"];
List<dynamic> args = jsonDecode(call.arguments["args"]);
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;
default:
......@@ -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 `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) {
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