This repository was archived by the owner on Feb 22, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9.8k
[webview_flutter] Added Android implementation of PlatformWebViewController #6674
Merged
mvanbeusekom
merged 5 commits into
flutter:v4_webview
from
Baseflow:v4_webview_android_webview_controller
Nov 19, 2022
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
4e7f4c2
Added Android implementation of PlatformWebViewController
mvanbeusekom 4594cc4
Apply feedback from PR
mvanbeusekom 9917bbf
Apply feedback from PR
mvanbeusekom 62d5149
Remove AndroidWebViewWidget which was added to early
mvanbeusekom 8b3c42c
Merge remote-tracking branch 'upstream/v4_webview' into v4_webview_an…
mvanbeusekom File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
322 changes: 322 additions & 0 deletions
322
...es/webview_flutter/webview_flutter_android/lib/src/v4/src/android_webview_controller.dart
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,322 @@ | ||
// Copyright 2013 The Flutter Authors. All rights reserved. | ||
// Use of this source code is governed by a BSD-style license that can be | ||
// found in the LICENSE file. | ||
|
||
import 'dart:math'; | ||
|
||
// TODO(a14n): remove this import once Flutter 3.1 or later reaches stable (including flutter/flutter#104231) | ||
// ignore: unnecessary_import | ||
import 'dart:typed_data'; | ||
|
||
import 'package:flutter/foundation.dart'; | ||
import 'package:flutter/material.dart'; | ||
import 'package:flutter/services.dart'; | ||
import 'package:webview_flutter_platform_interface/v4/webview_flutter_platform_interface.dart'; | ||
|
||
import '../../android_webview.dart' as android_webview; | ||
import '../../android_webview.dart'; | ||
import '../../instance_manager.dart'; | ||
import '../../weak_reference_utils.dart'; | ||
import 'android_navigation_delegate.dart'; | ||
import 'android_proxy.dart'; | ||
|
||
/// Object specifying creation parameters for creating a [AndroidWebViewController]. | ||
/// | ||
/// When adding additional fields make sure they can be null or have a default | ||
/// value to avoid breaking changes. See [PlatformWebViewControllerCreationParams] for | ||
/// more information. | ||
@immutable | ||
class AndroidWebViewControllerCreationParams | ||
extends PlatformWebViewControllerCreationParams { | ||
/// Creates a new [AndroidWebViewControllerCreationParams] instance. | ||
AndroidWebViewControllerCreationParams({ | ||
@visibleForTesting this.androidWebViewProxy = const AndroidWebViewProxy(), | ||
@visibleForTesting android_webview.WebStorage? androidWebStorage, | ||
}) : androidWebStorage = | ||
androidWebStorage ?? android_webview.WebStorage.instance, | ||
super(); | ||
|
||
/// Creates a [AndroidWebViewControllerCreationParams] instance based on [PlatformWebViewControllerCreationParams]. | ||
factory AndroidWebViewControllerCreationParams.fromPlatformWebViewControllerCreationParams( | ||
// Recommended placeholder to prevent being broken by platform interface. | ||
// ignore: avoid_unused_constructor_parameters | ||
PlatformWebViewControllerCreationParams params, { | ||
@visibleForTesting | ||
AndroidWebViewProxy androidWebViewProxy = const AndroidWebViewProxy(), | ||
@visibleForTesting android_webview.WebStorage? androidWebStorage, | ||
}) { | ||
return AndroidWebViewControllerCreationParams( | ||
androidWebViewProxy: androidWebViewProxy, | ||
androidWebStorage: | ||
androidWebStorage ?? android_webview.WebStorage.instance, | ||
); | ||
} | ||
|
||
/// Handles constructing objects and calling static methods for the Android WebView | ||
/// native library. | ||
@visibleForTesting | ||
final AndroidWebViewProxy androidWebViewProxy; | ||
|
||
/// Manages the JavaScript storage APIs provided by the [android_webview.WebView]. | ||
@visibleForTesting | ||
final android_webview.WebStorage androidWebStorage; | ||
} | ||
|
||
/// Implementation of the [PlatformWebViewController] with the Android WebView API. | ||
class AndroidWebViewController extends PlatformWebViewController { | ||
/// Creates a new [AndroidWebViewCookieManager]. | ||
AndroidWebViewController(PlatformWebViewControllerCreationParams params) | ||
: super.implementation(params is AndroidWebViewControllerCreationParams | ||
? params | ||
: AndroidWebViewControllerCreationParams | ||
.fromPlatformWebViewControllerCreationParams(params)); | ||
|
||
AndroidWebViewControllerCreationParams get _androidWebViewParams => | ||
params as AndroidWebViewControllerCreationParams; | ||
|
||
/// The native [android_webview.WebView] being controlled. | ||
late final android_webview.WebView _webView = | ||
_androidWebViewParams.androidWebViewProxy.createAndroidWebView( | ||
// Due to changes in Flutter 3.0 the `useHybridComposition` doesn't have | ||
// any effect and is purposefully not exposed publicly by the | ||
// [AndroidWebViewController]. More info here: | ||
// https://github.com/flutter/flutter/issues/108106 | ||
useHybridComposition: true, | ||
); | ||
|
||
/// The native [android_webview.FlutterAssetManager] allows managing assets. | ||
late final android_webview.FlutterAssetManager _flutterAssetManager = | ||
_androidWebViewParams.androidWebViewProxy.createFlutterAssetManager(); | ||
|
||
final Map<String, AndroidJavaScriptChannelParams> _javaScriptChannelParams = | ||
<String, AndroidJavaScriptChannelParams>{}; | ||
|
||
@override | ||
Future<void> loadFile( | ||
String absoluteFilePath, | ||
) { | ||
final String url = absoluteFilePath.startsWith('file://') | ||
? absoluteFilePath | ||
: Uri.file(absoluteFilePath).toString(); | ||
|
||
_webView.settings.setAllowFileAccess(true); | ||
return _webView.loadUrl(url, <String, String>{}); | ||
} | ||
|
||
@override | ||
Future<void> loadFlutterAsset( | ||
String key, | ||
) async { | ||
final String assetFilePath = | ||
await _flutterAssetManager.getAssetFilePathByName(key); | ||
final List<String> pathElements = assetFilePath.split('/'); | ||
final String fileName = pathElements.removeLast(); | ||
final List<String?> paths = | ||
await _flutterAssetManager.list(pathElements.join('/')); | ||
|
||
if (!paths.contains(fileName)) { | ||
throw ArgumentError( | ||
'Asset for key "$key" not found.', | ||
'key', | ||
); | ||
} | ||
|
||
return _webView.loadUrl( | ||
Uri.file('/android_asset/$assetFilePath').toString(), | ||
<String, String>{}, | ||
); | ||
} | ||
|
||
@override | ||
Future<void> loadHtmlString( | ||
String html, { | ||
String? baseUrl, | ||
}) { | ||
return _webView.loadDataWithBaseUrl( | ||
baseUrl: baseUrl, | ||
data: html, | ||
mimeType: 'text/html', | ||
); | ||
} | ||
|
||
@override | ||
Future<void> loadRequest( | ||
LoadRequestParams params, | ||
) { | ||
if (!params.uri.hasScheme) { | ||
throw ArgumentError('WebViewRequest#uri is required to have a scheme.'); | ||
} | ||
switch (params.method) { | ||
case LoadRequestMethod.get: | ||
return _webView.loadUrl(params.uri.toString(), params.headers); | ||
case LoadRequestMethod.post: | ||
return _webView.postUrl( | ||
params.uri.toString(), params.body ?? Uint8List(0)); | ||
mvanbeusekom marked this conversation as resolved.
Show resolved
Hide resolved
|
||
default: | ||
throw UnimplementedError( | ||
'This version of `AndroidWebViewController` currently has no implementation for HTTP method ${params.method.serialize()} in loadRequest.', | ||
); | ||
} | ||
} | ||
|
||
@override | ||
Future<String?> currentUrl() => _webView.getUrl(); | ||
|
||
@override | ||
Future<bool> canGoBack() => _webView.canGoBack(); | ||
|
||
@override | ||
Future<bool> canGoForward() => _webView.canGoForward(); | ||
|
||
@override | ||
Future<void> goBack() => _webView.goBack(); | ||
|
||
@override | ||
Future<void> goForward() => _webView.goForward(); | ||
|
||
@override | ||
Future<void> reload() => _webView.reload(); | ||
|
||
@override | ||
Future<void> clearCache() => _webView.clearCache(true); | ||
|
||
@override | ||
Future<void> clearLocalStorage() => | ||
_androidWebViewParams.androidWebStorage.deleteAllData(); | ||
|
||
@override | ||
Future<void> setPlatformNavigationDelegate( | ||
covariant AndroidNavigationDelegate handler) async { | ||
_webView.setWebViewClient(handler.androidWebViewClient); | ||
_webView.setWebChromeClient(handler.androidWebChromeClient); | ||
} | ||
|
||
@override | ||
Future<void> runJavaScript(String javaScript) { | ||
return _webView.evaluateJavascript(javaScript); | ||
} | ||
|
||
@override | ||
Future<String> runJavaScriptReturningResult(String javaScript) async { | ||
return await _webView.evaluateJavascript(javaScript) ?? ''; | ||
} | ||
|
||
@override | ||
Future<void> addJavaScriptChannel( | ||
JavaScriptChannelParams javaScriptChannelParams, | ||
) { | ||
final AndroidJavaScriptChannelParams androidJavaScriptParams = | ||
javaScriptChannelParams is AndroidJavaScriptChannelParams | ||
? javaScriptChannelParams | ||
: AndroidJavaScriptChannelParams.fromJavaScriptChannelParams( | ||
javaScriptChannelParams); | ||
|
||
// When JavaScript channel with the same name exists make sure to remove it | ||
// before registering the new channel. | ||
if (_javaScriptChannelParams.containsKey(androidJavaScriptParams.name)) { | ||
_webView | ||
.removeJavaScriptChannel(androidJavaScriptParams._javaScriptChannel); | ||
} | ||
|
||
_javaScriptChannelParams[androidJavaScriptParams.name] = | ||
androidJavaScriptParams; | ||
|
||
return _webView | ||
.addJavaScriptChannel(androidJavaScriptParams._javaScriptChannel); | ||
} | ||
|
||
@override | ||
Future<void> removeJavaScriptChannel(String javaScriptChannelName) async { | ||
final AndroidJavaScriptChannelParams? javaScriptChannelParams = | ||
_javaScriptChannelParams[javaScriptChannelName]; | ||
if (javaScriptChannelParams == null) { | ||
return; | ||
} | ||
|
||
_javaScriptChannelParams.remove(javaScriptChannelName); | ||
return _webView | ||
.removeJavaScriptChannel(javaScriptChannelParams._javaScriptChannel); | ||
} | ||
|
||
@override | ||
Future<String?> getTitle() => _webView.getTitle(); | ||
|
||
@override | ||
Future<void> scrollTo(int x, int y) => _webView.scrollTo(x, y); | ||
|
||
@override | ||
Future<void> scrollBy(int x, int y) => _webView.scrollBy(x, y); | ||
|
||
@override | ||
Future<Point<int>> getScrollPosition() async { | ||
final Offset position = await _webView.getScrollPosition(); | ||
return Point<int>(position.dx.round(), position.dy.round()); | ||
} | ||
|
||
@override | ||
Future<void> enableDebugging(bool enabled) => | ||
_androidWebViewParams.androidWebViewProxy | ||
.setWebContentsDebuggingEnabled(enabled); | ||
|
||
@override | ||
Future<void> enableZoom(bool enabled) => | ||
_webView.settings.setSupportZoom(enabled); | ||
|
||
@override | ||
Future<void> setBackgroundColor(Color color) => | ||
_webView.setBackgroundColor(color); | ||
|
||
@override | ||
Future<void> setJavaScriptMode(JavaScriptMode javaScriptMode) => | ||
_webView.settings | ||
.setJavaScriptEnabled(javaScriptMode == JavaScriptMode.unrestricted); | ||
|
||
@override | ||
Future<void> setUserAgent(String? userAgent) => | ||
_webView.settings.setUserAgentString(userAgent); | ||
} | ||
|
||
/// An implementation of [JavaScriptChannelParams] with the Android WebView API. | ||
/// | ||
/// See [AndroidWebViewController.addJavaScriptChannel]. | ||
@immutable | ||
class AndroidJavaScriptChannelParams extends JavaScriptChannelParams { | ||
/// Constructs a [AndroidJavaScriptChannelParams]. | ||
AndroidJavaScriptChannelParams({ | ||
required super.name, | ||
required super.onMessageReceived, | ||
@visibleForTesting | ||
AndroidWebViewProxy webViewProxy = const AndroidWebViewProxy(), | ||
}) : assert(name.isNotEmpty), | ||
_javaScriptChannel = webViewProxy.createJavaScriptChannel( | ||
name, | ||
postMessage: withWeakRefenceTo( | ||
onMessageReceived, | ||
(WeakReference<void Function(JavaScriptMessage)> weakReference) { | ||
return ( | ||
String message, | ||
) { | ||
if (weakReference.target != null) { | ||
weakReference.target!( | ||
JavaScriptMessage(message: message), | ||
); | ||
} | ||
}; | ||
}, | ||
), | ||
); | ||
|
||
/// Constructs a [AndroidJavaScriptChannelParams] using a | ||
/// [JavaScriptChannelParams]. | ||
AndroidJavaScriptChannelParams.fromJavaScriptChannelParams( | ||
JavaScriptChannelParams params, { | ||
@visibleForTesting | ||
AndroidWebViewProxy webViewProxy = const AndroidWebViewProxy(), | ||
}) : this( | ||
name: params.name, | ||
onMessageReceived: params.onMessageReceived, | ||
webViewProxy: webViewProxy, | ||
); | ||
|
||
final android_webview.JavaScriptChannel _javaScriptChannel; | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.