created flutter_inappwebview_web, updated web_support.js path

This commit is contained in:
Lorenzo Pichilli 2023-11-27 12:09:17 +01:00
parent b66eeae75a
commit b99824ee21
61 changed files with 3157 additions and 81 deletions

View File

@ -1,8 +1,9 @@
## 6.1.0-beta.1
## 6.0.0-beta.29
### BREAKING CHANGES
Plugin conversion to a [Federated Plugin](https://docs.flutter.dev/packages-and-plugins/developing-packages#federated-plugins) to better support multiple environments and implementations.
- Plugin conversion to a [Federated Plugin](https://docs.flutter.dev/packages-and-plugins/developing-packages#federated-plugins) to better support multiple environments and implementations.
- `web_support.js` path has been changed to `packages/flutter_inappwebview_web/assets/web/web_support.js`
## 6.0.0-beta.28

View File

@ -64,7 +64,7 @@ To make it work properly on the Web platform, you need to add the `web_support.j
```html
<head>
<!-- ... -->
<script type="application/javascript" src="/assets/packages/flutter_inappwebview/assets/web/web_support.js" defer></script>
<script type="application/javascript" src="/assets/packages/flutter_inappwebview_web/assets/web/web_support.js" defer></script>
<!-- ... -->
</head>
```

View File

@ -33,7 +33,7 @@
<link rel="manifest" href="manifest.json">
<!-- Load flutter_inappwebview web_support js library -->
<script type="application/javascript" src="/assets/packages/flutter_inappwebview/assets/web/web_support.js" defer></script>
<script type="application/javascript" src="/assets/packages/flutter_inappwebview_web/assets/web/web_support.js" defer></script>
</head>
<body>
<!-- This script installs service_worker.js to provide PWA functionality to

View File

@ -7,7 +7,7 @@ import '../find_interaction/find_interaction_controller.dart';
import '../pull_to_refresh/pull_to_refresh_controller.dart';
import 'in_app_webview_controller.dart';
/// Object specifying creation parameters for creating a [AndroidCookieManager].
/// Object specifying creation parameters for creating a [AndroidHeadlessInAppWebView].
///
/// When adding additional fields make sure they can be null or have a default
/// value to avoid breaking changes. See [PlatformHeadlessInAppWebViewCreationParams] for

View File

@ -391,12 +391,10 @@ class AndroidInAppWebViewWidget extends PlatformInAppWebViewWidget {
void _onPlatformViewCreated(int id) {
dynamic viewId = id;
if (!kIsWeb) {
if (_androidParams.headlessWebView?.isRunning() ?? false) {
viewId = _androidParams.headlessWebView?.id;
}
viewId = _androidParams.keepAlive?.id ?? viewId ?? id;
if (_androidParams.headlessWebView?.isRunning() ?? false) {
viewId = _androidParams.headlessWebView?.id;
}
viewId = _androidParams.keepAlive?.id ?? viewId ?? id;
_androidHeadlessInAppWebView?.internalDispose();
_controller = AndroidInAppWebViewController(
PlatformInAppWebViewControllerCreationParams(

View File

@ -17,7 +17,7 @@ import 'tracing_controller.dart';
import 'webview_asset_loader.dart';
import 'webview_feature.dart' as wv;
/// Implementation of [InAppWebViewPlatform] using the WebKit API.
/// Implementation of [InAppWebViewPlatform] using the WebView API.
class AndroidInAppWebViewPlatform extends InAppWebViewPlatform {
/// Registers this class as the default instance of [InAppWebViewPlatform].
static void registerWith() {

View File

@ -7,7 +7,7 @@ import '../find_interaction/find_interaction_controller.dart';
import '../pull_to_refresh/pull_to_refresh_controller.dart';
import 'in_app_webview_controller.dart';
/// Object specifying creation parameters for creating a [IOSCookieManager].
/// Object specifying creation parameters for creating a [IOSHeadlessInAppWebView].
///
/// When adding additional fields make sure they can be null or have a default
/// value to avoid breaking changes. See [PlatformHeadlessInAppWebViewCreationParams] for

View File

@ -335,12 +335,10 @@ class IOSInAppWebViewWidget extends PlatformInAppWebViewWidget {
void _onPlatformViewCreated(int id) {
dynamic viewId = id;
if (!kIsWeb) {
if (_iosParams.headlessWebView?.isRunning() ?? false) {
viewId = _iosParams.headlessWebView?.id;
}
viewId = _iosParams.keepAlive?.id ?? viewId ?? id;
if (_iosParams.headlessWebView?.isRunning() ?? false) {
viewId = _iosParams.headlessWebView?.id;
}
viewId = _iosParams.keepAlive?.id ?? viewId ?? id;
_iosHeadlessInAppWebView?.internalDispose();
_controller = IOSInAppWebViewController(
PlatformInAppWebViewControllerCreationParams(

View File

@ -6,7 +6,7 @@ import 'package:flutter_inappwebview_platform_interface/flutter_inappwebview_pla
import '../find_interaction/find_interaction_controller.dart';
import 'in_app_webview_controller.dart';
/// Object specifying creation parameters for creating a [MacOSCookieManager].
/// Object specifying creation parameters for creating a [MacOSHeadlessInAppWebView].
///
/// When adding additional fields make sure they can be null or have a default
/// value to avoid breaking changes. See [PlatformHeadlessInAppWebViewCreationParams] for

View File

@ -329,12 +329,10 @@ class MacOSInAppWebViewWidget extends PlatformInAppWebViewWidget {
void _onPlatformViewCreated(int id) {
dynamic viewId = id;
if (!kIsWeb) {
if (_macosParams.headlessWebView?.isRunning() ?? false) {
viewId = _macosParams.headlessWebView?.id;
}
viewId = _macosParams.keepAlive?.id ?? viewId ?? id;
if (_macosParams.headlessWebView?.isRunning() ?? false) {
viewId = _macosParams.headlessWebView?.id;
}
viewId = _macosParams.keepAlive?.id ?? viewId ?? id;
_macosHeadlessInAppWebView?.internalDispose();
_controller = MacOSInAppWebViewController(
PlatformInAppWebViewControllerCreationParams(

View File

@ -247,7 +247,7 @@ abstract class PlatformFindInteractionController extends PlatformInterface
///Disposes the controller.
///{@endtemplate}
@override
void dispose() {
void dispose({bool isKeepAlive = false}) {
throw UnimplementedError(
'dispose is not implemented on the current platform');
}

30
flutter_inappwebview_web/.gitignore vendored Normal file
View File

@ -0,0 +1,30 @@
# Miscellaneous
*.class
*.log
*.pyc
*.swp
.DS_Store
.atom/
.buildlog/
.history
.svn/
migrate_working_dir/
# IntelliJ related
*.iml
*.ipr
*.iws
.idea/
# The .vscode folder contains launch configuration and tasks you configure in
# VS Code which you may wish to be included in version control, so this line
# is commented out by default.
#.vscode/
# Flutter/Dart/Pub related
# Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock.
/pubspec.lock
**/doc/api/
.dart_tool/
.packages
build/

View File

@ -0,0 +1,30 @@
# This file tracks properties of this Flutter project.
# Used by Flutter tool to assess capabilities and perform upgrades etc.
#
# This file should be version controlled and should not be manually edited.
version:
revision: "6c4930c4ac86fb286f30e31d0ec8bffbcbb9953e"
channel: "stable"
project_type: plugin
# Tracks metadata for the flutter migrate command
migration:
platforms:
- platform: root
create_revision: 6c4930c4ac86fb286f30e31d0ec8bffbcbb9953e
base_revision: 6c4930c4ac86fb286f30e31d0ec8bffbcbb9953e
- platform: web
create_revision: 6c4930c4ac86fb286f30e31d0ec8bffbcbb9953e
base_revision: 6c4930c4ac86fb286f30e31d0ec8bffbcbb9953e
# User provided section
# List of Local paths (relative to this file) that should be
# ignored by the migrate tool.
#
# Files that are not part of the templates will be ignored by default.
unmanaged_files:
- 'lib/main.dart'
- 'ios/Runner.xcodeproj/project.pbxproj'

View File

@ -0,0 +1,3 @@
## 0.0.1
* TODO: Describe initial release.

View File

@ -0,0 +1 @@
TODO: Add your license here.

View File

@ -0,0 +1,15 @@
# flutter_inappwebview_web
A new Flutter project.
## Getting Started
This project is a starting point for a Flutter
[plug-in package](https://flutter.dev/developing-packages/),
a specialized package that includes platform-specific implementation code for
Android and/or iOS.
For help getting started with Flutter development, view the
[online documentation](https://flutter.dev/docs), which offers tutorials,
samples, guidance on mobile development, and a full API reference.

View File

@ -0,0 +1,13 @@
include: package:flutter_lints/flutter.yaml
linter:
rules:
constant_identifier_names: ignore
deprecated_member_use_from_same_package: ignore
# Additional information about this file can be found at
# https://dart.dev/guides/language/analysis-options
analyzer:
errors:
deprecated_member_use: ignore
deprecated_member_use_from_same_package: ignore

View File

@ -0,0 +1,5 @@
targets:
$default:
sources:
exclude:
- example/**.dart

View File

@ -0,0 +1,44 @@
# Miscellaneous
*.class
*.log
*.pyc
*.swp
.DS_Store
.atom/
.buildlog/
.history
.svn/
migrate_working_dir/
# IntelliJ related
*.iml
*.ipr
*.iws
.idea/
# The .vscode folder contains launch configuration and tasks you configure in
# VS Code which you may wish to be included in version control, so this line
# is commented out by default.
#.vscode/
# Flutter/Dart/Pub related
**/doc/api/
**/ios/Flutter/.last_build_id
.dart_tool/
.flutter-plugins
.flutter-plugins-dependencies
.packages
.pub-cache/
.pub/
/build/
# Symbolication related
app.*.symbols
# Obfuscation related
app.*.map.json
# Android Studio will place build artifacts here
/android/app/debug
/android/app/profile
/android/app/release

View File

@ -0,0 +1,16 @@
# flutter_inappwebview_web_example
Demonstrates how to use the flutter_inappwebview_web plugin.
## Getting Started
This project is a starting point for a Flutter application.
A few resources to get you started if this is your first Flutter project:
- [Lab: Write your first Flutter app](https://docs.flutter.dev/get-started/codelab)
- [Cookbook: Useful Flutter samples](https://docs.flutter.dev/cookbook)
For help getting started with Flutter development, view the
[online documentation](https://docs.flutter.dev/), which offers tutorials,
samples, guidance on mobile development, and a full API reference.

View File

@ -0,0 +1,28 @@
# This file configures the analyzer, which statically analyzes Dart code to
# check for errors, warnings, and lints.
#
# The issues identified by the analyzer are surfaced in the UI of Dart-enabled
# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be
# invoked from the command line by running `flutter analyze`.
# The following line activates a set of recommended lints for Flutter apps,
# packages, and plugins designed to encourage good coding practices.
include: package:flutter_lints/flutter.yaml
linter:
# The lint rules applied to this project can be customized in the
# section below to disable rules from the `package:flutter_lints/flutter.yaml`
# included above or to enable additional rules. A list of all available lints
# and their documentation is published at https://dart.dev/lints.
#
# Instead of disabling a lint rule for the entire project in the
# section below, it can also be suppressed for a single line of code
# or a specific dart file by using the `// ignore: name_of_lint` and
# `// ignore_for_file: name_of_lint` syntax on the line or in the file
# producing the lint.
rules:
# avoid_print: false # Uncomment to disable the `avoid_print` rule
# prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule
# Additional information about this file can be found at
# https://dart.dev/guides/language/analysis-options

View File

@ -0,0 +1,295 @@
# Generated by pub
# See https://dart.dev/tools/pub/glossary#lockfile
packages:
async:
dependency: transitive
description:
name: async
sha256: "947bfcf187f74dbc5e146c9eb9c0f10c9f8b30743e341481c1e2ed3ecc18c20c"
url: "https://pub.dev"
source: hosted
version: "2.11.0"
boolean_selector:
dependency: transitive
description:
name: boolean_selector
sha256: "6cfb5af12253eaf2b368f07bacc5a80d1301a071c73360d746b7f2e32d762c66"
url: "https://pub.dev"
source: hosted
version: "2.1.1"
characters:
dependency: transitive
description:
name: characters
sha256: "04a925763edad70e8443c99234dc3328f442e811f1d8fd1a72f1c8ad0f69a605"
url: "https://pub.dev"
source: hosted
version: "1.3.0"
clock:
dependency: transitive
description:
name: clock
sha256: cb6d7f03e1de671e34607e909a7213e31d7752be4fb66a86d29fe1eb14bfb5cf
url: "https://pub.dev"
source: hosted
version: "1.1.1"
collection:
dependency: transitive
description:
name: collection
sha256: f092b211a4319e98e5ff58223576de6c2803db36221657b46c82574721240687
url: "https://pub.dev"
source: hosted
version: "1.17.2"
cupertino_icons:
dependency: "direct main"
description:
name: cupertino_icons
sha256: d57953e10f9f8327ce64a508a355f0b1ec902193f66288e8cb5070e7c47eeb2d
url: "https://pub.dev"
source: hosted
version: "1.0.6"
fake_async:
dependency: transitive
description:
name: fake_async
sha256: "511392330127add0b769b75a987850d136345d9227c6b94c96a04cf4a391bf78"
url: "https://pub.dev"
source: hosted
version: "1.3.1"
file:
dependency: transitive
description:
name: file
sha256: "1b92bec4fc2a72f59a8e15af5f52cd441e4a7860b49499d69dfa817af20e925d"
url: "https://pub.dev"
source: hosted
version: "6.1.4"
flutter:
dependency: "direct main"
description: flutter
source: sdk
version: "0.0.0"
flutter_driver:
dependency: transitive
description: flutter
source: sdk
version: "0.0.0"
flutter_inappwebview_internal_annotations:
dependency: transitive
description:
name: flutter_inappwebview_internal_annotations
sha256: "5f80fd30e208ddded7dbbcd0d569e7995f9f63d45ea3f548d8dd4c0b473fb4c8"
url: "https://pub.dev"
source: hosted
version: "1.1.1"
flutter_inappwebview_platform_interface:
dependency: transitive
description:
path: "../../flutter_inappwebview_platform_interface"
relative: true
source: path
version: "1.0.0"
flutter_inappwebview_web:
dependency: "direct main"
description:
path: ".."
relative: true
source: path
version: "1.0.0"
flutter_lints:
dependency: "direct dev"
description:
name: flutter_lints
sha256: a25a15ebbdfc33ab1cd26c63a6ee519df92338a9c10f122adda92938253bef04
url: "https://pub.dev"
source: hosted
version: "2.0.3"
flutter_test:
dependency: "direct dev"
description: flutter
source: sdk
version: "0.0.0"
flutter_web_plugins:
dependency: transitive
description: flutter
source: sdk
version: "0.0.0"
fuchsia_remote_debug_protocol:
dependency: transitive
description: flutter
source: sdk
version: "0.0.0"
integration_test:
dependency: "direct dev"
description: flutter
source: sdk
version: "0.0.0"
js:
dependency: transitive
description:
name: js
sha256: f2c445dce49627136094980615a031419f7f3eb393237e4ecd97ac15dea343f3
url: "https://pub.dev"
source: hosted
version: "0.6.7"
lints:
dependency: transitive
description:
name: lints
sha256: "0a217c6c989d21039f1498c3ed9f3ed71b354e69873f13a8dfc3c9fe76f1b452"
url: "https://pub.dev"
source: hosted
version: "2.1.1"
matcher:
dependency: transitive
description:
name: matcher
sha256: "1803e76e6653768d64ed8ff2e1e67bea3ad4b923eb5c56a295c3e634bad5960e"
url: "https://pub.dev"
source: hosted
version: "0.12.16"
material_color_utilities:
dependency: transitive
description:
name: material_color_utilities
sha256: "9528f2f296073ff54cb9fee677df673ace1218163c3bc7628093e7eed5203d41"
url: "https://pub.dev"
source: hosted
version: "0.5.0"
meta:
dependency: transitive
description:
name: meta
sha256: "3c74dbf8763d36539f114c799d8a2d87343b5067e9d796ca22b5eb8437090ee3"
url: "https://pub.dev"
source: hosted
version: "1.9.1"
path:
dependency: transitive
description:
name: path
sha256: "8829d8a55c13fc0e37127c29fedf290c102f4e40ae94ada574091fe0ff96c917"
url: "https://pub.dev"
source: hosted
version: "1.8.3"
platform:
dependency: transitive
description:
name: platform
sha256: "4a451831508d7d6ca779f7ac6e212b4023dd5a7d08a27a63da33756410e32b76"
url: "https://pub.dev"
source: hosted
version: "3.1.0"
plugin_platform_interface:
dependency: transitive
description:
name: plugin_platform_interface
sha256: f4f88d4a900933e7267e2b353594774fc0d07fb072b47eedcd5b54e1ea3269f8
url: "https://pub.dev"
source: hosted
version: "2.1.7"
process:
dependency: transitive
description:
name: process
sha256: "53fd8db9cec1d37b0574e12f07520d582019cb6c44abf5479a01505099a34a09"
url: "https://pub.dev"
source: hosted
version: "4.2.4"
sky_engine:
dependency: transitive
description: flutter
source: sdk
version: "0.0.99"
source_span:
dependency: transitive
description:
name: source_span
sha256: "53e943d4206a5e30df338fd4c6e7a077e02254531b138a15aec3bd143c1a8b3c"
url: "https://pub.dev"
source: hosted
version: "1.10.0"
stack_trace:
dependency: transitive
description:
name: stack_trace
sha256: c3c7d8edb15bee7f0f74debd4b9c5f3c2ea86766fe4178eb2a18eb30a0bdaed5
url: "https://pub.dev"
source: hosted
version: "1.11.0"
stream_channel:
dependency: transitive
description:
name: stream_channel
sha256: "83615bee9045c1d322bbbd1ba209b7a749c2cbcdcb3fdd1df8eb488b3279c1c8"
url: "https://pub.dev"
source: hosted
version: "2.1.1"
string_scanner:
dependency: transitive
description:
name: string_scanner
sha256: "556692adab6cfa87322a115640c11f13cb77b3f076ddcc5d6ae3c20242bedcde"
url: "https://pub.dev"
source: hosted
version: "1.2.0"
sync_http:
dependency: transitive
description:
name: sync_http
sha256: "7f0cd72eca000d2e026bcd6f990b81d0ca06022ef4e32fb257b30d3d1014a961"
url: "https://pub.dev"
source: hosted
version: "0.3.1"
term_glyph:
dependency: transitive
description:
name: term_glyph
sha256: a29248a84fbb7c79282b40b8c72a1209db169a2e0542bce341da992fe1bc7e84
url: "https://pub.dev"
source: hosted
version: "1.2.1"
test_api:
dependency: transitive
description:
name: test_api
sha256: "75760ffd7786fffdfb9597c35c5b27eaeec82be8edfb6d71d32651128ed7aab8"
url: "https://pub.dev"
source: hosted
version: "0.6.0"
vector_math:
dependency: transitive
description:
name: vector_math
sha256: "80b3257d1492ce4d091729e3a67a60407d227c27241d6927be0130c98e741803"
url: "https://pub.dev"
source: hosted
version: "2.1.4"
vm_service:
dependency: transitive
description:
name: vm_service
sha256: c620a6f783fa22436da68e42db7ebbf18b8c44b9a46ab911f666ff09ffd9153f
url: "https://pub.dev"
source: hosted
version: "11.7.1"
web:
dependency: transitive
description:
name: web
sha256: dc8ccd225a2005c1be616fe02951e2e342092edf968cf0844220383757ef8f10
url: "https://pub.dev"
source: hosted
version: "0.1.4-beta"
webdriver:
dependency: transitive
description:
name: webdriver
sha256: "3c923e918918feeb90c4c9fdf1fe39220fa4c0e8e2c0fffaded174498ef86c49"
url: "https://pub.dev"
source: hosted
version: "3.0.2"
sdks:
dart: ">=3.1.4 <4.0.0"
flutter: ">=3.0.0"

View File

@ -0,0 +1,85 @@
name: flutter_inappwebview_web_example
description: Demonstrates how to use the flutter_inappwebview_web plugin.
# The following line prevents the package from being accidentally published to
# pub.dev using `flutter pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
environment:
sdk: '>=3.1.4 <4.0.0'
# Dependencies specify other packages that your package needs in order to work.
# To automatically upgrade your package dependencies to the latest versions
# consider running `flutter pub upgrade --major-versions`. Alternatively,
# dependencies can be manually updated by changing the version numbers below to
# the latest version available on pub.dev. To see which dependencies have newer
# versions available, run `flutter pub outdated`.
dependencies:
flutter:
sdk: flutter
flutter_inappwebview_web:
# When depending on this package from a real application you should use:
# flutter_inappwebview_web: ^x.y.z
# See https://dart.dev/tools/pub/dependencies#version-constraints
# The example app is bundled with the plugin so we use a path dependency on
# the parent directory to use the current plugin's version.
path: ../
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.2
dev_dependencies:
integration_test:
sdk: flutter
flutter_test:
sdk: flutter
# The "flutter_lints" package below contains a set of recommended lints to
# encourage good coding practices. The lint set provided by the package is
# activated in the `analysis_options.yaml` file located at the root of your
# package. See that file for information about deactivating specific lint
# rules and activating additional ones.
flutter_lints: ^2.0.0
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
# The following section is specific to Flutter packages.
flutter:
# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the material Icons class.
uses-material-design: true
# To add assets to your application, add an assets section, like this:
# assets:
# - images/a_dot_burr.jpeg
# - images/a_dot_ham.jpeg
# An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.dev/assets-and-images/#resolution-aware
# For details regarding adding assets from package dependencies, see
# https://flutter.dev/assets-and-images/#from-packages
# To add custom fonts to your application, add a fonts section here,
# in this "flutter" section. Each entry in this list should have a
# "family" key with the font family name, and a "fonts" key with a
# list giving the asset and other descriptors for the font. For
# example:
# fonts:
# - family: Schyler
# fonts:
# - asset: fonts/Schyler-Regular.ttf
# - asset: fonts/Schyler-Italic.ttf
# style: italic
# - family: Trajan Pro
# fonts:
# - asset: fonts/TrajanPro.ttf
# - asset: fonts/TrajanPro_Bold.ttf
# weight: 700
#
# For details regarding fonts from package dependencies,
# see https://flutter.dev/custom-fonts/#from-packages

Binary file not shown.

After

Width:  |  Height:  |  Size: 917 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

View File

@ -0,0 +1,59 @@
<!DOCTYPE html>
<html>
<head>
<!--
If you are serving your web app in a path other than the root, change the
href value below to reflect the base path you are serving from.
The path provided below has to start and end with a slash "/" in order for
it to work correctly.
For more details:
* https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base
This is a placeholder for base href that will be replaced by the value of
the `--base-href` argument provided to `flutter build`.
-->
<base href="$FLUTTER_BASE_HREF">
<meta charset="UTF-8">
<meta content="IE=Edge" http-equiv="X-UA-Compatible">
<meta name="description" content="Demonstrates how to use the flutter_inappwebview_web plugin.">
<!-- iOS meta tags & icons -->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-title" content="flutter_inappwebview_web_example">
<link rel="apple-touch-icon" href="icons/Icon-192.png">
<!-- Favicon -->
<link rel="icon" type="image/png" href="favicon.png"/>
<title>flutter_inappwebview_web_example</title>
<link rel="manifest" href="manifest.json">
<script>
// The value below is injected by flutter build, do not touch.
const serviceWorkerVersion = null;
</script>
<!-- This script adds the flutter initialization JS code -->
<script src="flutter.js" defer></script>
</head>
<body>
<script>
window.addEventListener('load', function(ev) {
// Download main.dart.js
_flutter.loader.loadEntrypoint({
serviceWorker: {
serviceWorkerVersion: serviceWorkerVersion,
},
onEntrypointLoaded: function(engineInitializer) {
engineInitializer.initializeEngine().then(function(appRunner) {
appRunner.runApp();
});
}
});
});
</script>
</body>
</html>

View File

@ -0,0 +1,35 @@
{
"name": "flutter_inappwebview_web_example",
"short_name": "flutter_inappwebview_web_example",
"start_url": ".",
"display": "standalone",
"background_color": "#0175C2",
"theme_color": "#0175C2",
"description": "Demonstrates how to use the flutter_inappwebview_web plugin.",
"orientation": "portrait-primary",
"prefer_related_applications": false,
"icons": [
{
"src": "icons/Icon-192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "icons/Icon-512.png",
"sizes": "512x512",
"type": "image/png"
},
{
"src": "icons/Icon-maskable-192.png",
"sizes": "192x192",
"type": "image/png",
"purpose": "maskable"
},
{
"src": "icons/Icon-maskable-512.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "maskable"
}
]
}

View File

@ -485,6 +485,15 @@ window.flutter_inappwebview = {
}
return null;
},
getContentWidth: function() {
var iframe = webView.iframe;
try {
return iframe.contentDocument.documentElement.scrollWidth;
} catch (e) {
console.log(e);
}
return null;
},
getSelectedText: function() {
var iframe = webView.iframe;
try {

View File

@ -0,0 +1,4 @@
library flutter_inappwebview_web;
export 'src/main.dart';
export 'web/main.dart';

View File

@ -0,0 +1,309 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_inappwebview_platform_interface/flutter_inappwebview_platform_interface.dart';
import 'in_app_webview/headless_in_app_webview.dart';
import 'platform_util.dart';
/// Object specifying creation parameters for creating a [WebPlatformCookieManager].
///
/// When adding additional fields make sure they can be null or have a default
/// value to avoid breaking changes. See [PlatformCookieManagerCreationParams] for
/// more information.
@immutable
class WebPlatformCookieManagerCreationParams
extends PlatformCookieManagerCreationParams {
/// Creates a new [WebPlatformCookieManagerCreationParams] instance.
const WebPlatformCookieManagerCreationParams(
// This parameter prevents breaking changes later.
// ignore: avoid_unused_constructor_parameters
PlatformCookieManagerCreationParams params,
) : super();
/// Creates a [WebPlatformCookieManagerCreationParams] instance based on [PlatformCookieManagerCreationParams].
factory WebPlatformCookieManagerCreationParams.fromPlatformCookieManagerCreationParams(
PlatformCookieManagerCreationParams params) {
return WebPlatformCookieManagerCreationParams(params);
}
}
///{@macro flutter_inappwebview_platform_interface.PlatformCookieManager}
class WebPlatformCookieManager extends PlatformCookieManager
with ChannelController {
/// Creates a new [WebPlatformCookieManager].
WebPlatformCookieManager(PlatformCookieManagerCreationParams params)
: super.implementation(
params is WebPlatformCookieManagerCreationParams
? params
: WebPlatformCookieManagerCreationParams
.fromPlatformCookieManagerCreationParams(params),
) {
channel = const MethodChannel(
'com.pichillilorenzo/flutter_inappwebview_cookiemanager');
handler = handleMethod;
initMethodCallHandler();
}
static WebPlatformCookieManager? _instance;
///Gets the [WebPlatformCookieManager] shared instance.
static WebPlatformCookieManager instance() {
return (_instance != null) ? _instance! : _init();
}
static WebPlatformCookieManager _init() {
_instance = WebPlatformCookieManager(WebPlatformCookieManagerCreationParams(
const PlatformCookieManagerCreationParams()));
return _instance!;
}
Future<dynamic> _handleMethod(MethodCall call) async {}
@override
Future<bool> setCookie(
{required WebUri url,
required String name,
required String value,
String path = "/",
String? domain,
int? expiresDate,
int? maxAge,
bool? isSecure,
bool? isHttpOnly,
HTTPCookieSameSitePolicy? sameSite,
@Deprecated("Use webViewController instead")
PlatformInAppWebViewController? iosBelow11WebViewController,
PlatformInAppWebViewController? webViewController}) async {
webViewController = webViewController ?? iosBelow11WebViewController;
assert(url.toString().isNotEmpty);
assert(name.isNotEmpty);
assert(value.isNotEmpty);
assert(path.isNotEmpty);
await _setCookieWithJavaScript(
url: url,
name: name,
value: value,
domain: domain,
path: path,
expiresDate: expiresDate,
maxAge: maxAge,
isSecure: isSecure,
sameSite: sameSite,
webViewController: webViewController);
return true;
}
Future<void> _setCookieWithJavaScript(
{required WebUri url,
required String name,
required String value,
String path = "/",
String? domain,
int? expiresDate,
int? maxAge,
bool? isSecure,
HTTPCookieSameSitePolicy? sameSite,
PlatformInAppWebViewController? webViewController}) async {
var cookieValue = name + "=" + value + "; Path=" + path;
if (domain != null) cookieValue += "; Domain=" + domain;
if (expiresDate != null)
cookieValue += "; Expires=" + await _getCookieExpirationDate(expiresDate);
if (maxAge != null) cookieValue += "; Max-Age=" + maxAge.toString();
if (isSecure != null && isSecure) cookieValue += "; Secure";
if (sameSite != null)
cookieValue += "; SameSite=" + sameSite.toNativeValue();
cookieValue += ";";
if (webViewController != null) {
final javaScriptEnabled =
(await webViewController.getSettings())?.javaScriptEnabled ?? false;
if (javaScriptEnabled) {
await webViewController.evaluateJavascript(
source: 'document.cookie="$cookieValue"');
return;
}
}
final setCookieCompleter = Completer<void>();
final headlessWebView =
WebPlatformHeadlessInAppWebView(WebPlatformHeadlessInAppWebViewCreationParams(
initialUrlRequest: URLRequest(url: url),
onLoadStop: (controller, url) async {
await controller.evaluateJavascript(
source: 'document.cookie="$cookieValue"');
setCookieCompleter.complete();
}));
await headlessWebView.run();
await setCookieCompleter.future;
await headlessWebView.dispose();
}
@override
Future<List<Cookie>> getCookies(
{required WebUri url,
@Deprecated("Use webViewController instead")
PlatformInAppWebViewController? iosBelow11WebViewController,
PlatformInAppWebViewController? webViewController}) async {
assert(url.toString().isNotEmpty);
webViewController = webViewController ?? iosBelow11WebViewController;
return await _getCookiesWithJavaScript(
url: url, webViewController: webViewController);
}
Future<List<Cookie>> _getCookiesWithJavaScript(
{required WebUri url,
PlatformInAppWebViewController? webViewController}) async {
assert(url.toString().isNotEmpty);
List<Cookie> cookies = [];
if (webViewController != null) {
final javaScriptEnabled =
(await webViewController.getSettings())?.javaScriptEnabled ?? false;
if (javaScriptEnabled) {
List<String> documentCookies = (await webViewController
.evaluateJavascript(source: 'document.cookie') as String)
.split(';')
.map((documentCookie) => documentCookie.trim())
.toList();
documentCookies.forEach((documentCookie) {
List<String> cookie = documentCookie.split('=');
if (cookie.length > 1) {
cookies.add(Cookie(
name: cookie[0],
value: cookie[1],
));
}
});
return cookies;
}
}
final pageLoaded = Completer<void>();
final headlessWebView =
WebPlatformHeadlessInAppWebView(WebPlatformHeadlessInAppWebViewCreationParams(
initialUrlRequest: URLRequest(url: url),
onLoadStop: (controller, url) async {
pageLoaded.complete();
},
));
await headlessWebView.run();
await pageLoaded.future;
List<String> documentCookies = (await headlessWebView.webViewController!
.evaluateJavascript(source: 'document.cookie') as String)
.split(';')
.map((documentCookie) => documentCookie.trim())
.toList();
documentCookies.forEach((documentCookie) {
List<String> cookie = documentCookie.split('=');
if (cookie.length > 1) {
cookies.add(Cookie(
name: cookie[0],
value: cookie[1],
));
}
});
await headlessWebView.dispose();
return cookies;
}
@override
Future<Cookie?> getCookie(
{required WebUri url,
required String name,
@Deprecated("Use webViewController instead")
PlatformInAppWebViewController? iosBelow11WebViewController,
PlatformInAppWebViewController? webViewController}) async {
assert(url.toString().isNotEmpty);
assert(name.isNotEmpty);
webViewController = webViewController ?? iosBelow11WebViewController;
List<Cookie> cookies = await _getCookiesWithJavaScript(
url: url, webViewController: webViewController);
return cookies
.cast<Cookie?>()
.firstWhere((cookie) => cookie!.name == name, orElse: () => null);
}
@override
Future<void> deleteCookie(
{required WebUri url,
required String name,
String path = "/",
String? domain,
@Deprecated("Use webViewController instead")
PlatformInAppWebViewController? iosBelow11WebViewController,
PlatformInAppWebViewController? webViewController}) async {
assert(url.toString().isNotEmpty);
assert(name.isNotEmpty);
webViewController = webViewController ?? iosBelow11WebViewController;
await _setCookieWithJavaScript(
url: url,
name: name,
value: "",
path: path,
domain: domain,
maxAge: -1,
webViewController: webViewController);
return;
}
@override
Future<void> deleteCookies(
{required WebUri url,
String path = "/",
String? domain,
@Deprecated("Use webViewController instead")
PlatformInAppWebViewController? iosBelow11WebViewController,
PlatformInAppWebViewController? webViewController}) async {
assert(url.toString().isNotEmpty);
webViewController = webViewController ?? iosBelow11WebViewController;
List<Cookie> cookies = await _getCookiesWithJavaScript(
url: url, webViewController: webViewController);
for (var i = 0; i < cookies.length; i++) {
await _setCookieWithJavaScript(
url: url,
name: cookies[i].name,
value: "",
path: path,
domain: domain,
maxAge: -1,
webViewController: webViewController);
}
return;
}
Future<String> _getCookieExpirationDate(int expiresDate) async {
var platformUtil = PlatformUtil.instance();
var dateTime = DateTime.fromMillisecondsSinceEpoch(expiresDate).toUtc();
return await platformUtil.getWebCookieExpirationDate(date: dateTime);
}
@override
void dispose() {
// empty
}
}
extension InternalCookieManager on WebPlatformCookieManager {
get handleMethod => _handleMethod;
}

View File

@ -0,0 +1,4 @@
import 'package:flutter/services.dart';
const IN_APP_WEBVIEW_STATIC_CHANNEL =
MethodChannel('com.pichillilorenzo/flutter_inappwebview_manager');

View File

@ -0,0 +1,428 @@
import 'dart:ui';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_inappwebview_platform_interface/flutter_inappwebview_platform_interface.dart';
import 'in_app_webview_controller.dart';
/// Object specifying creation parameters for creating a [WebPlatformHeadlessInAppWebView].
///
/// When adding additional fields make sure they can be null or have a default
/// value to avoid breaking changes. See [PlatformHeadlessInAppWebViewCreationParams] for
/// more information.
@immutable
class WebPlatformHeadlessInAppWebViewCreationParams
extends PlatformHeadlessInAppWebViewCreationParams {
/// Creates a new [WebPlatformHeadlessInAppWebViewCreationParams] instance.
WebPlatformHeadlessInAppWebViewCreationParams(
{super.controllerFromPlatform,
super.initialSize,
super.windowId,
super.onWebViewCreated,
super.onLoadStart,
super.onLoadStop,
@Deprecated('Use onReceivedError instead') super.onLoadError,
super.onReceivedError,
@Deprecated("Use onReceivedHttpError instead") super.onLoadHttpError,
super.onReceivedHttpError,
super.onProgressChanged,
super.onConsoleMessage,
super.shouldOverrideUrlLoading,
super.onLoadResource,
super.onScrollChanged,
@Deprecated('Use onDownloadStartRequest instead') super.onDownloadStart,
super.onDownloadStartRequest,
@Deprecated('Use onLoadResourceWithCustomScheme instead')
super.onLoadResourceCustomScheme,
super.onLoadResourceWithCustomScheme,
super.onCreateWindow,
super.onCloseWindow,
super.onJsAlert,
super.onJsConfirm,
super.onJsPrompt,
super.onReceivedHttpAuthRequest,
super.onReceivedServerTrustAuthRequest,
super.onReceivedClientCertRequest,
@Deprecated('Use FindInteractionController.onFindResultReceived instead')
super.onFindResultReceived,
super.shouldInterceptAjaxRequest,
super.onAjaxReadyStateChange,
super.onAjaxProgress,
super.shouldInterceptFetchRequest,
super.onUpdateVisitedHistory,
@Deprecated("Use onPrintRequest instead") super.onPrint,
super.onPrintRequest,
super.onLongPressHitTestResult,
super.onEnterFullscreen,
super.onExitFullscreen,
super.onPageCommitVisible,
super.onTitleChanged,
super.onWindowFocus,
super.onWindowBlur,
super.onOverScrolled,
super.onZoomScaleChanged,
@Deprecated('Use onSafeBrowsingHit instead')
super.androidOnSafeBrowsingHit,
super.onSafeBrowsingHit,
@Deprecated('Use onPermissionRequest instead')
super.androidOnPermissionRequest,
super.onPermissionRequest,
@Deprecated('Use onGeolocationPermissionsShowPrompt instead')
super.androidOnGeolocationPermissionsShowPrompt,
super.onGeolocationPermissionsShowPrompt,
@Deprecated('Use onGeolocationPermissionsHidePrompt instead')
super.androidOnGeolocationPermissionsHidePrompt,
super.onGeolocationPermissionsHidePrompt,
@Deprecated('Use shouldInterceptRequest instead')
super.androidShouldInterceptRequest,
super.shouldInterceptRequest,
@Deprecated('Use onRenderProcessGone instead')
super.androidOnRenderProcessGone,
super.onRenderProcessGone,
@Deprecated('Use onRenderProcessResponsive instead')
super.androidOnRenderProcessResponsive,
super.onRenderProcessResponsive,
@Deprecated('Use onRenderProcessUnresponsive instead')
super.androidOnRenderProcessUnresponsive,
super.onRenderProcessUnresponsive,
@Deprecated('Use onFormResubmission instead')
super.androidOnFormResubmission,
super.onFormResubmission,
@Deprecated('Use onZoomScaleChanged instead') super.androidOnScaleChanged,
@Deprecated('Use onReceivedIcon instead') super.androidOnReceivedIcon,
super.onReceivedIcon,
@Deprecated('Use onReceivedTouchIconUrl instead')
super.androidOnReceivedTouchIconUrl,
super.onReceivedTouchIconUrl,
@Deprecated('Use onJsBeforeUnload instead') super.androidOnJsBeforeUnload,
super.onJsBeforeUnload,
@Deprecated('Use onReceivedLoginRequest instead')
super.androidOnReceivedLoginRequest,
super.onReceivedLoginRequest,
super.onPermissionRequestCanceled,
super.onRequestFocus,
@Deprecated('Use onWebContentProcessDidTerminate instead')
super.iosOnWebContentProcessDidTerminate,
super.onWebContentProcessDidTerminate,
@Deprecated(
'Use onDidReceiveServerRedirectForProvisionalNavigation instead')
super.iosOnDidReceiveServerRedirectForProvisionalNavigation,
super.onDidReceiveServerRedirectForProvisionalNavigation,
@Deprecated('Use onNavigationResponse instead')
super.iosOnNavigationResponse,
super.onNavigationResponse,
@Deprecated('Use shouldAllowDeprecatedTLS instead')
super.iosShouldAllowDeprecatedTLS,
super.shouldAllowDeprecatedTLS,
super.onCameraCaptureStateChanged,
super.onMicrophoneCaptureStateChanged,
super.onContentSizeChanged,
super.initialUrlRequest,
super.initialFile,
super.initialData,
@Deprecated('Use initialSettings instead') super.initialOptions,
super.initialSettings,
super.contextMenu,
super.initialUserScripts,
super.pullToRefreshController,
super.findInteractionController});
/// Creates a [WebPlatformHeadlessInAppWebViewCreationParams] instance based on [PlatformHeadlessInAppWebViewCreationParams].
WebPlatformHeadlessInAppWebViewCreationParams.fromPlatformHeadlessInAppWebViewCreationParams(
PlatformHeadlessInAppWebViewCreationParams params)
: this(
controllerFromPlatform: params.controllerFromPlatform,
initialSize: params.initialSize,
windowId: params.windowId,
onWebViewCreated: params.onWebViewCreated,
onLoadStart: params.onLoadStart,
onLoadStop: params.onLoadStop,
onLoadError: params.onLoadError,
onReceivedError: params.onReceivedError,
onLoadHttpError: params.onLoadHttpError,
onReceivedHttpError: params.onReceivedHttpError,
onProgressChanged: params.onProgressChanged,
onConsoleMessage: params.onConsoleMessage,
shouldOverrideUrlLoading: params.shouldOverrideUrlLoading,
onLoadResource: params.onLoadResource,
onScrollChanged: params.onScrollChanged,
onDownloadStart: params.onDownloadStart,
onDownloadStartRequest: params.onDownloadStartRequest,
onLoadResourceCustomScheme: params.onLoadResourceCustomScheme,
onLoadResourceWithCustomScheme:
params.onLoadResourceWithCustomScheme,
onCreateWindow: params.onCreateWindow,
onCloseWindow: params.onCloseWindow,
onJsAlert: params.onJsAlert,
onJsConfirm: params.onJsConfirm,
onJsPrompt: params.onJsPrompt,
onReceivedHttpAuthRequest: params.onReceivedHttpAuthRequest,
onReceivedServerTrustAuthRequest:
params.onReceivedServerTrustAuthRequest,
onReceivedClientCertRequest: params.onReceivedClientCertRequest,
onFindResultReceived: params.onFindResultReceived,
shouldInterceptAjaxRequest: params.shouldInterceptAjaxRequest,
onAjaxReadyStateChange: params.onAjaxReadyStateChange,
onAjaxProgress: params.onAjaxProgress,
shouldInterceptFetchRequest: params.shouldInterceptFetchRequest,
onUpdateVisitedHistory: params.onUpdateVisitedHistory,
onPrint: params.onPrint,
onPrintRequest: params.onPrintRequest,
onLongPressHitTestResult: params.onLongPressHitTestResult,
onEnterFullscreen: params.onEnterFullscreen,
onExitFullscreen: params.onExitFullscreen,
onPageCommitVisible: params.onPageCommitVisible,
onTitleChanged: params.onTitleChanged,
onWindowFocus: params.onWindowFocus,
onWindowBlur: params.onWindowBlur,
onOverScrolled: params.onOverScrolled,
onZoomScaleChanged: params.onZoomScaleChanged,
androidOnSafeBrowsingHit: params.androidOnSafeBrowsingHit,
onSafeBrowsingHit: params.onSafeBrowsingHit,
androidOnPermissionRequest: params.androidOnPermissionRequest,
onPermissionRequest: params.onPermissionRequest,
androidOnGeolocationPermissionsShowPrompt:
params.androidOnGeolocationPermissionsShowPrompt,
onGeolocationPermissionsShowPrompt:
params.onGeolocationPermissionsShowPrompt,
androidOnGeolocationPermissionsHidePrompt:
params.androidOnGeolocationPermissionsHidePrompt,
onGeolocationPermissionsHidePrompt:
params.onGeolocationPermissionsHidePrompt,
androidShouldInterceptRequest: params.androidShouldInterceptRequest,
shouldInterceptRequest: params.shouldInterceptRequest,
androidOnRenderProcessGone: params.androidOnRenderProcessGone,
onRenderProcessGone: params.onRenderProcessGone,
androidOnRenderProcessResponsive:
params.androidOnRenderProcessResponsive,
onRenderProcessResponsive: params.onRenderProcessResponsive,
androidOnRenderProcessUnresponsive:
params.androidOnRenderProcessUnresponsive,
onRenderProcessUnresponsive: params.onRenderProcessUnresponsive,
androidOnFormResubmission: params.androidOnFormResubmission,
onFormResubmission: params.onFormResubmission,
androidOnScaleChanged: params.androidOnScaleChanged,
androidOnReceivedIcon: params.androidOnReceivedIcon,
onReceivedIcon: params.onReceivedIcon,
androidOnReceivedTouchIconUrl: params.androidOnReceivedTouchIconUrl,
onReceivedTouchIconUrl: params.onReceivedTouchIconUrl,
androidOnJsBeforeUnload: params.androidOnJsBeforeUnload,
onJsBeforeUnload: params.onJsBeforeUnload,
androidOnReceivedLoginRequest: params.androidOnReceivedLoginRequest,
onReceivedLoginRequest: params.onReceivedLoginRequest,
onPermissionRequestCanceled: params.onPermissionRequestCanceled,
onRequestFocus: params.onRequestFocus,
iosOnWebContentProcessDidTerminate:
params.iosOnWebContentProcessDidTerminate,
onWebContentProcessDidTerminate:
params.onWebContentProcessDidTerminate,
iosOnDidReceiveServerRedirectForProvisionalNavigation:
params.iosOnDidReceiveServerRedirectForProvisionalNavigation,
onDidReceiveServerRedirectForProvisionalNavigation:
params.onDidReceiveServerRedirectForProvisionalNavigation,
iosOnNavigationResponse: params.iosOnNavigationResponse,
onNavigationResponse: params.onNavigationResponse,
iosShouldAllowDeprecatedTLS: params.iosShouldAllowDeprecatedTLS,
shouldAllowDeprecatedTLS: params.shouldAllowDeprecatedTLS,
onCameraCaptureStateChanged: params.onCameraCaptureStateChanged,
onMicrophoneCaptureStateChanged:
params.onMicrophoneCaptureStateChanged,
onContentSizeChanged: params.onContentSizeChanged,
initialUrlRequest: params.initialUrlRequest,
initialFile: params.initialFile,
initialData: params.initialData,
initialOptions: params.initialOptions,
initialSettings: params.initialSettings,
contextMenu: params.contextMenu,
initialUserScripts: params.initialUserScripts,
pullToRefreshController: params.pullToRefreshController,
findInteractionController: params.findInteractionController);
}
///{@macro flutter_inappwebview_platform_interface.PlatformHeadlessInAppWebView}
class WebPlatformHeadlessInAppWebView extends PlatformHeadlessInAppWebView
with ChannelController {
@override
late final String id;
bool _started = false;
bool _running = false;
static const MethodChannel _sharedChannel =
const MethodChannel('com.pichillilorenzo/flutter_headless_inappwebview');
WebPlatformInAppWebViewController? _webViewController;
/// Constructs a [WebPlatformHeadlessInAppWebView].
WebPlatformHeadlessInAppWebView(PlatformHeadlessInAppWebViewCreationParams params)
: super.implementation(
params is WebPlatformHeadlessInAppWebViewCreationParams
? params
: WebPlatformHeadlessInAppWebViewCreationParams
.fromPlatformHeadlessInAppWebViewCreationParams(params),
) {
id = IdGenerator.generate();
}
@override
WebPlatformInAppWebViewController? get webViewController => _webViewController;
dynamic _controllerFromPlatform;
WebPlatformHeadlessInAppWebViewCreationParams get _macosParams =>
params as WebPlatformHeadlessInAppWebViewCreationParams;
_init() {
_webViewController = WebPlatformInAppWebViewController(
WebPlatformInAppWebViewControllerCreationParams(
id: id, webviewParams: params),
);
_controllerFromPlatform =
params.controllerFromPlatform?.call(_webViewController!) ??
_webViewController!;
channel =
MethodChannel('com.pichillilorenzo/flutter_headless_inappwebview_$id');
handler = _handleMethod;
initMethodCallHandler();
}
Future<dynamic> _handleMethod(MethodCall call) async {
switch (call.method) {
case "onWebViewCreated":
if (params.onWebViewCreated != null && _webViewController != null) {
params.onWebViewCreated!(_controllerFromPlatform);
}
break;
default:
throw UnimplementedError("Unimplemented ${call.method} method");
}
return null;
}
Future<void> run() async {
if (_started) {
return;
}
_started = true;
_init();
final initialSettings = params.initialSettings ?? InAppWebViewSettings();
_inferInitialSettings(initialSettings);
Map<String, dynamic> settingsMap =
(params.initialSettings != null ? initialSettings.toMap() : null) ??
params.initialOptions?.toMap() ??
initialSettings.toMap();
Map<String, dynamic> pullToRefreshSettings =
_macosParams.pullToRefreshController?.params.settings.toMap() ??
_macosParams.pullToRefreshController?.params.options.toMap() ??
PullToRefreshSettings(enabled: false).toMap();
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent('id', () => id);
args.putIfAbsent(
'params',
() => <String, dynamic>{
'initialUrlRequest': params.initialUrlRequest?.toMap(),
'initialFile': params.initialFile,
'initialData': params.initialData?.toMap(),
'initialSettings': settingsMap,
'contextMenu': params.contextMenu?.toMap() ?? {},
'windowId': params.windowId,
'initialUserScripts':
params.initialUserScripts?.map((e) => e.toMap()).toList() ??
[],
'pullToRefreshSettings': pullToRefreshSettings,
'initialSize': params.initialSize.toMap()
});
await _sharedChannel.invokeMethod('run', args);
_running = true;
}
void _inferInitialSettings(InAppWebViewSettings settings) {
if (params.shouldOverrideUrlLoading != null &&
settings.useShouldOverrideUrlLoading == null) {
settings.useShouldOverrideUrlLoading = true;
}
if (params.onLoadResource != null && settings.useOnLoadResource == null) {
settings.useOnLoadResource = true;
}
if (params.onDownloadStartRequest != null &&
settings.useOnDownloadStart == null) {
settings.useOnDownloadStart = true;
}
if (params.shouldInterceptAjaxRequest != null &&
settings.useShouldInterceptAjaxRequest == null) {
settings.useShouldInterceptAjaxRequest = true;
}
if (params.shouldInterceptFetchRequest != null &&
settings.useShouldInterceptFetchRequest == null) {
settings.useShouldInterceptFetchRequest = true;
}
if (params.shouldInterceptRequest != null &&
settings.useShouldInterceptRequest == null) {
settings.useShouldInterceptRequest = true;
}
if (params.onRenderProcessGone != null &&
settings.useOnRenderProcessGone == null) {
settings.useOnRenderProcessGone = true;
}
if (params.onNavigationResponse != null &&
settings.useOnNavigationResponse == null) {
settings.useOnNavigationResponse = true;
}
}
@override
bool isRunning() {
return _running;
}
@override
Future<void> setSize(Size size) async {
if (!_running) {
return;
}
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent('size', () => size.toMap());
await channel?.invokeMethod('setSize', args);
}
@override
Future<Size?> getSize() async {
if (!_running) {
return null;
}
Map<String, dynamic> args = <String, dynamic>{};
Map<String, dynamic> sizeMap =
(await channel?.invokeMethod('getSize', args))?.cast<String, dynamic>();
return MapSize.fromMap(sizeMap);
}
@override
Future<void> dispose() async {
if (!_running) {
return;
}
Map<String, dynamic> args = <String, dynamic>{};
await channel?.invokeMethod('dispose', args);
disposeChannel();
_started = false;
_running = false;
_webViewController?.dispose();
_webViewController = null;
_controllerFromPlatform = null;
_macosParams.pullToRefreshController?.dispose();
_macosParams.findInteractionController?.dispose();
}
}
extension InternalHeadlessInAppWebView on WebPlatformHeadlessInAppWebView {
Future<void> internalDispose() async {
_started = false;
_running = false;
}
}

View File

@ -0,0 +1,384 @@
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_inappwebview_platform_interface/flutter_inappwebview_platform_interface.dart';
import '../../web/web_platform_manager.dart';
import 'headless_in_app_webview.dart';
import 'in_app_webview_controller.dart';
/// Object specifying creation parameters for creating a [PlatformInAppWebViewWidget].
///
/// Platform specific implementations can add additional fields by extending
/// this class.
class WebPlatformInAppWebViewWidgetCreationParams
extends PlatformInAppWebViewWidgetCreationParams {
WebPlatformInAppWebViewWidgetCreationParams(
{super.controllerFromPlatform,
super.key,
super.layoutDirection,
super.gestureRecognizers,
super.headlessWebView,
super.keepAlive,
super.preventGestureDelay,
super.windowId,
super.onWebViewCreated,
super.onLoadStart,
super.onLoadStop,
@Deprecated('Use onReceivedError instead') super.onLoadError,
super.onReceivedError,
@Deprecated("Use onReceivedHttpError instead") super.onLoadHttpError,
super.onReceivedHttpError,
super.onProgressChanged,
super.onConsoleMessage,
super.shouldOverrideUrlLoading,
super.onLoadResource,
super.onScrollChanged,
@Deprecated('Use onDownloadStartRequest instead') super.onDownloadStart,
super.onDownloadStartRequest,
@Deprecated('Use onLoadResourceWithCustomScheme instead')
super.onLoadResourceCustomScheme,
super.onLoadResourceWithCustomScheme,
super.onCreateWindow,
super.onCloseWindow,
super.onJsAlert,
super.onJsConfirm,
super.onJsPrompt,
super.onReceivedHttpAuthRequest,
super.onReceivedServerTrustAuthRequest,
super.onReceivedClientCertRequest,
@Deprecated('Use FindInteractionController.onFindResultReceived instead')
super.onFindResultReceived,
super.shouldInterceptAjaxRequest,
super.onAjaxReadyStateChange,
super.onAjaxProgress,
super.shouldInterceptFetchRequest,
super.onUpdateVisitedHistory,
@Deprecated("Use onPrintRequest instead") super.onPrint,
super.onPrintRequest,
super.onLongPressHitTestResult,
super.onEnterFullscreen,
super.onExitFullscreen,
super.onPageCommitVisible,
super.onTitleChanged,
super.onWindowFocus,
super.onWindowBlur,
super.onOverScrolled,
super.onZoomScaleChanged,
@Deprecated('Use onSafeBrowsingHit instead')
super.androidOnSafeBrowsingHit,
super.onSafeBrowsingHit,
@Deprecated('Use onPermissionRequest instead')
super.androidOnPermissionRequest,
super.onPermissionRequest,
@Deprecated('Use onGeolocationPermissionsShowPrompt instead')
super.androidOnGeolocationPermissionsShowPrompt,
super.onGeolocationPermissionsShowPrompt,
@Deprecated('Use onGeolocationPermissionsHidePrompt instead')
super.androidOnGeolocationPermissionsHidePrompt,
super.onGeolocationPermissionsHidePrompt,
@Deprecated('Use shouldInterceptRequest instead')
super.androidShouldInterceptRequest,
super.shouldInterceptRequest,
@Deprecated('Use onRenderProcessGone instead')
super.androidOnRenderProcessGone,
super.onRenderProcessGone,
@Deprecated('Use onRenderProcessResponsive instead')
super.androidOnRenderProcessResponsive,
super.onRenderProcessResponsive,
@Deprecated('Use onRenderProcessUnresponsive instead')
super.androidOnRenderProcessUnresponsive,
super.onRenderProcessUnresponsive,
@Deprecated('Use onFormResubmission instead')
super.androidOnFormResubmission,
super.onFormResubmission,
@Deprecated('Use onZoomScaleChanged instead') super.androidOnScaleChanged,
@Deprecated('Use onReceivedIcon instead') super.androidOnReceivedIcon,
super.onReceivedIcon,
@Deprecated('Use onReceivedTouchIconUrl instead')
super.androidOnReceivedTouchIconUrl,
super.onReceivedTouchIconUrl,
@Deprecated('Use onJsBeforeUnload instead') super.androidOnJsBeforeUnload,
super.onJsBeforeUnload,
@Deprecated('Use onReceivedLoginRequest instead')
super.androidOnReceivedLoginRequest,
super.onReceivedLoginRequest,
super.onPermissionRequestCanceled,
super.onRequestFocus,
@Deprecated('Use onWebContentProcessDidTerminate instead')
super.iosOnWebContentProcessDidTerminate,
super.onWebContentProcessDidTerminate,
@Deprecated(
'Use onDidReceiveServerRedirectForProvisionalNavigation instead')
super.iosOnDidReceiveServerRedirectForProvisionalNavigation,
super.onDidReceiveServerRedirectForProvisionalNavigation,
@Deprecated('Use onNavigationResponse instead')
super.iosOnNavigationResponse,
super.onNavigationResponse,
@Deprecated('Use shouldAllowDeprecatedTLS instead')
super.iosShouldAllowDeprecatedTLS,
super.shouldAllowDeprecatedTLS,
super.onCameraCaptureStateChanged,
super.onMicrophoneCaptureStateChanged,
super.onContentSizeChanged,
super.initialUrlRequest,
super.initialFile,
super.initialData,
@Deprecated('Use initialSettings instead') super.initialOptions,
super.initialSettings,
super.contextMenu,
super.initialUserScripts,
super.pullToRefreshController,
super.findInteractionController});
/// Constructs a [WebPlatformInAppWebViewWidgetCreationParams] using a
/// [PlatformInAppWebViewWidgetCreationParams].
WebPlatformInAppWebViewWidgetCreationParams.fromPlatformInAppWebViewWidgetCreationParams(
PlatformInAppWebViewWidgetCreationParams params)
: this(
controllerFromPlatform: params.controllerFromPlatform,
key: params.key,
layoutDirection: params.layoutDirection,
gestureRecognizers: params.gestureRecognizers,
headlessWebView: params.headlessWebView,
keepAlive: params.keepAlive,
preventGestureDelay: params.preventGestureDelay,
windowId: params.windowId,
onWebViewCreated: params.onWebViewCreated,
onLoadStart: params.onLoadStart,
onLoadStop: params.onLoadStop,
onLoadError: params.onLoadError,
onReceivedError: params.onReceivedError,
onLoadHttpError: params.onLoadHttpError,
onReceivedHttpError: params.onReceivedHttpError,
onProgressChanged: params.onProgressChanged,
onConsoleMessage: params.onConsoleMessage,
shouldOverrideUrlLoading: params.shouldOverrideUrlLoading,
onLoadResource: params.onLoadResource,
onScrollChanged: params.onScrollChanged,
onDownloadStart: params.onDownloadStart,
onDownloadStartRequest: params.onDownloadStartRequest,
onLoadResourceCustomScheme: params.onLoadResourceCustomScheme,
onLoadResourceWithCustomScheme:
params.onLoadResourceWithCustomScheme,
onCreateWindow: params.onCreateWindow,
onCloseWindow: params.onCloseWindow,
onJsAlert: params.onJsAlert,
onJsConfirm: params.onJsConfirm,
onJsPrompt: params.onJsPrompt,
onReceivedHttpAuthRequest: params.onReceivedHttpAuthRequest,
onReceivedServerTrustAuthRequest:
params.onReceivedServerTrustAuthRequest,
onReceivedClientCertRequest: params.onReceivedClientCertRequest,
onFindResultReceived: params.onFindResultReceived,
shouldInterceptAjaxRequest: params.shouldInterceptAjaxRequest,
onAjaxReadyStateChange: params.onAjaxReadyStateChange,
onAjaxProgress: params.onAjaxProgress,
shouldInterceptFetchRequest: params.shouldInterceptFetchRequest,
onUpdateVisitedHistory: params.onUpdateVisitedHistory,
onPrint: params.onPrint,
onPrintRequest: params.onPrintRequest,
onLongPressHitTestResult: params.onLongPressHitTestResult,
onEnterFullscreen: params.onEnterFullscreen,
onExitFullscreen: params.onExitFullscreen,
onPageCommitVisible: params.onPageCommitVisible,
onTitleChanged: params.onTitleChanged,
onWindowFocus: params.onWindowFocus,
onWindowBlur: params.onWindowBlur,
onOverScrolled: params.onOverScrolled,
onZoomScaleChanged: params.onZoomScaleChanged,
androidOnSafeBrowsingHit: params.androidOnSafeBrowsingHit,
onSafeBrowsingHit: params.onSafeBrowsingHit,
androidOnPermissionRequest: params.androidOnPermissionRequest,
onPermissionRequest: params.onPermissionRequest,
androidOnGeolocationPermissionsShowPrompt:
params.androidOnGeolocationPermissionsShowPrompt,
onGeolocationPermissionsShowPrompt:
params.onGeolocationPermissionsShowPrompt,
androidOnGeolocationPermissionsHidePrompt:
params.androidOnGeolocationPermissionsHidePrompt,
onGeolocationPermissionsHidePrompt:
params.onGeolocationPermissionsHidePrompt,
androidShouldInterceptRequest: params.androidShouldInterceptRequest,
shouldInterceptRequest: params.shouldInterceptRequest,
androidOnRenderProcessGone: params.androidOnRenderProcessGone,
onRenderProcessGone: params.onRenderProcessGone,
androidOnRenderProcessResponsive:
params.androidOnRenderProcessResponsive,
onRenderProcessResponsive: params.onRenderProcessResponsive,
androidOnRenderProcessUnresponsive:
params.androidOnRenderProcessUnresponsive,
onRenderProcessUnresponsive: params.onRenderProcessUnresponsive,
androidOnFormResubmission: params.androidOnFormResubmission,
onFormResubmission: params.onFormResubmission,
androidOnScaleChanged: params.androidOnScaleChanged,
androidOnReceivedIcon: params.androidOnReceivedIcon,
onReceivedIcon: params.onReceivedIcon,
androidOnReceivedTouchIconUrl: params.androidOnReceivedTouchIconUrl,
onReceivedTouchIconUrl: params.onReceivedTouchIconUrl,
androidOnJsBeforeUnload: params.androidOnJsBeforeUnload,
onJsBeforeUnload: params.onJsBeforeUnload,
androidOnReceivedLoginRequest: params.androidOnReceivedLoginRequest,
onReceivedLoginRequest: params.onReceivedLoginRequest,
onPermissionRequestCanceled: params.onPermissionRequestCanceled,
onRequestFocus: params.onRequestFocus,
iosOnWebContentProcessDidTerminate:
params.iosOnWebContentProcessDidTerminate,
onWebContentProcessDidTerminate:
params.onWebContentProcessDidTerminate,
iosOnDidReceiveServerRedirectForProvisionalNavigation:
params.iosOnDidReceiveServerRedirectForProvisionalNavigation,
onDidReceiveServerRedirectForProvisionalNavigation:
params.onDidReceiveServerRedirectForProvisionalNavigation,
iosOnNavigationResponse: params.iosOnNavigationResponse,
onNavigationResponse: params.onNavigationResponse,
iosShouldAllowDeprecatedTLS: params.iosShouldAllowDeprecatedTLS,
shouldAllowDeprecatedTLS: params.shouldAllowDeprecatedTLS,
onCameraCaptureStateChanged: params.onCameraCaptureStateChanged,
onMicrophoneCaptureStateChanged:
params.onMicrophoneCaptureStateChanged,
onContentSizeChanged: params.onContentSizeChanged,
initialUrlRequest: params.initialUrlRequest,
initialFile: params.initialFile,
initialData: params.initialData,
initialOptions: params.initialOptions,
initialSettings: params.initialSettings,
contextMenu: params.contextMenu,
initialUserScripts: params.initialUserScripts,
pullToRefreshController: params.pullToRefreshController,
findInteractionController: params.findInteractionController);
}
///{@macro flutter_inappwebview_platform_interface.PlatformInAppWebViewWidget}
class WebPlatformInAppWebViewWidget extends PlatformInAppWebViewWidget {
/// Constructs a [WebPlatformInAppWebViewWidget].
///
///{@macro flutter_inappwebview_platform_interface.PlatformInAppWebViewWidget}
WebPlatformInAppWebViewWidget(PlatformInAppWebViewWidgetCreationParams params)
: super.implementation(
params is WebPlatformInAppWebViewWidgetCreationParams
? params
: WebPlatformInAppWebViewWidgetCreationParams
.fromPlatformInAppWebViewWidgetCreationParams(params),
);
WebPlatformInAppWebViewWidgetCreationParams get _webPlatformParams =>
params as WebPlatformInAppWebViewWidgetCreationParams;
WebPlatformInAppWebViewController? _controller;
WebPlatformHeadlessInAppWebView? get _macosHeadlessInAppWebView =>
_webPlatformParams.headlessWebView as WebPlatformHeadlessInAppWebView?;
@override
Widget build(BuildContext context) {
final initialSettings =
_webPlatformParams.initialSettings ?? InAppWebViewSettings();
_inferInitialSettings(initialSettings);
if ((_webPlatformParams.headlessWebView?.isRunning() ?? false) &&
_webPlatformParams.keepAlive != null) {
final headlessId = _webPlatformParams.headlessWebView?.id;
if (headlessId != null) {
// force keep alive id to match headless webview id
_webPlatformParams.keepAlive?.id = headlessId;
}
}
return HtmlElementView(
viewType: 'com.pichillilorenzo/flutter_inappwebview',
onPlatformViewCreated: (int viewId) {
var webViewHtmlElement = WebPlatformManager.webViews[viewId]!;
webViewHtmlElement.initialSettings = initialSettings;
webViewHtmlElement.initialUrlRequest = _webPlatformParams.initialUrlRequest;
webViewHtmlElement.initialFile = _webPlatformParams.initialFile;
webViewHtmlElement.initialData = _webPlatformParams.initialData;
webViewHtmlElement.headlessWebViewId =
_webPlatformParams.headlessWebView?.isRunning() ?? false
? _webPlatformParams.headlessWebView?.id
: null;
webViewHtmlElement.prepare();
if (webViewHtmlElement.headlessWebViewId == null) {
webViewHtmlElement.makeInitialLoad();
}
_onPlatformViewCreated(viewId);
},
);
}
void _onPlatformViewCreated(int id) {
dynamic viewId = id;
_macosHeadlessInAppWebView?.internalDispose();
_controller = WebPlatformInAppWebViewController(
PlatformInAppWebViewControllerCreationParams(
id: viewId, webviewParams: params));
debugLog(
className: runtimeType.toString(),
id: viewId?.toString(),
debugLoggingSettings:
PlatformInAppWebViewController.debugLoggingSettings,
method: "onWebViewCreated",
args: []);
if (_webPlatformParams.onWebViewCreated != null) {
_webPlatformParams.onWebViewCreated!(
params.controllerFromPlatform?.call(_controller!) ?? _controller!);
}
}
void _inferInitialSettings(InAppWebViewSettings settings) {
if (_webPlatformParams.shouldOverrideUrlLoading != null &&
settings.useShouldOverrideUrlLoading == null) {
settings.useShouldOverrideUrlLoading = true;
}
if (_webPlatformParams.onLoadResource != null &&
settings.useOnLoadResource == null) {
settings.useOnLoadResource = true;
}
if (_webPlatformParams.onDownloadStartRequest != null &&
settings.useOnDownloadStart == null) {
settings.useOnDownloadStart = true;
}
if (_webPlatformParams.shouldInterceptAjaxRequest != null &&
settings.useShouldInterceptAjaxRequest == null) {
settings.useShouldInterceptAjaxRequest = true;
}
if (_webPlatformParams.shouldInterceptFetchRequest != null &&
settings.useShouldInterceptFetchRequest == null) {
settings.useShouldInterceptFetchRequest = true;
}
if (_webPlatformParams.shouldInterceptRequest != null &&
settings.useShouldInterceptRequest == null) {
settings.useShouldInterceptRequest = true;
}
if (_webPlatformParams.onRenderProcessGone != null &&
settings.useOnRenderProcessGone == null) {
settings.useOnRenderProcessGone = true;
}
if (_webPlatformParams.onNavigationResponse != null &&
settings.useOnNavigationResponse == null) {
settings.useOnNavigationResponse = true;
}
}
@override
void dispose() {
dynamic viewId = _controller?.getViewId();
debugLog(
className: runtimeType.toString(),
id: viewId?.toString(),
debugLoggingSettings:
PlatformInAppWebViewController.debugLoggingSettings,
method: "dispose",
args: []);
final isKeepAlive = _webPlatformParams.keepAlive != null;
_controller?.dispose(isKeepAlive: isKeepAlive);
_controller = null;
_webPlatformParams.pullToRefreshController?.dispose(isKeepAlive: isKeepAlive);
_webPlatformParams.findInteractionController?.dispose(isKeepAlive: isKeepAlive);
}
@override
T controllerFromPlatform<T>(PlatformInAppWebViewController controller) {
// unused
throw UnimplementedError();
}
}

View File

@ -0,0 +1,855 @@
import 'dart:convert';
import 'dart:core';
import 'dart:typed_data';
import 'dart:ui';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_inappwebview_platform_interface/flutter_inappwebview_platform_interface.dart';
import '../web_storage/web_storage.dart';
import 'headless_in_app_webview.dart';
import '_static_channel.dart';
/// Object specifying creation parameters for creating a [WebPlatformInAppWebViewController].
///
/// When adding additional fields make sure they can be null or have a default
/// value to avoid breaking changes. See [PlatformInAppWebViewControllerCreationParams] for
/// more information.
@immutable
class WebPlatformInAppWebViewControllerCreationParams
extends PlatformInAppWebViewControllerCreationParams {
/// Creates a new [WebPlatformInAppWebViewControllerCreationParams] instance.
const WebPlatformInAppWebViewControllerCreationParams(
{required super.id, super.webviewParams});
/// Creates a [WebPlatformInAppWebViewControllerCreationParams] instance based on [PlatformInAppWebViewControllerCreationParams].
factory WebPlatformInAppWebViewControllerCreationParams.fromPlatformInAppWebViewControllerCreationParams(
// Recommended placeholder to prevent being broken by platform interface.
// ignore: avoid_unused_constructor_parameters
PlatformInAppWebViewControllerCreationParams params) {
return WebPlatformInAppWebViewControllerCreationParams(
id: params.id, webviewParams: params.webviewParams);
}
}
///Controls a WebView, such as an [InAppWebView] widget instance, a [WebPlatformHeadlessInAppWebView] instance or [WebPlatformInAppBrowser] WebView instance.
///
///If you are using the [InAppWebView] widget, an [InAppWebViewController] instance can be obtained by setting the [InAppWebView.onWebViewCreated]
///callback. Instead, if you are using an [WebPlatformInAppBrowser] instance, you can get it through the [WebPlatformInAppBrowser.webViewController] attribute.
class WebPlatformInAppWebViewController extends PlatformInAppWebViewController
with ChannelController {
// ignore: unused_field
static final MethodChannel _staticChannel = IN_APP_WEBVIEW_STATIC_CHANNEL;
Map<String, ScriptHtmlTagAttributes> _injectedScriptsFromURL = {};
dynamic _controllerFromPlatform;
@override
late WebPlatformWebStorage webStorage;
WebPlatformInAppWebViewController(
PlatformInAppWebViewControllerCreationParams params)
: super.implementation(params is WebPlatformInAppWebViewControllerCreationParams
? params
: WebPlatformInAppWebViewControllerCreationParams
.fromPlatformInAppWebViewControllerCreationParams(params)) {
channel = MethodChannel('com.pichillilorenzo/flutter_inappwebview_$id');
handler = handleMethod;
initMethodCallHandler();
this._init(params);
}
static final WebPlatformInAppWebViewController _staticValue =
WebPlatformInAppWebViewController(
WebPlatformInAppWebViewControllerCreationParams(id: null));
factory WebPlatformInAppWebViewController.static() {
return _staticValue;
}
void _init(PlatformInAppWebViewControllerCreationParams params) {
_controllerFromPlatform =
params.webviewParams?.controllerFromPlatform?.call(this) ?? this;
webStorage = WebPlatformWebStorage(WebPlatformWebStorageCreationParams(
localStorage: WebPlatformLocalStorage.defaultStorage(controller: this),
sessionStorage: WebPlatformSessionStorage.defaultStorage(controller: this)));
}
_debugLog(String method, dynamic args) {
debugLog(
className: this.runtimeType.toString(),
name: "WebView",
id: getViewId().toString(),
debugLoggingSettings:
PlatformInAppWebViewController.debugLoggingSettings,
method: method,
args: args);
}
Future<dynamic> _handleMethod(MethodCall call) async {
if (PlatformInAppWebViewController.debugLoggingSettings.enabled &&
call.method != "onCallJsHandler") {
_debugLog(call.method, call.arguments);
}
switch (call.method) {
case "onLoadStart":
_injectedScriptsFromURL.clear();
if ((webviewParams != null && webviewParams!.onLoadStart != null)) {
String? url = call.arguments["url"];
WebUri? uri = url != null ? WebUri(url) : null;
webviewParams!.onLoadStart!(_controllerFromPlatform, uri);
}
break;
case "onLoadStop":
if ((webviewParams != null && webviewParams!.onLoadStop != null)) {
String? url = call.arguments["url"];
WebUri? uri = url != null ? WebUri(url) : null;
webviewParams!.onLoadStop!(_controllerFromPlatform, uri);
}
break;
case "onConsoleMessage":
if ((webviewParams != null &&
webviewParams!.onConsoleMessage != null)) {
Map<String, dynamic> arguments =
call.arguments.cast<String, dynamic>();
ConsoleMessage consoleMessage = ConsoleMessage.fromMap(arguments)!;
webviewParams!.onConsoleMessage!(
_controllerFromPlatform, consoleMessage);
}
break;
case "onScrollChanged":
if ((webviewParams != null && webviewParams!.onScrollChanged != null)) {
int x = call.arguments["x"];
int y = call.arguments["y"];
webviewParams!.onScrollChanged!(_controllerFromPlatform, x, y);
}
break;
case "onCreateWindow":
if ((webviewParams != null && webviewParams!.onCreateWindow != null)) {
Map<String, dynamic> arguments =
call.arguments.cast<String, dynamic>();
CreateWindowAction createWindowAction =
CreateWindowAction.fromMap(arguments)!;
return await webviewParams!.onCreateWindow!(
_controllerFromPlatform, createWindowAction);
}
break;
case "onTitleChanged":
if ((webviewParams != null && webviewParams!.onTitleChanged != null)) {
String? title = call.arguments["title"];
webviewParams!.onTitleChanged!(_controllerFromPlatform, title);
}
break;
case "onZoomScaleChanged":
if ((webviewParams != null &&
// ignore: deprecated_member_use_from_same_package
(webviewParams!.androidOnScaleChanged != null ||
webviewParams!.onZoomScaleChanged != null))) {
double oldScale = call.arguments["oldScale"];
double newScale = call.arguments["newScale"];
if (webviewParams!.onZoomScaleChanged != null)
webviewParams!.onZoomScaleChanged!(
_controllerFromPlatform, oldScale, newScale);
else {
// ignore: deprecated_member_use_from_same_package
webviewParams!.androidOnScaleChanged!(
_controllerFromPlatform, oldScale, newScale);
}
}
break;
case "onUpdateVisitedHistory":
if ((webviewParams != null &&
webviewParams!.onUpdateVisitedHistory != null)) {
String? url = call.arguments["url"];
bool? isReload = call.arguments["isReload"];
WebUri? uri = url != null ? WebUri(url) : null;
webviewParams!.onUpdateVisitedHistory!(
_controllerFromPlatform, uri, isReload);
}
break;
case "onEnterFullscreen":
if (webviewParams != null && webviewParams!.onEnterFullscreen != null)
webviewParams!.onEnterFullscreen!(_controllerFromPlatform);
break;
case "onExitFullscreen":
if (webviewParams != null && webviewParams!.onExitFullscreen != null)
webviewParams!.onExitFullscreen!(_controllerFromPlatform);
break;
case "onWindowFocus":
if (webviewParams != null && webviewParams!.onWindowFocus != null)
webviewParams!.onWindowFocus!(_controllerFromPlatform);
break;
case "onWindowBlur":
if (webviewParams != null && webviewParams!.onWindowBlur != null)
webviewParams!.onWindowBlur!(_controllerFromPlatform);
break;
case "onPrintRequest":
if ((webviewParams != null &&
(webviewParams!.onPrintRequest != null ||
// ignore: deprecated_member_use_from_same_package
webviewParams!.onPrint != null))) {
String? url = call.arguments["url"];
WebUri? uri = url != null ? WebUri(url) : null;
if (webviewParams!.onPrintRequest != null)
return await webviewParams!.onPrintRequest!(
_controllerFromPlatform, uri, null);
else {
// ignore: deprecated_member_use_from_same_package
webviewParams!.onPrint!(_controllerFromPlatform, uri);
return false;
}
}
break;
case "onInjectedScriptLoaded":
String id = call.arguments[0];
var onLoadCallback = _injectedScriptsFromURL[id]?.onLoad;
if ((webviewParams != null) &&
onLoadCallback != null) {
onLoadCallback();
}
break;
case "onInjectedScriptError":
String id = call.arguments[0];
var onErrorCallback = _injectedScriptsFromURL[id]?.onError;
if ((webviewParams != null) &&
onErrorCallback != null) {
onErrorCallback();
}
break;
default:
throw UnimplementedError("Unimplemented ${call.method} method");
}
return null;
}
@override
Future<WebUri?> getUrl() async {
Map<String, dynamic> args = <String, dynamic>{};
String? url = await channel?.invokeMethod<String?>('getUrl', args);
return url != null ? WebUri(url) : null;
}
@override
Future<String?> getTitle() async {
Map<String, dynamic> args = <String, dynamic>{};
return await channel?.invokeMethod<String?>('getTitle', args);
}
@override
Future<String?> getHtml() async {
String? html;
InAppWebViewSettings? settings = await getSettings();
if (settings != null && settings.javaScriptEnabled == true) {
html = await evaluateJavascript(
source: "window.document.getElementsByTagName('html')[0].outerHTML;");
if (html != null && html.isNotEmpty) return html;
}
var webviewUrl = await getUrl();
if (webviewUrl == null) {
return html;
}
if (webviewUrl.isScheme("file")) {
var assetPathSplitted = webviewUrl.toString().split("/flutter_assets/");
var assetPath = assetPathSplitted[assetPathSplitted.length - 1];
try {
var bytes = await rootBundle.load(assetPath);
html = utf8.decode(bytes.buffer.asUint8List());
} catch (e) {}
}
return html;
}
@override
Future<List<Favicon>> getFavicons() async {
List<Favicon> favicons = [];
var webviewUrl = await getUrl();
if (webviewUrl == null) {
return favicons;
}
String? manifestUrl;
var html = await getHtml();
if (html == null || html.isEmpty) {
return favicons;
}
var assetPathBase;
if (webviewUrl.isScheme("file")) {
var assetPathSplitted = webviewUrl.toString().split("/flutter_assets/");
assetPathBase = assetPathSplitted[0] + "/flutter_assets/";
}
InAppWebViewSettings? settings = await getSettings();
if (settings != null && settings.javaScriptEnabled == true) {
List<Map<dynamic, dynamic>> links = (await evaluateJavascript(source: """
(function() {
var linkNodes = document.head.getElementsByTagName("link");
var links = [];
for (var i = 0; i < linkNodes.length; i++) {
var linkNode = linkNodes[i];
if (linkNode.rel === 'manifest') {
links.push(
{
rel: linkNode.rel,
href: linkNode.href,
sizes: null
}
);
} else if (linkNode.rel != null && linkNode.rel.indexOf('icon') >= 0) {
links.push(
{
rel: linkNode.rel,
href: linkNode.href,
sizes: linkNode.sizes != null && linkNode.sizes.value != "" ? linkNode.sizes.value : null
}
);
}
}
return links;
})();
"""))?.cast<Map<dynamic, dynamic>>() ?? [];
for (var link in links) {
if (link["rel"] == "manifest") {
manifestUrl = link["href"];
if (!_isUrlAbsolute(manifestUrl!)) {
if (manifestUrl.startsWith("/")) {
manifestUrl = manifestUrl.substring(1);
}
manifestUrl = ((assetPathBase == null)
? webviewUrl.scheme + "://" + webviewUrl.host + "/"
: assetPathBase) +
manifestUrl;
}
continue;
}
favicons.addAll(_createFavicons(webviewUrl, assetPathBase, link["href"],
link["rel"], link["sizes"], false));
}
}
return favicons;
}
bool _isUrlAbsolute(String url) {
return url.startsWith("http://") || url.startsWith("https://");
}
List<Favicon> _createFavicons(WebUri url, String? assetPathBase,
String urlIcon, String? rel, String? sizes, bool isManifest) {
List<Favicon> favicons = [];
List<String> urlSplitted = urlIcon.split("/");
if (!_isUrlAbsolute(urlIcon)) {
if (urlIcon.startsWith("/")) {
urlIcon = urlIcon.substring(1);
}
urlIcon = ((assetPathBase == null)
? url.scheme + "://" + url.host + "/"
: assetPathBase) +
urlIcon;
}
if (isManifest) {
rel = (sizes != null)
? urlSplitted[urlSplitted.length - 1]
.replaceFirst("-" + sizes, "")
.split(" ")[0]
.split(".")[0]
: null;
}
if (sizes != null && sizes.isNotEmpty && sizes != "any") {
List<String> sizesSplitted = sizes.split(" ");
for (String size in sizesSplitted) {
int width = int.parse(size.split("x")[0]);
int height = int.parse(size.split("x")[1]);
favicons.add(Favicon(
url: WebUri(urlIcon), rel: rel, width: width, height: height));
}
} else {
favicons.add(
Favicon(url: WebUri(urlIcon), rel: rel, width: null, height: null));
}
return favicons;
}
@override
Future<void> loadUrl(
{required URLRequest urlRequest,
@Deprecated('Use allowingReadAccessTo instead')
Uri? iosAllowingReadAccessTo,
WebUri? allowingReadAccessTo}) async {
assert(urlRequest.url != null && urlRequest.url.toString().isNotEmpty);
assert(
allowingReadAccessTo == null || allowingReadAccessTo.isScheme("file"));
assert(iosAllowingReadAccessTo == null ||
iosAllowingReadAccessTo.isScheme("file"));
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent('urlRequest', () => urlRequest.toMap());
args.putIfAbsent(
'allowingReadAccessTo',
() =>
allowingReadAccessTo?.toString() ??
iosAllowingReadAccessTo?.toString());
await channel?.invokeMethod('loadUrl', args);
}
@override
Future<void> postUrl(
{required WebUri url, required Uint8List postData}) async {
assert(url.toString().isNotEmpty);
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent('url', () => url.toString());
args.putIfAbsent('postData', () => postData);
await channel?.invokeMethod('postUrl', args);
}
@override
Future<void> loadData(
{required String data,
String mimeType = "text/html",
String encoding = "utf8",
WebUri? baseUrl,
@Deprecated('Use historyUrl instead') Uri? androidHistoryUrl,
WebUri? historyUrl,
@Deprecated('Use allowingReadAccessTo instead')
Uri? iosAllowingReadAccessTo,
WebUri? allowingReadAccessTo}) async {
assert(
allowingReadAccessTo == null || allowingReadAccessTo.isScheme("file"));
assert(iosAllowingReadAccessTo == null ||
iosAllowingReadAccessTo.isScheme("file"));
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent('data', () => data);
args.putIfAbsent('mimeType', () => mimeType);
args.putIfAbsent('encoding', () => encoding);
args.putIfAbsent('baseUrl', () => baseUrl?.toString() ?? "about:blank");
args.putIfAbsent(
'historyUrl',
() =>
historyUrl?.toString() ??
androidHistoryUrl?.toString() ??
"about:blank");
args.putIfAbsent(
'allowingReadAccessTo',
() =>
allowingReadAccessTo?.toString() ??
iosAllowingReadAccessTo?.toString());
await channel?.invokeMethod('loadData', args);
}
@override
Future<void> loadFile({required String assetFilePath}) async {
assert(assetFilePath.isNotEmpty);
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent('assetFilePath', () => assetFilePath);
await channel?.invokeMethod('loadFile', args);
}
@override
Future<void> reload() async {
Map<String, dynamic> args = <String, dynamic>{};
await channel?.invokeMethod('reload', args);
}
@override
Future<void> goBack() async {
Map<String, dynamic> args = <String, dynamic>{};
await channel?.invokeMethod('goBack', args);
}
@override
Future<void> goForward() async {
Map<String, dynamic> args = <String, dynamic>{};
await channel?.invokeMethod('goForward', args);
}
@override
Future<void> goBackOrForward({required int steps}) async {
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent('steps', () => steps);
await channel?.invokeMethod('goBackOrForward', args);
}
@override
Future<bool> isLoading() async {
Map<String, dynamic> args = <String, dynamic>{};
return await channel?.invokeMethod<bool>('isLoading', args) ?? false;
}
@override
Future<void> stopLoading() async {
Map<String, dynamic> args = <String, dynamic>{};
await channel?.invokeMethod('stopLoading', args);
}
@override
Future<dynamic> evaluateJavascript(
{required String source, ContentWorld? contentWorld}) async {
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent('source', () => source);
args.putIfAbsent('contentWorld', () => contentWorld?.toMap());
var data = await channel?.invokeMethod('evaluateJavascript', args);
if (data != null) {
try {
// try to json decode the data coming from JavaScript
// otherwise return it as it is.
data = json.decode(data);
} catch (e) {}
}
return data;
}
@override
Future<void> injectJavascriptFileFromUrl(
{required WebUri urlFile,
ScriptHtmlTagAttributes? scriptHtmlTagAttributes}) async {
assert(urlFile.toString().isNotEmpty);
var id = scriptHtmlTagAttributes?.id;
if (scriptHtmlTagAttributes != null && id != null) {
_injectedScriptsFromURL[id] = scriptHtmlTagAttributes;
}
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent('urlFile', () => urlFile.toString());
args.putIfAbsent(
'scriptHtmlTagAttributes', () => scriptHtmlTagAttributes?.toMap());
await channel?.invokeMethod('injectJavascriptFileFromUrl', args);
}
@override
Future<dynamic> injectJavascriptFileFromAsset(
{required String assetFilePath}) async {
String source = await rootBundle.loadString(assetFilePath);
return await evaluateJavascript(source: source);
}
@override
Future<void> injectCSSCode({required String source}) async {
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent('source', () => source);
await channel?.invokeMethod('injectCSSCode', args);
}
@override
Future<void> injectCSSFileFromUrl(
{required WebUri urlFile,
CSSLinkHtmlTagAttributes? cssLinkHtmlTagAttributes}) async {
assert(urlFile.toString().isNotEmpty);
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent('urlFile', () => urlFile.toString());
args.putIfAbsent(
'cssLinkHtmlTagAttributes', () => cssLinkHtmlTagAttributes?.toMap());
await channel?.invokeMethod('injectCSSFileFromUrl', args);
}
@override
Future<void> injectCSSFileFromAsset({required String assetFilePath}) async {
String source = await rootBundle.loadString(assetFilePath);
await injectCSSCode(source: source);
}
@override
@Deprecated('Use setSettings instead')
Future<void> setOptions({required InAppWebViewGroupOptions options}) async {
InAppWebViewSettings settings =
InAppWebViewSettings.fromMap(options.toMap()) ?? InAppWebViewSettings();
await setSettings(settings: settings);
}
@override
@Deprecated('Use getSettings instead')
Future<InAppWebViewGroupOptions?> getOptions() async {
InAppWebViewSettings? settings = await getSettings();
Map<dynamic, dynamic>? options = settings?.toMap();
if (options != null) {
options = options.cast<String, dynamic>();
return InAppWebViewGroupOptions.fromMap(options as Map<String, dynamic>);
}
return null;
}
@override
Future<void> setSettings({required InAppWebViewSettings settings}) async {
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent('settings', () => settings.toMap());
await channel?.invokeMethod('setSettings', args);
}
@override
Future<InAppWebViewSettings?> getSettings() async {
Map<String, dynamic> args = <String, dynamic>{};
Map<dynamic, dynamic>? settings =
await channel?.invokeMethod('getSettings', args);
if (settings != null) {
settings = settings.cast<String, dynamic>();
return InAppWebViewSettings.fromMap(settings as Map<String, dynamic>);
}
return null;
}
@override
@Deprecated("Use tRexRunnerHtml instead")
Future<String> getTRexRunnerHtml() async {
return await tRexRunnerHtml;
}
@override
@Deprecated("Use tRexRunnerCss instead")
Future<String> getTRexRunnerCss() async {
return await tRexRunnerCss;
}
@override
Future<void> scrollTo(
{required int x, required int y, bool animated = false}) async {
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent('x', () => x);
args.putIfAbsent('y', () => y);
args.putIfAbsent('animated', () => animated);
await channel?.invokeMethod('scrollTo', args);
}
@override
Future<void> scrollBy(
{required int x, required int y, bool animated = false}) async {
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent('x', () => x);
args.putIfAbsent('y', () => y);
args.putIfAbsent('animated', () => animated);
await channel?.invokeMethod('scrollBy', args);
}
@override
Future<PlatformPrintJobController?> printCurrentPage(
{PrintJobSettings? settings}) async {
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent("settings", () => settings?.toMap());
await channel?.invokeMethod<String?>('printCurrentPage', args);
return null;
}
@override
Future<int?> getContentHeight() async {
Map<String, dynamic> args = <String, dynamic>{};
var height = await channel?.invokeMethod('getContentHeight', args);
if (height == null || height == 0) {
// try to use javascript
var scrollHeight = await evaluateJavascript(
source: "document.documentElement.scrollHeight;");
if (scrollHeight != null && scrollHeight is num) {
height = scrollHeight.toInt();
}
}
return height;
}
@override
Future<int?> getContentWidth() async {
Map<String, dynamic> args = <String, dynamic>{};
var width = await channel?.invokeMethod('getContentWidth', args);
if (width == null || width == 0) {
// try to use javascript
var scrollHeight = await evaluateJavascript(
source: "document.documentElement.scrollWidth;");
if (scrollHeight != null && scrollHeight is num) {
width = scrollHeight.toInt();
}
}
return width;
}
@override
Future<WebUri?> getOriginalUrl() async {
Map<String, dynamic> args = <String, dynamic>{};
String? url = await channel?.invokeMethod<String?>('getOriginalUrl', args);
return url != null ? WebUri(url) : null;
}
@override
Future<String?> getSelectedText() async {
Map<String, dynamic> args = <String, dynamic>{};
return await channel?.invokeMethod<String?>('getSelectedText', args);
}
@override
Future<List<MetaTag>> getMetaTags() async {
List<MetaTag> metaTags = [];
List<Map<dynamic, dynamic>>? metaTagList =
(await evaluateJavascript(source: """
(function() {
var metaTags = [];
var metaTagNodes = document.head.getElementsByTagName('meta');
for (var i = 0; i < metaTagNodes.length; i++) {
var metaTagNode = metaTagNodes[i];
var otherAttributes = metaTagNode.getAttributeNames();
var nameIndex = otherAttributes.indexOf("name");
if (nameIndex !== -1) otherAttributes.splice(nameIndex, 1);
var contentIndex = otherAttributes.indexOf("content");
if (contentIndex !== -1) otherAttributes.splice(contentIndex, 1);
var attrs = [];
for (var j = 0; j < otherAttributes.length; j++) {
var otherAttribute = otherAttributes[j];
attrs.push(
{
name: otherAttribute,
value: metaTagNode.getAttribute(otherAttribute)
}
);
}
metaTags.push(
{
name: metaTagNode.name,
content: metaTagNode.content,
attrs: attrs
}
);
}
return metaTags;
})();
"""))?.cast<Map<dynamic, dynamic>>();
if (metaTagList == null) {
return metaTags;
}
for (var metaTag in metaTagList) {
var attrs = <MetaTagAttribute>[];
for (var metaTagAttr in metaTag["attrs"]) {
attrs.add(MetaTagAttribute(
name: metaTagAttr["name"], value: metaTagAttr["value"]));
}
metaTags.add(MetaTag(
name: metaTag["name"], content: metaTag["content"], attrs: attrs));
}
return metaTags;
}
@override
Future<Color?> getMetaThemeColor() async {
Color? themeColor;
try {
Map<String, dynamic> args = <String, dynamic>{};
themeColor = UtilColor.fromStringRepresentation(
await channel?.invokeMethod('getMetaThemeColor', args));
return themeColor;
} catch (e) {
// not implemented
}
// try using javascript
var metaTags = await getMetaTags();
MetaTag? metaTagThemeColor;
for (var metaTag in metaTags) {
if (metaTag.name == "theme-color") {
metaTagThemeColor = metaTag;
break;
}
}
if (metaTagThemeColor == null) {
return null;
}
var colorValue = metaTagThemeColor.content;
themeColor = colorValue != null
? UtilColor.fromStringRepresentation(colorValue)
: null;
return themeColor;
}
@override
Future<int?> getScrollX() async {
Map<String, dynamic> args = <String, dynamic>{};
return await channel?.invokeMethod<int?>('getScrollX', args);
}
@override
Future<int?> getScrollY() async {
Map<String, dynamic> args = <String, dynamic>{};
return await channel?.invokeMethod<int?>('getScrollY', args);
}
@override
Future<bool> isSecureContext() async {
Map<String, dynamic> args = <String, dynamic>{};
return await channel?.invokeMethod<bool>('isSecureContext', args) ?? false;
}
@override
Future<bool> canScrollVertically() async {
Map<String, dynamic> args = <String, dynamic>{};
return await channel?.invokeMethod<bool>('canScrollVertically', args) ??
false;
}
@override
Future<bool> canScrollHorizontally() async {
Map<String, dynamic> args = <String, dynamic>{};
return await channel?.invokeMethod<bool>('canScrollHorizontally', args) ??
false;
}
@override
Future<String> get tRexRunnerHtml async => await rootBundle.loadString(
'packages/flutter_inappwebview/assets/t_rex_runner/t-rex.html');
@override
Future<String> get tRexRunnerCss async => await rootBundle.loadString(
'packages/flutter_inappwebview/assets/t_rex_runner/t-rex.css');
@override
Future<String?> getIFrameId() async {
Map<String, dynamic> args = <String, dynamic>{};
return await channel?.invokeMethod<String?>('getIFrameId', args);
}
@override
dynamic getViewId() {
return id;
}
@override
void dispose({bool isKeepAlive = false}) {
disposeChannel(removeMethodCallHandler: true);
webStorage.dispose();
_controllerFromPlatform = null;
_injectedScriptsFromURL.clear();
}
}
extension InternalInAppWebViewController on WebPlatformInAppWebViewController {
get handleMethod => _handleMethod;
}

View File

@ -0,0 +1,3 @@
export 'in_app_webview_controller.dart' hide InternalInAppWebViewController;
export 'in_app_webview.dart';
export 'headless_in_app_webview.dart' hide InternalHeadlessInAppWebView;

View File

@ -0,0 +1,65 @@
import 'package:flutter_inappwebview_platform_interface/flutter_inappwebview_platform_interface.dart';
import 'cookie_manager.dart';
import 'in_app_webview/main.dart';
/// Implementation of [InAppWebViewPlatform] using the Web API.
class WebPlatformInAppWebViewPlatform extends InAppWebViewPlatform {
/// Registers this class as the default instance of [InAppWebViewPlatform].
static void registerWith() {
InAppWebViewPlatform.instance = WebPlatformInAppWebViewPlatform();
}
/// Creates a new [WebPlatformCookieManager].
///
/// This function should only be called by the app-facing package.
/// Look at using [CookieManager] in `flutter_inappwebview` instead.
@override
WebPlatformCookieManager createPlatformCookieManager(
PlatformCookieManagerCreationParams params,
) {
return WebPlatformCookieManager(params);
}
/// Creates a new [WebPlatformInAppWebViewController].
///
/// This function should only be called by the app-facing package.
/// Look at using [InAppWebViewController] in `flutter_inappwebview` instead.
@override
WebPlatformInAppWebViewController createPlatformInAppWebViewController(
PlatformInAppWebViewControllerCreationParams params,
) {
return WebPlatformInAppWebViewController(params);
}
/// Creates a new empty [WebPlatformInAppWebViewController] to access static methods.
///
/// This function should only be called by the app-facing package.
/// Look at using [InAppWebViewController] in `flutter_inappwebview` instead.
@override
WebPlatformInAppWebViewController createPlatformInAppWebViewControllerStatic() {
return WebPlatformInAppWebViewController.static();
}
/// Creates a new [WebPlatformInAppWebViewWidget].
///
/// This function should only be called by the app-facing package.
/// Look at using [InAppWebView] in `flutter_inappwebview` instead.
@override
WebPlatformInAppWebViewWidget createPlatformInAppWebViewWidget(
PlatformInAppWebViewWidgetCreationParams params,
) {
return WebPlatformInAppWebViewWidget(params);
}
/// Creates a new [WebPlatformHeadlessInAppWebView].
///
/// This function should only be called by the app-facing package.
/// Look at using [HeadlessInAppWebView] in `flutter_inappwebview` instead.
@override
WebPlatformHeadlessInAppWebView createPlatformHeadlessInAppWebView(
PlatformHeadlessInAppWebViewCreationParams params,
) {
return WebPlatformHeadlessInAppWebView(params);
}
}

View File

@ -0,0 +1,4 @@
export 'inappwebview_platform.dart';
export 'in_app_webview/main.dart';
export 'web_storage/main.dart';
export 'cookie_manager.dart' hide InternalCookieManager;

View File

@ -0,0 +1,50 @@
import 'package:flutter/services.dart';
///Platform native utilities
class PlatformUtil {
static PlatformUtil? _instance;
static const MethodChannel _channel =
MethodChannel('com.pichillilorenzo/flutter_inappwebview_platformutil');
PlatformUtil._();
///Get [PlatformUtil] instance.
static PlatformUtil instance() {
return (_instance != null) ? _instance! : _init();
}
static PlatformUtil _init() {
_channel.setMethodCallHandler((call) async {
try {
return await _handleMethod(call);
} on Error catch (e) {
print(e);
print(e.stackTrace);
}
});
_instance = PlatformUtil._();
return _instance!;
}
static Future<dynamic> _handleMethod(MethodCall call) async {}
String? _cachedSystemVersion;
///Get current platform system version.
Future<String> getSystemVersion() async {
if (_cachedSystemVersion != null) {
return _cachedSystemVersion!;
}
Map<String, dynamic> args = <String, dynamic>{};
_cachedSystemVersion =
await _channel.invokeMethod('getSystemVersion', args);
return _cachedSystemVersion!;
}
///Get cookie expiration date used by Web platform.
Future<String> getWebCookieExpirationDate({required DateTime date}) async {
Map<String, dynamic> args = <String, dynamic>{};
args.putIfAbsent('date', () => date.millisecondsSinceEpoch);
return await _channel.invokeMethod('getWebCookieExpirationDate', args);
}
}

View File

@ -0,0 +1 @@
export 'web_storage.dart';

View File

@ -0,0 +1,257 @@
import 'dart:convert';
import 'package:flutter_inappwebview_platform_interface/flutter_inappwebview_platform_interface.dart';
import '../in_app_webview/in_app_webview_controller.dart';
/// Object specifying creation parameters for creating a [WebPlatformWebStorage].
///
/// When adding additional fields make sure they can be null or have a default
/// value to avoid breaking changes. See [PlatformWebStorageCreationParams] for
/// more information.
class WebPlatformWebStorageCreationParams extends PlatformWebStorageCreationParams {
/// Creates a new [WebPlatformWebStorageCreationParams] instance.
WebPlatformWebStorageCreationParams(
{required super.localStorage, required super.sessionStorage});
/// Creates a [WebPlatformWebStorageCreationParams] instance based on [PlatformWebStorageCreationParams].
factory WebPlatformWebStorageCreationParams.fromPlatformWebStorageCreationParams(
// Recommended placeholder to prevent being broken by platform interface.
// ignore: avoid_unused_constructor_parameters
PlatformWebStorageCreationParams params) {
return WebPlatformWebStorageCreationParams(
localStorage: params.localStorage,
sessionStorage: params.sessionStorage);
}
}
///{@macro flutter_inappwebview_platform_interface.PlatformWebStorage}
class WebPlatformWebStorage extends PlatformWebStorage {
/// Constructs a [WebPlatformWebStorage].
WebPlatformWebStorage(PlatformWebStorageCreationParams params)
: super.implementation(
params is WebPlatformWebStorageCreationParams
? params
: WebPlatformWebStorageCreationParams
.fromPlatformWebStorageCreationParams(params),
);
@override
PlatformLocalStorage get localStorage => params.localStorage;
@override
PlatformSessionStorage get sessionStorage => params.sessionStorage;
@override
void dispose() {
localStorage.dispose();
sessionStorage.dispose();
}
}
/// Object specifying creation parameters for creating a [WebPlatformStorage].
///
/// When adding additional fields make sure they can be null or have a default
/// value to avoid breaking changes. See [PlatformStorageCreationParams] for
/// more information.
class WebPlatformStorageCreationParams extends PlatformStorageCreationParams {
/// Creates a new [WebPlatformStorageCreationParams] instance.
WebPlatformStorageCreationParams(
{required super.controller, required super.webStorageType});
/// Creates a [WebPlatformStorageCreationParams] instance based on [PlatformStorageCreationParams].
factory WebPlatformStorageCreationParams.fromPlatformStorageCreationParams(
// Recommended placeholder to prevent being broken by platform interface.
// ignore: avoid_unused_constructor_parameters
PlatformStorageCreationParams params) {
return WebPlatformStorageCreationParams(
controller: params.controller, webStorageType: params.webStorageType);
}
}
///{@macro flutter_inappwebview_platform_interface.PlatformStorage}
abstract class WebPlatformStorage implements PlatformStorage {
@override
WebPlatformInAppWebViewController? controller;
@override
Future<int?> length() async {
var result = await controller?.evaluateJavascript(source: """
window.$webStorageType.length;
""");
return result != null ? int.parse(json.decode(result)) : null;
}
@override
Future<void> setItem({required String key, required dynamic value}) async {
var encodedValue = json.encode(value);
await controller?.evaluateJavascript(source: """
window.$webStorageType.setItem("$key", ${value is String ? encodedValue : "JSON.stringify($encodedValue)"});
""");
}
@override
Future<dynamic> getItem({required String key}) async {
var itemValue = await controller?.evaluateJavascript(source: """
window.$webStorageType.getItem("$key");
""");
if (itemValue == null) {
return null;
}
try {
return json.decode(itemValue);
} catch (e) {}
return itemValue;
}
@override
Future<void> removeItem({required String key}) async {
await controller?.evaluateJavascript(source: """
window.$webStorageType.removeItem("$key");
""");
}
@override
Future<List<WebStorageItem>> getItems() async {
var webStorageItems = <WebStorageItem>[];
List<Map<dynamic, dynamic>>? items =
(await controller?.evaluateJavascript(source: """
(function() {
var webStorageItems = [];
for(var i = 0; i < window.$webStorageType.length; i++){
var key = window.$webStorageType.key(i);
webStorageItems.push(
{
key: key,
value: window.$webStorageType.getItem(key)
}
);
}
return webStorageItems;
})();
"""))?.cast<Map<dynamic, dynamic>>();
if (items == null) {
return webStorageItems;
}
for (var item in items) {
webStorageItems
.add(WebStorageItem(key: item["key"], value: item["value"]));
}
return webStorageItems;
}
@override
Future<void> clear() async {
await controller?.evaluateJavascript(source: """
window.$webStorageType.clear();
""");
}
@override
Future<String> key({required int index}) async {
var result = await controller?.evaluateJavascript(source: """
window.$webStorageType.key($index);
""");
return result != null ? json.decode(result) : null;
}
@override
void dispose() {
controller = null;
}
}
/// Object specifying creation parameters for creating a [WebPlatformLocalStorage].
///
/// When adding additional fields make sure they can be null or have a default
/// value to avoid breaking changes. See [PlatformLocalStorageCreationParams] for
/// more information.
class WebPlatformLocalStorageCreationParams
extends PlatformLocalStorageCreationParams {
/// Creates a new [WebPlatformLocalStorageCreationParams] instance.
WebPlatformLocalStorageCreationParams(super.params);
/// Creates a [WebPlatformLocalStorageCreationParams] instance based on [PlatformLocalStorageCreationParams].
factory WebPlatformLocalStorageCreationParams.fromPlatformLocalStorageCreationParams(
// Recommended placeholder to prevent being broken by platform interface.
// ignore: avoid_unused_constructor_parameters
PlatformLocalStorageCreationParams params) {
return WebPlatformLocalStorageCreationParams(params);
}
}
///{@macro flutter_inappwebview_platform_interface.PlatformLocalStorage}
class WebPlatformLocalStorage extends PlatformLocalStorage with WebPlatformStorage {
/// Constructs a [WebPlatformLocalStorage].
WebPlatformLocalStorage(PlatformLocalStorageCreationParams params)
: super.implementation(
params is WebPlatformLocalStorageCreationParams
? params
: WebPlatformLocalStorageCreationParams
.fromPlatformLocalStorageCreationParams(params),
);
/// Default storage
factory WebPlatformLocalStorage.defaultStorage(
{required PlatformInAppWebViewController? controller}) {
return WebPlatformLocalStorage(WebPlatformLocalStorageCreationParams(
PlatformLocalStorageCreationParams(PlatformStorageCreationParams(
controller: controller,
webStorageType: WebStorageType.LOCAL_STORAGE))));
}
@override
WebPlatformInAppWebViewController? get controller =>
params.controller as WebPlatformInAppWebViewController?;
}
/// Object specifying creation parameters for creating a [WebPlatformSessionStorage].
///
/// When adding additional fields make sure they can be null or have a default
/// value to avoid breaking changes. See [PlatformSessionStorageCreationParams] for
/// more information.
class WebPlatformSessionStorageCreationParams
extends PlatformSessionStorageCreationParams {
/// Creates a new [WebPlatformSessionStorageCreationParams] instance.
WebPlatformSessionStorageCreationParams(super.params);
/// Creates a [WebPlatformSessionStorageCreationParams] instance based on [PlatformSessionStorageCreationParams].
factory WebPlatformSessionStorageCreationParams.fromPlatformSessionStorageCreationParams(
// Recommended placeholder to prevent being broken by platform interface.
// ignore: avoid_unused_constructor_parameters
PlatformSessionStorageCreationParams params) {
return WebPlatformSessionStorageCreationParams(params);
}
}
///{@macro flutter_inappwebview_platform_interface.PlatformSessionStorage}
class WebPlatformSessionStorage extends PlatformSessionStorage with WebPlatformStorage {
/// Constructs a [WebPlatformSessionStorage].
WebPlatformSessionStorage(PlatformSessionStorageCreationParams params)
: super.implementation(
params is WebPlatformSessionStorageCreationParams
? params
: WebPlatformSessionStorageCreationParams
.fromPlatformSessionStorageCreationParams(params),
);
/// Default storage
factory WebPlatformSessionStorage.defaultStorage(
{required PlatformInAppWebViewController? controller}) {
return WebPlatformSessionStorage(WebPlatformSessionStorageCreationParams(
PlatformSessionStorageCreationParams(PlatformStorageCreationParams(
controller: controller,
webStorageType: WebStorageType.SESSION_STORAGE))));
}
@override
WebPlatformInAppWebViewController? get controller =>
params.controller as WebPlatformInAppWebViewController?;
}

View File

@ -4,7 +4,7 @@ import 'package:flutter/services.dart';
import 'headless_inappwebview_manager.dart';
import 'in_app_web_view_web_element.dart';
import '../../../flutter_inappwebview_platform_interface/lib/src/util.dart';
import 'package:flutter_inappwebview_platform_interface/flutter_inappwebview_platform_interface.dart';
class HeadlessInAppWebViewWebElement extends ChannelController {
String id;

View File

@ -1,13 +1,11 @@
import 'dart:html';
import 'package:flutter/services.dart';
import 'package:flutter_inappwebview_platform_interface/flutter_inappwebview_platform_interface.dart';
import 'web_platform_manager.dart';
import '../in_app_webview/in_app_webview_settings.dart';
import 'in_app_web_view_web_element.dart';
import 'headless_in_app_web_view_web_element.dart';
import '../types/main.dart';
class HeadlessInAppWebViewManager {
static final Map<String, HeadlessInAppWebViewWebElement?> webViews = {};

View File

@ -2,15 +2,12 @@ import 'dart:async';
import 'dart:typed_data';
import 'dart:ui';
import 'package:flutter/services.dart';
import '../../../flutter_inappwebview_platform_interface/lib/src/web_uri.dart';
import 'package:flutter_inappwebview_platform_interface/flutter_inappwebview_platform_interface.dart';
import 'dart:html';
import 'dart:js' as js;
import 'headless_inappwebview_manager.dart';
import 'web_platform_manager.dart';
import '../in_app_webview/in_app_webview_settings.dart';
import '../types/main.dart';
import '../types/disposable.dart';
class InAppWebViewWebElement implements Disposable {
late dynamic _viewId;
@ -157,6 +154,8 @@ class InAppWebViewWebElement implements Disposable {
break;
case "getContentHeight":
return await getContentHeight();
case "getContentWidth":
return await getContentWidth();
case "getOriginalUrl":
return await getOriginalUrl();
case "getSelectedText":
@ -392,6 +391,10 @@ class InAppWebViewWebElement implements Disposable {
return (_callMethod('getContentHeight') as num?)?.toInt();
}
Future<int?> getContentWidth() async {
return (_callMethod('getContentWidth') as num?)?.toInt();
}
Future<String?> getOriginalUrl() async {
return iframe.src;
}

View File

@ -1,6 +1,6 @@
import 'dart:async';
import 'package:flutter/services.dart';
import '../../../flutter_inappwebview_platform_interface/lib/src/util.dart';
import 'package:flutter_inappwebview_platform_interface/flutter_inappwebview_platform_interface.dart';
import 'dart:js' as js;

View File

@ -1,8 +1,9 @@
import 'dart:async';
import 'dart:ui_web';
import '../src/inappwebview_platform.dart';
import 'headless_inappwebview_manager.dart';
import 'web_platform_manager.dart';
import 'package:flutter_web_plugins/flutter_web_plugins.dart';
import 'shims/dart_ui.dart' as ui;
import 'in_app_web_view_web_element.dart';
import 'platform_util.dart';
@ -11,10 +12,10 @@ import 'package:js/js.dart';
/// Builds an iframe based WebView.
///
/// This is used as the default implementation for `WebView` on web.
class FlutterInAppWebViewWebPlatform {
/// Constructs a new instance of [FlutterInAppWebViewWebPlatform].
FlutterInAppWebViewWebPlatform(Registrar registrar) {
ui.platformViewRegistry.registerViewFactory(
class InAppWebViewFlutterPlugin {
/// Constructs a new instance of [InAppWebViewFlutterPlugin].
InAppWebViewFlutterPlugin(Registrar registrar) {
platformViewRegistry.registerViewFactory(
'com.pichillilorenzo/flutter_inappwebview', (int viewId) {
var webView =
InAppWebViewWebElement(viewId: viewId, messenger: registrar);
@ -24,8 +25,9 @@ class FlutterInAppWebViewWebPlatform {
}
static void registerWith(Registrar registrar) {
WebPlatformInAppWebViewPlatform.registerWith();
// ignore: unused_local_variable
final pluginInstance = FlutterInAppWebViewWebPlatform(registrar);
final pluginInstance = InAppWebViewFlutterPlugin(registrar);
// ignore: unused_local_variable
final platformUtil = PlatformUtil(messenger: registrar);
// ignore: unused_local_variable

View File

@ -0,0 +1,85 @@
name: flutter_inappwebview_web
description: Web implementation of the flutter_inappwebview plugin.
version: 1.0.0
homepage: https://inappwebview.dev/
repository: https://github.com/pichillilorenzo/flutter_inappwebview/tree/master/flutter_inappwebview_web
issue_tracker: https://github.com/pichillilorenzo/flutter_inappwebview/issues
topics:
- html
- webview
- webview-flutter
- inappwebview
- browser
environment:
sdk: ">=2.17.0 <4.0.0"
flutter: ">=3.0.0"
dependencies:
flutter:
sdk: flutter
flutter_web_plugins:
sdk: flutter
js: ^0.6.4
flutter_inappwebview_platform_interface:
path: ../flutter_inappwebview_platform_interface
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^2.0.0
plugin_platform_interface: ^2.0.2
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
# The following section is specific to Flutter packages.
flutter:
# This section identifies this Flutter project as a plugin project.
# The 'pluginClass' specifies the class (in Java, Kotlin, Swift, Objective-C, etc.)
# which should be registered in the plugin registry. This is required for
# using method channels.
# The Android 'package' specifies package in which the registered class is.
# This is required for using method channels on Android.
# The 'ffiPlugin' specifies that native code should be built and bundled.
# This is required for using `dart:ffi`.
# All these are used by the tooling to maintain consistency when
# adding or updating assets for this project.
plugin:
platforms:
web:
pluginClass: InAppWebViewFlutterPlugin
fileName: web/main.dart
assets:
- packages/flutter_inappwebview_web/assets/web/web_support.js
# To add assets to your plugin package, add an assets section, like this:
# assets:
# - images/a_dot_burr.jpeg
# - images/a_dot_ham.jpeg
#
# For details regarding assets in packages, see
# https://flutter.dev/assets-and-images/#from-packages
#
# An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.dev/assets-and-images/#resolution-aware
# To add custom fonts to your plugin package, add a fonts section here,
# in this "flutter" section. Each entry in this list should have a
# "family" key with the font family name, and a "fonts" key with a
# list giving the asset and other descriptors for the font. For
# example:
# fonts:
# - family: Schyler
# fonts:
# - asset: fonts/Schyler-Regular.ttf
# - asset: fonts/Schyler-Italic.ttf
# style: italic
# - family: Trajan Pro
# fonts:
# - asset: fonts/TrajanPro.ttf
# - asset: fonts/TrajanPro_Bold.ttf
# weight: 700
#
# For details regarding fonts in packages, see
# https://flutter.dev/custom-fonts/#from-packages

View File

@ -34,4 +34,3 @@ export 'package:flutter_inappwebview_platform_interface/flutter_inappwebview_pla
MapSize,
MapEdgeInsets;
export 'src/main.dart';
export 'src/web/main_stub.dart' if (dart.library.html) 'src/web/main.dart';

View File

@ -1,4 +0,0 @@
///Stub for web support.
class FlutterInAppWebViewWebPlatform {
static void registerWith(dynamic registrar) {}
}

View File

@ -1 +0,0 @@
export 'dart_ui_fake.dart' if (dart.library.html) 'dart_ui_real.dart';

View File

@ -1,29 +0,0 @@
import 'dart:html' as html;
// Fake interface for the logic that this package needs from (web-only) dart:ui.
// This is conditionally exported so the analyzer sees these methods as available.
// ignore_for_file: avoid_classes_with_only_static_members
// ignore_for_file: camel_case_types
/// Shim for web_ui engine.PlatformViewRegistry
/// https://github.com/flutter/engine/blob/master/lib/web_ui/lib/ui.dart#L62
class platformViewRegistry {
/// Shim for registerViewFactory
/// https://github.com/flutter/engine/blob/master/lib/web_ui/lib/ui.dart#L72
static bool registerViewFactory(
String viewTypeId, html.Element Function(int viewId) viewFactory) {
return false;
}
}
/// Shim for web_ui engine.AssetManager.
/// https://github.com/flutter/engine/blob/master/lib/web_ui/lib/src/engine/assets.dart#L12
class webOnlyAssetManager {
/// Shim for getAssetUrl.
/// https://github.com/flutter/engine/blob/master/lib/web_ui/lib/src/engine/assets.dart#L45
static String getAssetUrl(String asset) => '';
}
/// Signature of callbacks that have no arguments and return no data.
typedef VoidCallback = void Function();

View File

@ -1 +0,0 @@
export 'dart:ui';

View File

@ -18,9 +18,6 @@ environment:
dependencies:
flutter:
sdk: flutter
flutter_web_plugins:
sdk: flutter
js: ^0.6.4
flutter_inappwebview_platform_interface:
path: flutter_inappwebview_platform_interface
flutter_inappwebview_android:
@ -29,6 +26,8 @@ dependencies:
path: flutter_inappwebview_ios
flutter_inappwebview_macos:
path: flutter_inappwebview_macos
flutter_inappwebview_web:
path: flutter_inappwebview_web
dev_dependencies:
flutter_test:
@ -54,13 +53,11 @@ flutter:
macos:
default_package: flutter_inappwebview_macos
web:
pluginClass: FlutterInAppWebViewWebPlatform
fileName: flutter_inappwebview.dart
default_package: flutter_inappwebview_web
assets:
- packages/flutter_inappwebview/assets/t_rex_runner/t-rex.html
- packages/flutter_inappwebview/assets/t_rex_runner/t-rex.css
- packages/flutter_inappwebview/assets/web/web_support.js
# To add assets to your plugin package, add an assets section, like this:
# assets:
# - images/a_dot_burr.jpeg