Skip to content

Commit

Permalink
Updated window.flutter_inappwebview.callHandler implementation: if th…
Browse files Browse the repository at this point in the history
…ere is an error/exception on Flutter/Dart side, the callHandler will reject the JavaScript promise with the error/exception message, so you can catch it also on JavaScript side, Fixed Android Web Storage Manager deleteAllData and deleteOrigin methods implementation, fix pichillilorenzo#1462, fix pichillilorenzo#1475
  • Loading branch information
pichillilorenzo committed Dec 15, 2022
1 parent 0f1c7e3 commit a42b0e4
Show file tree
Hide file tree
Showing 22 changed files with 120 additions and 39 deletions.
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
## 6.0.0-beta.22

- Updated `window.flutter_inappwebview.callHandler` implementation: if there is an error/exception on Flutter/Dart side, the `callHandler` will reject the JavaScript promise with the error/exception message, so you can catch it also on JavaScript side
- Fixed Android Web Storage Manager `deleteAllData` and `deleteOrigin` methods implementation
- Fixed "Xiaomi store - Conflict of Privacy Permissions, android.permission.MY_READ_INSTALLED_PACKAGES" [#1462](https://github.com/pichillilorenzo/flutter_inappwebview/issues/1462)
- Fixed "Flutter 3.0.5 compilation issue" [#1475](https://github.com/pichillilorenzo/flutter_inappwebview/issues/1475)

## 6.0.0-beta.21

- Fixed "Android plugin version 6 - UserScripts not executing on new tabs." [#1455](https://github.com/pichillilorenzo/flutter_inappwebview/issues/1455)
Expand Down Expand Up @@ -174,6 +181,10 @@
- Removed `URLProtectionSpace.iosIsProxy` property
- `historyUrl` and `baseUrl` of `InAppWebViewInitialData` can be `null`

## 5.7.2+3

- Fixed "Xiaomi store - Conflict of Privacy Permissions, android.permission.MY_READ_INSTALLED_PACKAGES" [#1462](https://github.com/pichillilorenzo/flutter_inappwebview/issues/1462)

## 5.7.2+2

- Fixed "Unexpected addWebMessageListener behaviour" [#1422](https://github.com/pichillilorenzo/flutter_inappwebview/issues/1422)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,21 @@ public class MyCookieManager extends ChannelDelegateImpl {
@Nullable
public InAppWebViewFlutterPlugin plugin;

public MyCookieManager(final InAppWebViewFlutterPlugin plugin) {
public MyCookieManager(@NonNull final InAppWebViewFlutterPlugin plugin) {
super(new MethodChannel(plugin.messenger, METHOD_CHANNEL_NAME));
this.plugin = plugin;
cookieManager = getCookieManager();
}

public static void init() {
if (cookieManager == null) {
cookieManager = getCookieManager();
}
}

@Override
public void onMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
init();

switch (call.method) {
case "setCookie":
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,20 +25,27 @@ public class MyWebStorage extends ChannelDelegateImpl {
@Nullable
public InAppWebViewFlutterPlugin plugin;

public MyWebStorage(final InAppWebViewFlutterPlugin plugin) {
public MyWebStorage(@NonNull final InAppWebViewFlutterPlugin plugin) {
super(new MethodChannel(plugin.messenger, METHOD_CHANNEL_NAME));
this.plugin = plugin;
webStorageManager = WebStorage.getInstance();
}

public static void init() {
if (webStorageManager == null) {
webStorageManager = WebStorage.getInstance();
}
}

@Override
public void onMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
init();

switch (call.method) {
case "getOrigins":
getOrigins(result);
break;
case "deleteAllData":
if (webStorageManager == null) {
if (webStorageManager != null) {
webStorageManager.deleteAllData();
result.success(true);
} else {
Expand All @@ -47,7 +54,7 @@ public void onMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result
break;
case "deleteOrigin":
{
if (webStorageManager == null) {
if (webStorageManager != null) {
String origin = (String) call.argument("origin");
webStorageManager.deleteOrigin(origin);
result.success(true);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ public class WebViewFeatureManager extends ChannelDelegateImpl {
@Nullable
public InAppWebViewFlutterPlugin plugin;

public WebViewFeatureManager(final InAppWebViewFlutterPlugin plugin) {
public WebViewFeatureManager(@NonNull final InAppWebViewFlutterPlugin plugin) {
super(new MethodChannel(plugin.messenger, METHOD_CHANNEL_NAME));
this.plugin = plugin;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,23 @@ public class CredentialDatabaseHandler extends ChannelDelegateImpl {
@Nullable
public InAppWebViewFlutterPlugin plugin;

public CredentialDatabaseHandler(final InAppWebViewFlutterPlugin plugin) {
public CredentialDatabaseHandler(@NonNull final InAppWebViewFlutterPlugin plugin) {
super(new MethodChannel(plugin.messenger, METHOD_CHANNEL_NAME));
this.plugin = plugin;
credentialDatabase = CredentialDatabase.getInstance(plugin.applicationContext);
}

public static void init(@NonNull InAppWebViewFlutterPlugin plugin) {
if (credentialDatabase == null) {
credentialDatabase = CredentialDatabase.getInstance(plugin.applicationContext);
}
}

@Override
public void onMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
if (plugin != null) {
init(plugin);
}

switch (call.method) {
case "getAllAuthCredentials":
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,7 @@ public class JavaScriptBridgeJS {
" var _callHandlerID = setTimeout(function(){});" +
" window." + JAVASCRIPT_BRIDGE_NAME + "._callHandler(arguments[0], _callHandlerID, JSON.stringify(Array.prototype.slice.call(arguments, 1)));" +
" return new Promise(function(resolve, reject) {" +
" window." + JAVASCRIPT_BRIDGE_NAME + "[_callHandlerID] = resolve;" +
" window." + JAVASCRIPT_BRIDGE_NAME + "[_callHandlerID] = {resolve: resolve, reject: reject};" +
" });" +
" };" +
" }"+
Expand All @@ -230,7 +230,7 @@ public class JavaScriptBridgeJS {
" var _callHandlerID = setTimeout(function(){});" +
" window.top." + JAVASCRIPT_BRIDGE_NAME + "._callHandler(arguments[0], _callHandlerID, JSON.stringify(Array.prototype.slice.call(arguments, 1)));" +
" return new Promise(function(resolve, reject) {" +
" window.top." + JAVASCRIPT_BRIDGE_NAME + "[_callHandlerID] = resolve;" +
" window.top." + JAVASCRIPT_BRIDGE_NAME + "[_callHandlerID] = {resolve: resolve, reject: reject};" +
" });" +
" };" +
"}" +
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,18 +25,22 @@ public class ProxyManager extends ChannelDelegateImpl {
@Nullable
public InAppWebViewFlutterPlugin plugin;

public ProxyManager(final InAppWebViewFlutterPlugin plugin) {
public ProxyManager(@NonNull final InAppWebViewFlutterPlugin plugin) {
super(new MethodChannel(plugin.messenger, METHOD_CHANNEL_NAME));
this.plugin = plugin;
if (WebViewFeature.isFeatureSupported(WebViewFeature.PROXY_OVERRIDE)) {
}

public static void init() {
if (proxyController == null &&
WebViewFeature.isFeatureSupported(WebViewFeature.PROXY_OVERRIDE)) {
proxyController = ProxyController.getInstance();
} else {
proxyController = null;
}
}

@Override
public void onMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
init();

switch (call.method) {
case "setProxyOverride":
if (proxyController != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ public ServiceWorkerChannelDelegate(@NonNull ServiceWorkerManager serviceWorkerM
@SuppressLint("RestrictedApi")
@Override
public void onMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
ServiceWorkerManager.init();
ServiceWorkerControllerCompat serviceWorkerController = ServiceWorkerManager.serviceWorkerController;
ServiceWorkerWebSettingsCompat serviceWorkerWebSettings = (serviceWorkerController != null) ?
serviceWorkerController.getServiceWorkerWebSettings() : null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,16 @@ public class ServiceWorkerManager implements Disposable {
@Nullable
public InAppWebViewFlutterPlugin plugin;

public ServiceWorkerManager(final InAppWebViewFlutterPlugin plugin) {
public ServiceWorkerManager(@NonNull final InAppWebViewFlutterPlugin plugin) {
this.plugin = plugin;
final MethodChannel channel = new MethodChannel(plugin.messenger, METHOD_CHANNEL_NAME);
this.channelDelegate = new ServiceWorkerChannelDelegate(this, channel);
if (WebViewFeature.isFeatureSupported(WebViewFeature.SERVICE_WORKER_BASIC_USAGE)) {
}

public static void init() {
if (serviceWorkerController == null &&
WebViewFeature.isFeatureSupported(WebViewFeature.SERVICE_WORKER_BASIC_USAGE)) {
serviceWorkerController = ServiceWorkerControllerCompat.getInstance();
} else {
serviceWorkerController = null;
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ public TracingControllerChannelDelegate(@NonNull TracingControllerManager tracin

@Override
public void onMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
TracingControllerManager.init();
TracingController tracingController = TracingControllerManager.tracingController;

switch (call.method) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.pichillilorenzo.flutter_inappwebview.tracing;

import androidx.annotation.Nullable;
import androidx.webkit.ProxyController;
import androidx.webkit.TracingConfig;
import androidx.webkit.TracingController;
import androidx.webkit.WebViewFeature;
Expand All @@ -25,10 +26,12 @@ public TracingControllerManager(final InAppWebViewFlutterPlugin plugin) {
this.plugin = plugin;
final MethodChannel channel = new MethodChannel(plugin.messenger, METHOD_CHANNEL_NAME);
this.channelDelegate = new TracingControllerChannelDelegate(this, channel);
if (WebViewFeature.isFeatureSupported(WebViewFeature.TRACING_CONTROLLER_BASIC_USAGE)) {
}

public static void init() {
if (tracingController == null &&
WebViewFeature.isFeatureSupported(WebViewFeature.TRACING_CONTROLLER_BASIC_USAGE)) {
tracingController = TracingController.getInstance();
} else {
tracingController = null;
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ public void defaultBehaviour(@Nullable Object json) {
return;
}
String sourceCode = "if (window." + JavaScriptBridgeJS.JAVASCRIPT_BRIDGE_NAME + "[" + _callHandlerID + "] != null) { " +
"window." + JavaScriptBridgeJS.JAVASCRIPT_BRIDGE_NAME + "[" + _callHandlerID + "](" + json + "); " +
"window." + JavaScriptBridgeJS.JAVASCRIPT_BRIDGE_NAME + "[" + _callHandlerID + "].resolve(" + json + "); " +
"delete window." + JavaScriptBridgeJS.JAVASCRIPT_BRIDGE_NAME + "[" + _callHandlerID + "]; " +
"}";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Expand All @@ -143,7 +143,24 @@ public void defaultBehaviour(@Nullable Object json) {

@Override
public void error(String errorCode, @Nullable String errorMessage, @Nullable Object errorDetails) {
Log.e(LOG_TAG, errorCode + ", " + ((errorMessage != null) ? errorMessage : ""));
String message = errorCode + ((errorMessage != null) ? ", " + errorMessage : "");
Log.e(LOG_TAG, message);

if (inAppWebView == null) {
// The webview has already been disposed, ignore.
return;
}

String sourceCode = "if (window." + JavaScriptBridgeJS.JAVASCRIPT_BRIDGE_NAME + "[" + _callHandlerID + "] != null) { " +
"window." + JavaScriptBridgeJS.JAVASCRIPT_BRIDGE_NAME + "[" + _callHandlerID + "].reject(new Error(" + JSONObject.quote(message) + ")); " +
"delete window." + JavaScriptBridgeJS.JAVASCRIPT_BRIDGE_NAME + "[" + _callHandlerID + "]; " +
"}";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
inAppWebView.evaluateJavascript(sourceCode, (ValueCallback<String>) null);
}
else {
inAppWebView.loadUrl("javascript:" + sourceCode);
}
}
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ void openAndClose() {
activityButton: ActivityButton(
templateImage: UIImage(systemName: "sun.max"),
extensionIdentifier:
"com.pichillilorenzo.flutter-inappwebview6-example.test")));
"com.pichillilorenzo.flutter-inappwebview-example6.test")));
await chromeSafariBrowser.opened.future;
expect(chromeSafariBrowser.isOpened(), true);
expect(() async {
Expand Down
8 changes: 4 additions & 4 deletions example/ios/Runner.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -451,7 +451,7 @@
MARKETING_VERSION = 1.0;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
PRODUCT_BUNDLE_IDENTIFIER = "com.pichillilorenzo.flutter-inappwebview6-example.test";
PRODUCT_BUNDLE_IDENTIFIER = "com.pichillilorenzo.flutter-inappwebview-example6.test";
PRODUCT_NAME = "$(TARGET_NAME)";
SKIP_INSTALL = YES;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
Expand Down Expand Up @@ -484,7 +484,7 @@
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @executable_path/../../Frameworks";
MARKETING_VERSION = 1.0;
MTL_FAST_MATH = YES;
PRODUCT_BUNDLE_IDENTIFIER = "com.pichillilorenzo.flutter-inappwebview6-example.test";
PRODUCT_BUNDLE_IDENTIFIER = "com.pichillilorenzo.flutter-inappwebview-example6.test";
PRODUCT_NAME = "$(TARGET_NAME)";
SKIP_INSTALL = YES;
SWIFT_EMIT_LOC_STRINGS = YES;
Expand Down Expand Up @@ -627,7 +627,7 @@
"$(inherited)",
"$(PROJECT_DIR)/Flutter",
);
PRODUCT_BUNDLE_IDENTIFIER = "com.pichillilorenzo.flutter-inappwebview6-example";
PRODUCT_BUNDLE_IDENTIFIER = "com.pichillilorenzo.flutter-inappwebview-example6";
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "";
SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h";
Expand Down Expand Up @@ -659,7 +659,7 @@
"$(inherited)",
"$(PROJECT_DIR)/Flutter",
);
PRODUCT_BUNDLE_IDENTIFIER = "com.pichillilorenzo.flutter-inappwebview6-example";
PRODUCT_BUNDLE_IDENTIFIER = "com.pichillilorenzo.flutter-inappwebview-example6";
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "";
SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h";
Expand Down
12 changes: 10 additions & 2 deletions ios/Classes/InAppWebView/InAppWebView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2738,13 +2738,21 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate,

self.evaluateJavaScript("""
if(window.\(JAVASCRIPT_BRIDGE_NAME)[\(_callHandlerID)] != null) {
window.\(JAVASCRIPT_BRIDGE_NAME)[\(_callHandlerID)](\(json));
window.\(JAVASCRIPT_BRIDGE_NAME)[\(_callHandlerID)].resolve(\(json));
delete window.\(JAVASCRIPT_BRIDGE_NAME)[\(_callHandlerID)];
}
""", completionHandler: nil)
}
callback.error = { (code: String, message: String?, details: Any?) in
print(code + ", " + (message ?? ""))
let errorMessage = code + (message != nil ? ", " + (message ?? "") : "")
print(errorMessage)

self.evaluateJavaScript("""
if(window.\(JAVASCRIPT_BRIDGE_NAME)[\(_callHandlerID)] != null) {
window.\(JAVASCRIPT_BRIDGE_NAME)[\(_callHandlerID)].reject(new Error('\(errorMessage.replacingOccurrences(of: "\'", with: "\\'"))'));
delete window.\(JAVASCRIPT_BRIDGE_NAME)[\(_callHandlerID)];
}
""", completionHandler: nil)
}

if let channelDelegate = webView.channelDelegate {
Expand Down
2 changes: 1 addition & 1 deletion ios/Classes/PluginScriptsJS/JavaScriptBridgeJS.swift
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ window.\(JAVASCRIPT_BRIDGE_NAME).callHandler = function() {
var _callHandlerID = setTimeout(function(){});
window.webkit.messageHandlers['callHandler'].postMessage( {'handlerName': arguments[0], '_callHandlerID': _callHandlerID, 'args': JSON.stringify(Array.prototype.slice.call(arguments, 1)), '_windowId': _windowId} );
return new Promise(function(resolve, reject) {
window.\(JAVASCRIPT_BRIDGE_NAME)[_callHandlerID] = resolve;
window.\(JAVASCRIPT_BRIDGE_NAME)[_callHandlerID] = {resolve: resolve, reject: reject};
});
};
\(WEB_MESSAGE_LISTENER_JS_SOURCE)
Expand Down
1 change: 1 addition & 0 deletions lib/src/in_app_browser/in_app_browser.dart
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import 'dart:async';
import 'dart:collection';
import 'dart:typed_data';
import 'dart:ui';

import 'package:flutter/services.dart';

Expand Down
7 changes: 4 additions & 3 deletions lib/src/in_app_webview/in_app_webview_controller.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1378,9 +1378,10 @@ class InAppWebViewController {
// convert result to json
try {
return jsonEncode(await javaScriptHandlersMap[handlerName]!(args));
} catch (error) {
developer.log(error.toString(), name: this.runtimeType.toString());
return null;
} catch (error, stacktrace) {
developer.log(error.toString() + '\n' + stacktrace.toString(),
name: 'JavaScript Handler "$handlerName"');
throw Exception(error.toString().replaceFirst('Exception: ', ''));
}
}
break;
Expand Down
1 change: 1 addition & 0 deletions lib/src/in_app_webview/in_app_webview_settings.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_inappwebview/src/types/user_preferred_content_mode.dart';
import 'package:flutter_inappwebview_internal_annotations/flutter_inappwebview_internal_annotations.dart';
import 'dart:typed_data';

import '../android/webview_asset_loader.dart';
import '../types/action_mode_menu_item.dart';
Expand Down
12 changes: 10 additions & 2 deletions macos/Classes/InAppWebView/InAppWebView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2102,13 +2102,21 @@ public class InAppWebView: WKWebView, WKUIDelegate,

self.evaluateJavaScript("""
if(window.\(JAVASCRIPT_BRIDGE_NAME)[\(_callHandlerID)] != null) {
window.\(JAVASCRIPT_BRIDGE_NAME)[\(_callHandlerID)](\(json));
window.\(JAVASCRIPT_BRIDGE_NAME)[\(_callHandlerID)].resolve(\(json));
delete window.\(JAVASCRIPT_BRIDGE_NAME)[\(_callHandlerID)];
}
""", completionHandler: nil)
}
callback.error = { (code: String, message: String?, details: Any?) in
print(code + ", " + (message ?? ""))
let errorMessage = code + (message != nil ? ", " + (message ?? "") : "")
print(errorMessage)

self.evaluateJavaScript("""
if(window.\(JAVASCRIPT_BRIDGE_NAME)[\(_callHandlerID)] != null) {
window.\(JAVASCRIPT_BRIDGE_NAME)[\(_callHandlerID)].reject(new Error('\(errorMessage.replacingOccurrences(of: "\'", with: "\\'"))'));
delete window.\(JAVASCRIPT_BRIDGE_NAME)[\(_callHandlerID)];
}
""", completionHandler: nil)
}

if let channelDelegate = webView.channelDelegate {
Expand Down
Loading

0 comments on commit a42b0e4

Please sign in to comment.