Commit 0c49b45b authored by pichillilorenzo's avatar pichillilorenzo

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

parent a480ebf6
......@@ -15,30 +15,24 @@
</component>
<component name="ChangeListManager">
<list default="true" id="9b41f7a2-a71e-4923-91fb-249d7815b3e7" name="Default" comment="">
<change afterPath="$PROJECT_DIR$/example/ios/.symlinks/plugins/flutter_inappbrowser/ios/Classes/JsonSerializer.swift" afterDir="false" />
<change afterPath="$PROJECT_DIR$/ios/Classes/JsonSerializer.swift" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/android/build.gradle" beforeDir="false" afterPath="$PROJECT_DIR$/android/build.gradle" afterDir="false" />
<change beforePath="$PROJECT_DIR$/android/src/main/java/com/pichillilorenzo/flutter_inappbrowser/InAppWebView/InAppWebView.java" beforeDir="false" afterPath="$PROJECT_DIR$/android/src/main/java/com/pichillilorenzo/flutter_inappbrowser/InAppWebView/InAppWebView.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/android/src/main/java/com/pichillilorenzo/flutter_inappbrowser/InAppWebView/InAppWebViewClient.java" beforeDir="false" afterPath="$PROJECT_DIR$/android/src/main/java/com/pichillilorenzo/flutter_inappbrowser/InAppWebView/InAppWebViewClient.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/android/src/main/java/com/pichillilorenzo/flutter_inappbrowser/FlutterWebView.java" beforeDir="false" afterPath="$PROJECT_DIR$/android/src/main/java/com/pichillilorenzo/flutter_inappbrowser/FlutterWebView.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/android/src/main/java/com/pichillilorenzo/flutter_inappbrowser/JavaScriptBridgeInterface.java" beforeDir="false" afterPath="$PROJECT_DIR$/android/src/main/java/com/pichillilorenzo/flutter_inappbrowser/JavaScriptBridgeInterface.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/example/assets/index.html" beforeDir="false" afterPath="$PROJECT_DIR$/example/assets/index.html" afterDir="false" />
<change beforePath="$PROJECT_DIR$/example/ios/.symlinks/plugins/flutter_inappbrowser/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/example/ios/.symlinks/plugins/flutter_inappbrowser/.idea/workspace.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/example/ios/.symlinks/plugins/flutter_inappbrowser/android/build.gradle" beforeDir="false" afterPath="$PROJECT_DIR$/example/ios/.symlinks/plugins/flutter_inappbrowser/android/build.gradle" afterDir="false" />
<change beforePath="$PROJECT_DIR$/example/ios/.symlinks/plugins/flutter_inappbrowser/android/src/main/java/com/pichillilorenzo/flutter_inappbrowser/InAppWebView/InAppWebView.java" beforeDir="false" afterPath="$PROJECT_DIR$/example/ios/.symlinks/plugins/flutter_inappbrowser/android/src/main/java/com/pichillilorenzo/flutter_inappbrowser/InAppWebView/InAppWebView.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/example/ios/.symlinks/plugins/flutter_inappbrowser/android/src/main/java/com/pichillilorenzo/flutter_inappbrowser/InAppWebView/InAppWebViewClient.java" beforeDir="false" afterPath="$PROJECT_DIR$/example/ios/.symlinks/plugins/flutter_inappbrowser/android/src/main/java/com/pichillilorenzo/flutter_inappbrowser/InAppWebView/InAppWebViewClient.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/example/ios/.symlinks/plugins/flutter_inappbrowser/android/src/main/java/com/pichillilorenzo/flutter_inappbrowser/FlutterWebView.java" beforeDir="false" afterPath="$PROJECT_DIR$/example/ios/.symlinks/plugins/flutter_inappbrowser/android/src/main/java/com/pichillilorenzo/flutter_inappbrowser/FlutterWebView.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/example/ios/.symlinks/plugins/flutter_inappbrowser/android/src/main/java/com/pichillilorenzo/flutter_inappbrowser/JavaScriptBridgeInterface.java" beforeDir="false" afterPath="$PROJECT_DIR$/example/ios/.symlinks/plugins/flutter_inappbrowser/android/src/main/java/com/pichillilorenzo/flutter_inappbrowser/JavaScriptBridgeInterface.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/example/ios/.symlinks/plugins/flutter_inappbrowser/example/assets/index.html" beforeDir="false" afterPath="$PROJECT_DIR$/example/ios/.symlinks/plugins/flutter_inappbrowser/example/assets/index.html" afterDir="false" />
<change beforePath="$PROJECT_DIR$/example/ios/.symlinks/plugins/flutter_inappbrowser/example/lib/inline_example.screen.dart" beforeDir="false" afterPath="$PROJECT_DIR$/example/ios/.symlinks/plugins/flutter_inappbrowser/example/lib/inline_example.screen.dart" afterDir="false" />
<change beforePath="$PROJECT_DIR$/example/ios/.symlinks/plugins/flutter_inappbrowser/flutter_inappbrowser.iml" beforeDir="false" afterPath="$PROJECT_DIR$/example/ios/.symlinks/plugins/flutter_inappbrowser/flutter_inappbrowser.iml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/example/ios/.symlinks/plugins/flutter_inappbrowser/ios/Classes/InAppWebView.swift" beforeDir="false" afterPath="$PROJECT_DIR$/example/ios/.symlinks/plugins/flutter_inappbrowser/ios/Classes/InAppWebView.swift" afterDir="false" />
<change beforePath="$PROJECT_DIR$/example/ios/.symlinks/plugins/flutter_inappbrowser/ios/Classes/JsonSerializer.swift" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/example/ios/.symlinks/plugins/flutter_inappbrowser/lib/flutter_inappbrowser.dart" beforeDir="false" afterPath="$PROJECT_DIR$/example/ios/.symlinks/plugins/flutter_inappbrowser/lib/flutter_inappbrowser.dart" afterDir="false" />
<change beforePath="$PROJECT_DIR$/example/ios/.symlinks/plugins/flutter_inappbrowser/pubspec.yaml" beforeDir="false" afterPath="$PROJECT_DIR$/example/ios/.symlinks/plugins/flutter_inappbrowser/pubspec.yaml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/example/lib/inline_example.screen.dart" beforeDir="false" afterPath="$PROJECT_DIR$/example/lib/inline_example.screen.dart" afterDir="false" />
<change beforePath="$PROJECT_DIR$/flutter_inappbrowser.iml" beforeDir="false" afterPath="$PROJECT_DIR$/flutter_inappbrowser.iml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/ios/Classes/InAppWebView.swift" beforeDir="false" afterPath="$PROJECT_DIR$/ios/Classes/InAppWebView.swift" afterDir="false" />
<change beforePath="$PROJECT_DIR$/ios/Classes/JsonSerializer.swift" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/lib/flutter_inappbrowser.dart" beforeDir="false" afterPath="$PROJECT_DIR$/lib/flutter_inappbrowser.dart" afterDir="false" />
<change beforePath="$PROJECT_DIR$/pubspec.yaml" beforeDir="false" afterPath="$PROJECT_DIR$/pubspec.yaml" afterDir="false" />
</list>
<ignored path="$PROJECT_DIR$/.dart_tool/" />
<ignored path="$PROJECT_DIR$/.idea/" />
......@@ -56,39 +50,41 @@
<session id="-1166585903">
<usages-collector id="statistics.lifecycle.project">
<counts>
<entry key="project.closed" value="2" />
<entry key="project.closed" value="4" />
<entry key="project.open.time.10" value="1" />
<entry key="project.open.time.11" value="1" />
<entry key="project.open.time.14" value="1" />
<entry key="project.opened" value="3" />
<entry key="project.open.time.21" value="1" />
<entry key="project.open.time.25" value="1" />
<entry key="project.opened" value="5" />
</counts>
</usages-collector>
<usages-collector id="statistics.file.extensions.edit">
<counts>
<entry key="dart" value="296" />
<entry key="html" value="229" />
<entry key="dart" value="1078" />
<entry key="html" value="256" />
<entry key="md" value="7" />
<entry key="yaml" value="2" />
</counts>
</usages-collector>
<usages-collector id="statistics.file.types.edit">
<counts>
<entry key="Dart" value="296" />
<entry key="HTML" value="229" />
<entry key="Dart" value="1078" />
<entry key="HTML" value="256" />
<entry key="Markdown" value="7" />
<entry key="YAML" value="2" />
</counts>
</usages-collector>
<usages-collector id="statistics.file.extensions.open">
<counts>
<entry key="dart" value="6" />
<entry key="dart" value="8" />
<entry key="gradle" value="1" />
<entry key="html" value="5" />
</counts>
</usages-collector>
<usages-collector id="statistics.file.types.open">
<counts>
<entry key="Dart" value="6" />
<entry key="Dart" value="8" />
<entry key="Groovy" value="1" />
<entry key="HTML" value="5" />
</counts>
......@@ -109,7 +105,7 @@
<file pinned="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/example/lib/main.dart">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="224">
<state relative-caret-position="705">
<caret line="47" column="36" selection-start-line="47" selection-start-column="14" selection-end-line="47" selection-end-column="36" />
<folding>
<element signature="e#0#20#0" expanded="true" />
......@@ -119,10 +115,25 @@
</entry>
</file>
<file pinned="false" current-in-tab="true">
<entry file="file://$PROJECT_DIR$/lib/flutter_inappbrowser.dart">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="158">
<caret line="35" column="40" selection-start-line="35" selection-start-column="24" selection-end-line="35" selection-end-column="40" />
<folding>
<element signature="e#814#831#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
</file>
<file pinned="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/example/lib/inline_example.screen.dart">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="279">
<caret line="87" column="33" lean-forward="true" selection-start-line="87" selection-start-column="33" selection-end-line="87" selection-end-column="33" />
<state relative-caret-position="-382">
<caret line="12" column="28" selection-start-line="12" selection-start-column="28" selection-end-line="12" selection-end-column="28" />
<folding>
<element signature="e#0#39#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
......@@ -130,8 +141,8 @@
<file pinned="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/example/assets/index.html">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="184">
<caret line="27" column="10" lean-forward="true" selection-start-line="27" selection-start-column="10" selection-end-line="27" selection-end-column="10" />
<state relative-caret-position="301">
<caret line="34" column="49" selection-start-line="34" selection-start-column="49" selection-end-line="34" selection-end-column="49" />
</state>
</provider>
</entry>
......@@ -147,10 +158,6 @@
</component>
<component name="FindInProjectRecents">
<findStrings>
<find>initialData</find>
<find>openData</find>
<find>optionsType</find>
<find>InAppWebView</find>
<find>fromInAppBrowser</find>
<find>InAppWebViewController</find>
<find>InAppBrowser</find>
......@@ -175,8 +182,12 @@
<find>onExit</find>
<find>_handleMethod</find>
<find>javaScriptHandlersMap</find>
<find>JavaScriptHandlerCallback</find>
<find>onConsoleM</find>
<find>return this</find>
<find>return await</find>
<find>onCallJsHandler</find>
<find>JavaScriptHandlerCallback</find>
<find>ListenerCallback</find>
</findStrings>
<replaceStrings>
<replace>activity.getPreferences(0)</replace>
......@@ -230,11 +241,11 @@
<option value="$PROJECT_DIR$/README.md" />
<option value="$PROJECT_DIR$/CHANGELOG.md" />
<option value="$PROJECT_DIR$/example/lib/main.dart" />
<option value="$PROJECT_DIR$/lib/flutter_inappbrowser.dart" />
<option value="$PROJECT_DIR$/example/lib/webview_example.screen.dart" />
<option value="$PROJECT_DIR$/pubspec.yaml" />
<option value="$PROJECT_DIR$/example/assets/index.html" />
<option value="$PROJECT_DIR$/example/lib/inline_example.screen.dart" />
<option value="$PROJECT_DIR$/lib/flutter_inappbrowser.dart" />
</list>
</option>
</component>
......@@ -249,6 +260,7 @@
<foldersAlwaysOnTop value="true" />
</navigator>
<panes>
<pane id="PackagesPane" />
<pane id="AndroidView">
<subPane>
<expand>
......@@ -295,7 +307,6 @@
</subPane>
<option name="show-excluded-files" value="false" />
</pane>
<pane id="PackagesPane" />
<pane id="Scope">
<subPane subId="Project Files">
<expand>
......@@ -446,8 +457,8 @@
<frame x="0" y="23" width="1920" height="1057" extended-state="0" />
<editor active="true" />
<layout>
<window_info content_ui="combo" id="Project" order="0" sideWeight="0.64341086" visible="true" weight="0.18210863" />
<window_info id="Structure" order="1" sideWeight="0.35658914" side_tool="true" visible="true" weight="0.18210863" />
<window_info content_ui="combo" id="Project" order="0" sideWeight="0.640884" visible="true" weight="0.18210863" />
<window_info id="Structure" order="1" sideWeight="0.35911602" side_tool="true" visible="true" weight="0.18210863" />
<window_info id="Designer" order="2" />
<window_info id="Build Variants" order="3" side_tool="true" />
<window_info id="Captures" order="4" side_tool="true" weight="0.32936507" />
......@@ -456,7 +467,7 @@
<window_info id="Image Layers" order="7" />
<window_info anchor="bottom" id="Message" order="0" />
<window_info anchor="bottom" id="Find" order="1" weight="0.32745314" />
<window_info anchor="bottom" id="Run" order="2" sideWeight="0.49478307" weight="0.42356688" />
<window_info active="true" anchor="bottom" id="Run" order="2" sideWeight="0.49478307" visible="true" weight="0.42356688" />
<window_info anchor="bottom" id="Debug" order="3" weight="0.34288865" />
<window_info anchor="bottom" id="Cvs" order="4" weight="0.25" />
<window_info anchor="bottom" id="Inspection" order="5" weight="0.4" />
......@@ -464,7 +475,7 @@
<window_info anchor="bottom" id="Android Profiler" order="7" show_stripe_button="false" />
<window_info anchor="bottom" id="Event Log" order="8" sideWeight="0.5052169" side_tool="true" weight="0.34068358" />
<window_info anchor="bottom" id="Version Control" order="9" />
<window_info active="true" anchor="bottom" id="Terminal" order="10" sideWeight="0.49533224" visible="true" weight="0.4522293" />
<window_info anchor="bottom" id="Terminal" order="10" sideWeight="0.49533224" weight="0.4522293" />
<window_info anchor="bottom" id="Logcat" order="11" />
<window_info anchor="bottom" id="Messages" order="12" weight="0.2356688" />
<window_info anchor="bottom" id="Dependency Viewer" order="13" weight="0.32800853" />
......@@ -489,13 +500,6 @@
<option name="myLimit" value="2678400000" />
</component>
<component name="editorHistoryManager">
<entry file="file://$USER_HOME$/flutter/bin/cache/pkg/sky_engine/lib/core/string.dart">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="173">
<caret line="99" column="15" selection-start-line="99" selection-start-column="15" selection-end-line="99" selection-end-column="15" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/example/assets/images/dart.svg">
<provider selected="true" editor-type-id="images" />
</entry>
......@@ -615,9 +619,7 @@
<entry file="file://$PROJECT_DIR$/android/.idea/misc.xml">
<provider selected="true" editor-type-id="text-editor" />
</entry>
<entry file="file://$PROJECT_DIR$/example/build/app/intermediates/incremental/mergeDebugResources/merged.dir/values-v28/values-v28.xml">
<provider selected="true" editor-type-id="text-editor" />
</entry>
<entry file="file://$PROJECT_DIR$/example/build/app/intermediates/incremental/mergeDebugResources/merged.dir/values-v28/values-v28.xml" />
<entry file="file://$PROJECT_DIR$/example/android/app/build.gradle">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="603">
......@@ -723,13 +725,6 @@
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/lib/flutter_inappbrowser.dart">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="158">
<caret line="610" column="50" selection-start-line="610" selection-start-column="40" selection-end-line="610" selection-end-column="50" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/example/lib/webview_example.screen.dart">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="240">
......@@ -744,9 +739,16 @@
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/pubspec.yaml">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="30">
<caret line="2" column="14" selection-start-line="2" selection-start-column="14" selection-end-line="2" selection-end-column="14" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/example/lib/main.dart">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="224">
<state relative-caret-position="705">
<caret line="47" column="36" selection-start-line="47" selection-start-column="14" selection-end-line="47" selection-end-column="36" />
<folding>
<element signature="e#0#20#0" expanded="true" />
......@@ -754,24 +756,37 @@
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/pubspec.yaml">
<entry file="file://$PROJECT_DIR$/example/assets/index.html">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="30">
<caret line="2" column="14" selection-start-line="2" selection-start-column="14" selection-end-line="2" selection-end-column="14" />
<state relative-caret-position="301">
<caret line="34" column="49" selection-start-line="34" selection-start-column="49" selection-end-line="34" selection-end-column="49" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/example/assets/index.html">
<entry file="file://$USER_HOME$/flutter/bin/cache/pkg/sky_engine/lib/convert/json.dart">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="184">
<caret line="27" column="10" lean-forward="true" selection-start-line="27" selection-start-column="10" selection-end-line="27" selection-end-column="10" />
<state relative-caret-position="172">
<caret line="74" column="7" selection-start-line="74" selection-start-column="7" selection-end-line="74" selection-end-column="7" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/example/lib/inline_example.screen.dart">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="279">
<caret line="87" column="33" lean-forward="true" selection-start-line="87" selection-start-column="33" selection-end-line="87" selection-end-column="33" />
<state relative-caret-position="-382">
<caret line="12" column="28" selection-start-line="12" selection-start-column="28" selection-end-line="12" selection-end-column="28" />
<folding>
<element signature="e#0#39#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/lib/flutter_inappbrowser.dart">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="158">
<caret line="35" column="40" selection-start-line="35" selection-start-column="24" selection-end-line="35" selection-end-column="40" />
<folding>
<element signature="e#814#831#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
......
......@@ -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)
}
})
}
......
/*The MIT License (MIT)
Copyright (c) 2015 Peter Helstrup Jensen
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
import Foundation
/// Handles Convertion from instances of objects to JSON strings. Also helps with casting strings of JSON to Arrays or Dictionaries.
open class JSONSerializer {
/**
Errors that indicates failures of JSONSerialization
- JsonIsNotDictionary: -
- JsonIsNotArray: -
- JsonIsNotValid: -
*/
public enum JSONSerializerError: Error {
case jsonIsNotDictionary
case jsonIsNotArray
case jsonIsNotValid
}
//http://stackoverflow.com/questions/30480672/how-to-convert-a-json-string-to-a-dictionary
/**
Tries to convert a JSON string to a NSDictionary. NSDictionary can be easier to work with, and supports string bracket referencing. E.g. personDictionary["name"].
- parameter jsonString: JSON string to be converted to a NSDictionary.
- throws: Throws error of type JSONSerializerError. Either JsonIsNotValid or JsonIsNotDictionary. JsonIsNotDictionary will typically be thrown if you try to parse an array of JSON objects.
- returns: A NSDictionary representation of the JSON string.
*/
open static func toDictionary(_ jsonString: String) throws -> NSDictionary {
if let dictionary = try jsonToAnyObject(jsonString) as? NSDictionary {
return dictionary
} else {
throw JSONSerializerError.jsonIsNotDictionary
}
}
/**
Tries to convert a JSON string to a NSArray. NSArrays can be iterated and each item in the array can be converted to a NSDictionary.
- parameter jsonString: The JSON string to be converted to an NSArray
- throws: Throws error of type JSONSerializerError. Either JsonIsNotValid or JsonIsNotArray. JsonIsNotArray will typically be thrown if you try to parse a single JSON object.
- returns: NSArray representation of the JSON objects.
*/
open static func toArray(_ jsonString: String) throws -> NSArray {
if let array = try jsonToAnyObject(jsonString) as? NSArray {
return array
} else {
throw JSONSerializerError.jsonIsNotArray
}
}
/**
Tries to convert a JSON string to AnyObject. AnyObject can then be casted to either NSDictionary or NSArray.
- parameter jsonString: JSON string to be converted to AnyObject
- throws: Throws error of type JSONSerializerError.
- returns: Returns the JSON string as AnyObject
*/
fileprivate static func jsonToAnyObject(_ jsonString: String) throws -> Any? {
var any: Any?
if let data = jsonString.data(using: String.Encoding.utf8) {
do {
any = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)
}
catch let error as NSError {
let sError = String(describing: error)
NSLog(sError)
throw JSONSerializerError.jsonIsNotValid
}
}
return any
}
/**
Generates the JSON representation given any custom object of any custom class. Inherited properties will also be represented.
- parameter object: The instantiation of any custom class to be represented as JSON.
- returns: A string JSON representation of the object.
*/
open static func toJson(_ object: Any, prettify: Bool = false) -> String {
var json = ""
if (!(object is Array<Any>)) {
json += "{"
}
let mirror = Mirror(reflecting: object)
var children = [(label: String?, value: Any)]()
if let mirrorChildrenCollection = AnyRandomAccessCollection(mirror.children) {
children += mirrorChildrenCollection
}
else {
let mirrorIndexCollection = AnyCollection(mirror.children)
children += mirrorIndexCollection
}
var currentMirror = mirror
while let superclassChildren = currentMirror.superclassMirror?.children {
let randomCollection = AnyRandomAccessCollection(superclassChildren)!
children += randomCollection
currentMirror = currentMirror.superclassMirror!
}
var filteredChildren = [(label: String?, value: Any)]()
for (optionalPropertyName, value) in children {
if let optionalPropertyName = optionalPropertyName {
if !optionalPropertyName.contains("notMapped_") {
filteredChildren.append((optionalPropertyName, value))
}
}
else {
filteredChildren.append((nil, value))
}
}
var skip = false
let size = filteredChildren.count
var index = 0
var first = true
for (optionalPropertyName, value) in filteredChildren {
skip = false
let propertyName = optionalPropertyName
let property = Mirror(reflecting: value)
var handledValue = String()
if propertyName != nil && propertyName == "some" && property.displayStyle == Mirror.DisplayStyle.struct {
handledValue = toJson(value)
skip = true
}
else if (value is Int ||
value is Int32 ||
value is Int64 ||
value is Double ||
value is Float ||
value is Bool) && property.displayStyle != Mirror.DisplayStyle.optional {
handledValue = String(describing: value)
}
else if let array = value as? [Int?] {
handledValue += "["
for (index, value) in array.enumerated() {
handledValue += value != nil ? String(value!) : "null"
handledValue += (index < array.count-1 ? ", " : "")
}
handledValue += "]"
}
else if let array = value as? [Double?] {
handledValue += "["
for (index, value) in array.enumerated() {
handledValue += value != nil ? String(value!) : "null"
handledValue += (index < array.count-1 ? ", " : "")
}
handledValue += "]"
}
else if let array = value as? [Float?] {
handledValue += "["
for (index, value) in array.enumerated() {
handledValue += value != nil ? String(value!) : "null"
handledValue += (index < array.count-1 ? ", " : "")
}
handledValue += "]"
}
else if let array = value as? [Bool?] {
handledValue += "["
for (index, value) in array.enumerated() {
handledValue += value != nil ? String(value!) : "null"
handledValue += (index < array.count-1 ? ", " : "")
}
handledValue += "]"
}
else if let array = value as? [String?] {
handledValue += "["
for (index, value) in array.enumerated() {
handledValue += value != nil ? "\"\(value!)\"" : "null"
handledValue += (index < array.count-1 ? ", " : "")
}
handledValue += "]"
}
else if let array = value as? [String] {
handledValue += "["
for (index, value) in array.enumerated() {
handledValue += "\"\(value)\""
handledValue += (index < array.count-1 ? ", " : "")
}
handledValue += "]"
}
else if let array = value as? NSArray {
handledValue += "["
for (index, value) in array.enumerated() {
if !(value is Int) &&
!(value is Int32) &&
!(value is Int64) &&
!(value is Double) && !(value is Float) && !(value is Bool) && !(value is String) {
handledValue += toJson(value)
}
else {
handledValue += "\(value)"
}
handledValue += (index < array.count-1 ? ", " : "")
}
handledValue += "]"
}
else if property.displayStyle == Mirror.DisplayStyle.class ||
property.displayStyle == Mirror.DisplayStyle.struct ||
String(describing: value).contains("#") {
handledValue = toJson(value)
}
else if property.displayStyle == Mirror.DisplayStyle.optional {
let str = String(describing: value)
if str != "nil" {
// Some optional values cannot be unpacked if type is "Any"
// We remove the "Optional(" and last ")" from the value by string manipulation
var d = String(str).dropFirst(9)
d = d.dropLast(1)
handledValue = String(d)
} else {
handledValue = "null"
}
}
else {
handledValue = String(describing: value) != "nil" ? "\"\(value)\"" : "null"
}
if !skip {
// if optional propertyName is populated we'll use it
if let propertyName = propertyName {
json += "\"\(propertyName)\": \(handledValue)" + (index < size-1 ? ", " : "")
}
// if not then we have a member an array
else {
// if it's the first member we need to prepend ]
if first {
json += "["
first = false
}
// if it's not the last we need a comma. if it is the last we need to close ]
json += "\(handledValue)" + (index < size-1 ? ", " : "]")
}
} else {
json = "\(handledValue)" + (index < size-1 ? ", " : "")
}
index += 1
}
if !skip {
if (!(object is Array<Any>)) {
json += "}"
}
}
if prettify {
let jsonData = json.data(using: String.Encoding.utf8)!
let jsonObject = try! JSONSerialization.jsonObject(with: jsonData, options: [])
let prettyJsonData = try! JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted)
json = NSString(data: prettyJsonData, encoding: String.Encoding.utf8.rawValue)! as String
}
return json
}
}
......@@ -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