Inline WebView
-
+
Cover is a one-page template for building simple and beautiful home pages. Download, edit the text, and add your own fullscreen background photo to make it your own.
Learn more
@@ -33,7 +33,9 @@
diff --git a/example/ios/Runner.xcodeproj/project.pbxproj b/example/ios/Runner.xcodeproj/project.pbxproj
index 1525743a..ae60819b 100644
--- a/example/ios/Runner.xcodeproj/project.pbxproj
+++ b/example/ios/Runner.xcodeproj/project.pbxproj
@@ -12,6 +12,7 @@
3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; };
3B80C3941E831B6300D905FE /* App.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 3B80C3931E831B6300D905FE /* App.framework */; };
3B80C3951E831B6300D905FE /* App.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 3B80C3931E831B6300D905FE /* App.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };
+ 61FF730023634CA10069C557 /* libsqlite3.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = 61FF72FF23634CA10069C557 /* libsqlite3.tbd */; };
74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; };
9705A1C61CF904A100538489 /* Flutter.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 9740EEBA1CF902C7004384FC /* Flutter.framework */; };
9705A1C71CF904A300538489 /* Flutter.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 9740EEBA1CF902C7004384FC /* Flutter.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };
@@ -40,6 +41,8 @@
1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; };
3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; };
3B80C3931E831B6300D905FE /* App.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = App.framework; path = Flutter/App.framework; sourceTree = ""; };
+ 61FF72FF23634CA10069C557 /* libsqlite3.tbd */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.text-based-dylib-definition"; name = libsqlite3.tbd; path = usr/lib/libsqlite3.tbd; sourceTree = SDKROOT; };
+ 61FF730123634DD10069C557 /* flutter_downloader.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; path = flutter_downloader.framework; sourceTree = BUILT_PRODUCTS_DIR; };
74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; };
74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; };
7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; };
@@ -61,6 +64,7 @@
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
+ 61FF730023634CA10069C557 /* libsqlite3.tbd in Frameworks */,
9705A1C61CF904A100538489 /* Flutter.framework in Frameworks */,
3B80C3941E831B6300D905FE /* App.framework in Frameworks */,
25A517508F43E58C47090625 /* Pods_Runner.framework in Frameworks */,
@@ -73,6 +77,8 @@
50BAF1DF19E018DDF2B149B9 /* Frameworks */ = {
isa = PBXGroup;
children = (
+ 61FF730123634DD10069C557 /* flutter_downloader.framework */,
+ 61FF72FF23634CA10069C557 /* libsqlite3.tbd */,
E8D91E403808A7540F18B75D /* Pods_Runner.framework */,
);
name = Frameworks;
@@ -180,6 +186,11 @@
CreatedOnToolsVersion = 7.3.1;
DevelopmentTeam = PFP8UV45Y6;
LastSwiftMigration = 1020;
+ SystemCapabilities = {
+ com.apple.BackgroundModes = {
+ enabled = 1;
+ };
+ };
};
};
};
@@ -257,12 +268,16 @@
inputPaths = (
"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh",
"${PODS_ROOT}/../.symlinks/flutter/ios-release/Flutter.framework",
+ "${BUILT_PRODUCTS_DIR}/flutter_downloader/flutter_downloader.framework",
"${BUILT_PRODUCTS_DIR}/flutter_inappbrowser/flutter_inappbrowser.framework",
+ "${BUILT_PRODUCTS_DIR}/path_provider/path_provider.framework",
);
name = "[CP] Embed Pods Frameworks";
outputPaths = (
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Flutter.framework",
+ "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/flutter_downloader.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/flutter_inappbrowser.framework",
+ "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/path_provider.framework",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
diff --git a/example/ios/Runner/AppDelegate.swift b/example/ios/Runner/AppDelegate.swift
index 70693e4a..79dc7b49 100755
--- a/example/ios/Runner/AppDelegate.swift
+++ b/example/ios/Runner/AppDelegate.swift
@@ -1,13 +1,18 @@
import UIKit
import Flutter
+import flutter_downloader
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
+
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
GeneratedPluginRegistrant.register(with: self)
+ FlutterDownloaderPlugin.setPluginRegistrantCallback({(registry: FlutterPluginRegistry) in
+
+ })
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
diff --git a/example/ios/Runner/Info.plist b/example/ios/Runner/Info.plist
index ca37f3f9..f4b3e9b3 100755
--- a/example/ios/Runner/Info.plist
+++ b/example/ios/Runner/Info.plist
@@ -4,11 +4,6 @@
- NSAppTransportSecurity
-
- NSAllowsLocalNetworking
-
-
CFBundleDevelopmentRegion
en
CFBundleExecutable
@@ -29,6 +24,16 @@
$(FLUTTER_BUILD_NUMBER)
LSRequiresIPhoneOS
+ NSAppTransportSecurity
+
+ NSAllowsLocalNetworking
+
+
+ UIBackgroundModes
+
+ fetch
+ remote-notification
+
UILaunchStoryboardName
LaunchScreen
UIMainStoryboardFile
@@ -46,9 +51,9 @@
UIInterfaceOrientationLandscapeLeft
UIInterfaceOrientationLandscapeRight
- io.flutter.embedded_views_preview
-
UIViewControllerBasedStatusBarAppearance
+ io.flutter.embedded_views_preview
+
diff --git a/example/ios/Runner/Runner-Bridging-Header.h b/example/ios/Runner/Runner-Bridging-Header.h
index 7335fdf9..308a2a56 100755
--- a/example/ios/Runner/Runner-Bridging-Header.h
+++ b/example/ios/Runner/Runner-Bridging-Header.h
@@ -1 +1 @@
-#import "GeneratedPluginRegistrant.h"
\ No newline at end of file
+#import "GeneratedPluginRegistrant.h"
diff --git a/example/lib/inline_example.screen.dart b/example/lib/inline_example.screen.dart
index 445126d7..3ddfba3a 100644
--- a/example/lib/inline_example.screen.dart
+++ b/example/lib/inline_example.screen.dart
@@ -1,5 +1,12 @@
+import 'dart:convert';
+import 'dart:io';
+
import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
import 'package:flutter_inappbrowser/flutter_inappbrowser.dart';
+import 'package:flutter_downloader/flutter_downloader.dart';
+import 'package:path_provider/path_provider.dart';
+import 'package:flutter/services.dart' show rootBundle;
class InlineExampleScreen extends StatefulWidget {
@override
@@ -44,7 +51,7 @@ class _InlineExampleScreenState extends State {
child: Text(
"CURRENT URL\n${(url.length > 50) ? url.substring(0, 50) + "..." : url}"),
),
- Container(
+ Container(
padding: EdgeInsets.all(10.0),
child: progress < 1.0 ? LinearProgressIndicator(value: progress) : Container()
),
@@ -55,13 +62,15 @@ class _InlineExampleScreenState extends State {
BoxDecoration(border: Border.all(color: Colors.blueAccent)),
child: InAppWebView(
//initialUrl: "https://www.youtube.com/embed/M7lc1UVf-VE?playsinline=1",
- initialUrl: "https://flutter.dev/",
- //initialFile: "assets/index.html",
+ //initialUrl: "https://flutter.dev/",
+ initialFile: "assets/index.html",
initialHeaders: {},
initialOptions: {
//"mediaPlaybackRequiresUserGesture": false,
//"allowsInlineMediaPlayback": true,
- //"useShouldOverrideUrlLoading": true,
+ "useShouldOverrideUrlLoading": true,
+ "useOnTargetBlank": true,
+ "resourceCustomSchemes": ["my-special-custom-scheme"],
//"useOnLoadResource": true
},
onWebViewCreated: (InAppWebViewController controller) {
@@ -104,13 +113,34 @@ class _InlineExampleScreenState extends State {
response.url);
},
onConsoleMessage: (InAppWebViewController controller, ConsoleMessage consoleMessage) {
- print("""
- console output:
- sourceURL: ${consoleMessage.sourceURL}
- lineNumber: ${consoleMessage.lineNumber}
- message: ${consoleMessage.message}
- messageLevel: ${consoleMessage.messageLevel}
- """);
+// print("""
+// console output:
+// sourceURL: ${consoleMessage.sourceURL}
+// lineNumber: ${consoleMessage.lineNumber}
+// message: ${consoleMessage.message}
+// messageLevel: ${consoleMessage.messageLevel}
+// """);
+ },
+ onDownloadStart: (InAppWebViewController controller, String url) async {
+ final taskId = await FlutterDownloader.enqueue(
+ url: url,
+ savedDir: await _findLocalPath(),
+ showNotification: true, // show download progress in status bar (for Android)
+ openFileFromNotification: true, // click on notification to open downloaded file (for Android)
+ );
+ },
+ onLoadResourceCustomScheme: (InAppWebViewController controller, String scheme, String url) async {
+ if (scheme == "my-special-custom-scheme") {
+ var bytes = await rootBundle.load("assets/" + url.replaceFirst("my-special-custom-scheme://", "", 0));
+ var asBase64 = base64.encode(bytes.buffer.asUint8List());
+ var response = new CustomSchemeResponse(asBase64, "image/svg+xml", "utf-8");
+ return response;
+ }
+ return null;
+ },
+ onTargetBlank: (InAppWebViewController controller, String url) {
+ print("target _blank: " + url);
+ controller.loadUrl(url);
},
),
),
@@ -146,4 +176,11 @@ class _InlineExampleScreenState extends State {
),
]));
}
+
+ Future _findLocalPath() async {
+ final directory = Platform.isAndroid
+ ? await getExternalStorageDirectory()
+ : await getApplicationDocumentsDirectory();
+ return directory.path;
+ }
}
diff --git a/example/lib/main.dart b/example/lib/main.dart
index 515d300a..64977b02 100644
--- a/example/lib/main.dart
+++ b/example/lib/main.dart
@@ -4,11 +4,13 @@ import 'package:flutter_inappbrowser/flutter_inappbrowser.dart';
import 'package:flutter_inappbrowser_example/chrome_safari_example.screen.dart';
import 'package:flutter_inappbrowser_example/inline_example.screen.dart';
import 'package:flutter_inappbrowser_example/webview_example.screen.dart';
+import 'package:flutter_downloader/flutter_downloader.dart';
// InAppLocalhostServer localhostServer = new InAppLocalhostServer();
Future main() async {
// await localhostServer.start();
+ await FlutterDownloader.initialize();
runApp(new MyApp());
}
diff --git a/example/lib/webview_example.screen.dart b/example/lib/webview_example.screen.dart
index 43dfbe01..5a10c954 100644
--- a/example/lib/webview_example.screen.dart
+++ b/example/lib/webview_example.screen.dart
@@ -66,7 +66,16 @@ class MyInappBrowser extends InAppBrowser {
messageLevel: ${consoleMessage.messageLevel}
""");
}
-
+
+ @override
+ void onDownloadStart(String url) {
+ print("Download of " + url);
+ }
+
+ @override
+ Future onLoadResourceCustomScheme(String scheme, String url) async {
+ print("custom scheme: " + scheme);
+ }
}
class WebviewExampleScreen extends StatefulWidget {
@@ -87,7 +96,7 @@ class _WebviewExampleScreenState extends State {
child: new RaisedButton(
onPressed: () {
widget.browser.open(
- url: "https://google.com",
+ url: "https://www.google.com/",
options: {
"useShouldOverrideUrlLoading": true,
"useOnLoadResource": true,
diff --git a/example/pubspec.yaml b/example/pubspec.yaml
index a92c55d8..5e2bd8c0 100644
--- a/example/pubspec.yaml
+++ b/example/pubspec.yaml
@@ -19,6 +19,8 @@ dependencies:
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^0.1.2
+ flutter_downloader: ^1.3.2
+ path_provider: ^1.4.0
dev_dependencies:
flutter_test:
diff --git a/flutter_inappbrowser.iml b/flutter_inappbrowser.iml
index 456cf06e..187fcb84 100644
--- a/flutter_inappbrowser.iml
+++ b/flutter_inappbrowser.iml
@@ -21,7 +21,6 @@
-
diff --git a/ios/Classes/CustomeSchemeHandler.swift b/ios/Classes/CustomeSchemeHandler.swift
new file mode 100644
index 00000000..ae57d26d
--- /dev/null
+++ b/ios/Classes/CustomeSchemeHandler.swift
@@ -0,0 +1,40 @@
+//
+// CustomeSchemeHandler.swift
+// flutter_downloader
+//
+// Created by Lorenzo Pichilli on 25/10/2019.
+//
+
+import Flutter
+import Foundation
+import WebKit
+
+@available(iOS 11.0, *)
+class CustomeSchemeHandler : NSObject, WKURLSchemeHandler {
+ func webView(_ webView: WKWebView, start urlSchemeTask: WKURLSchemeTask) {
+ let inAppWebView = webView as! InAppWebView
+ if let url = urlSchemeTask.request.url, let scheme = url.scheme {
+ inAppWebView.onLoadResourceCustomScheme(scheme: scheme, url: url.absoluteString, result: {(result) -> Void in
+ if result is FlutterError {
+ print((result as! FlutterError).message)
+ }
+ else if (result as? NSObject) == FlutterMethodNotImplemented {}
+ else {
+ let json: [String: String]
+ if let r = result {
+ json = r as! [String: String]
+ let urlResponse = URLResponse(url: url, mimeType: json["content-type"], expectedContentLength: -1, textEncodingName: json["content-encoding"])
+ let data = Data(base64Encoded: json["base64data"]!, options: .ignoreUnknownCharacters)
+ urlSchemeTask.didReceive(urlResponse)
+ urlSchemeTask.didReceive(data!)
+ urlSchemeTask.didFinish()
+ }
+ }
+ })
+ }
+ }
+
+ func webView(_ webView: WKWebView, stop urlSchemeTask: WKURLSchemeTask) {
+
+ }
+}
diff --git a/ios/Classes/FlutterWebViewFactory.swift b/ios/Classes/FlutterWebViewFactory.swift
index e778883c..d910e57c 100755
--- a/ios/Classes/FlutterWebViewFactory.swift
+++ b/ios/Classes/FlutterWebViewFactory.swift
@@ -9,7 +9,7 @@ import Flutter
import Foundation
public class FlutterWebViewFactory: NSObject, FlutterPlatformViewFactory {
- private weak var registrar: FlutterPluginRegistrar?
+ private var registrar: FlutterPluginRegistrar?
init(registrar: FlutterPluginRegistrar?) {
super.init()
@@ -22,7 +22,10 @@ public class FlutterWebViewFactory: NSObject, FlutterPlatformViewFactory {
public func create(withFrame frame: CGRect, viewIdentifier viewId: Int64, arguments args: Any?) -> FlutterPlatformView {
let arguments = args as? NSDictionary
- let webviewController = FlutterWebViewController(registrar: registrar!, withFrame: frame, viewIdentifier: viewId, arguments: arguments!)
+ let webviewController = FlutterWebViewController(registrar: registrar!,
+ withFrame: frame,
+ viewIdentifier: viewId,
+ arguments: arguments!)
return webviewController
}
}
diff --git a/ios/Classes/InAppWebView.swift b/ios/Classes/InAppWebView.swift
index 3ab4a3c4..a016b47a 100755
--- a/ios/Classes/InAppWebView.swift
+++ b/ios/Classes/InAppWebView.swift
@@ -82,7 +82,7 @@ window.\(JAVASCRIPT_BRIDGE_NAME).callHandler = function() {
let platformReadyJS = "window.dispatchEvent(new Event('flutterInAppBrowserPlatformReady'));";
-public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavigationDelegate, WKScriptMessageHandler, URLSessionDownloadDelegate {
+public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavigationDelegate, WKScriptMessageHandler {
var IABController: InAppBrowserWebViewController?
var IAWController: FlutterWebViewController?
@@ -206,6 +206,16 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi
configuration.allowsInlineMediaPlayback = (options?.allowsInlineMediaPlayback)!
+ if #available(iOS 11.0, *) {
+ if let schemes = options?.resourceCustomSchemes {
+ for scheme in schemes {
+ configuration.setURLSchemeHandler(CustomeSchemeHandler(), forURLScheme: scheme)
+ }
+ }
+ } else {
+ // Fallback on earlier versions
+ }
+
return configuration
}
@@ -296,7 +306,7 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi
}
public func loadFile(url: String, headers: [String: String]?) throws {
- let key = SwiftFlutterPlugin.registrar!.lookupKey(forAsset: url)
+ let key = SwiftFlutterPlugin.instance!.registrar!.lookupKey(forAsset: url)
let assetURL = Bundle.main.url(forResource: key, withExtension: nil)
if assetURL == nil {
throw NSError(domain: url + " asset file cannot be found!", code: 0)
@@ -524,7 +534,9 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi
public func webView(_ webView: WKWebView,
decidePolicyFor navigationAction: WKNavigationAction,
decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
-
+
+ let app = UIApplication.shared
+
if let url = navigationAction.request.url {
if url.absoluteString != url.absoluteString && (options?.useOnLoadResource)! {
WKNavigationMap[url.absoluteString] = [
@@ -533,12 +545,32 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi
]
}
+ // Handle target="_blank"
+ if navigationAction.targetFrame == nil && (options?.useOnTargetBlank)! {
+ onTargetBlank(url: url)
+ decisionHandler(.cancel)
+ return
+ }
+
if navigationAction.navigationType == .linkActivated && (options?.useShouldOverrideUrlLoading)! {
shouldOverrideUrlLoading(url: url)
decisionHandler(.cancel)
return
}
+ // Handle phone and email links
+ if url.scheme == "tel" || url.scheme == "mailto" {
+ if app.canOpenURL(url) {
+ if #available(iOS 10.0, *) {
+ app.open(url)
+ } else {
+ app.openURL(url)
+ }
+ }
+ decisionHandler(.cancel)
+ return
+ }
+
if navigationAction.navigationType == .linkActivated || navigationAction.navigationType == .backForward {
currentURL = url
if IABController != nil {
@@ -568,9 +600,7 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi
let mimeType = navigationResponse.response.mimeType
if let url = navigationResponse.response.url {
if mimeType != nil && !mimeType!.starts(with: "text/") {
- Downloader.load(delegate: self, url: url, completion: { (destinationUrl: URL) in
- print(destinationUrl)
- })
+ onDownloadStart(url: url.absoluteString)
decisionHandler(.cancel)
return
}
@@ -579,40 +609,6 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi
decisionHandler(.allow)
}
- // func webView(_ webView: WKWebView,
- // decidePolicyFor navigationResponse: WKNavigationResponse,
- // decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
- // let mimeType = navigationResponse.response.mimeType
- // if mimeType != nil && !mimeType!.starts(with: "text/") {
- // download(url: webView.url)
- // decisionHandler(.cancel)
- // return
- // }
- // decisionHandler(.allow)
- // }
- //
- // func download (url: URL?) {
- // let filename = url?.lastPathComponent
- //
- // let destination: DownloadRequest.DownloadFileDestination = { _, _ in
- // let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
- // let fileURL = documentsURL.appendingPathComponent(filename!)
- //
- // return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
- // }
- //
- // Alamofire.download((url?.absoluteString)!, to: destination).downloadProgress { progress in
- // print("Download Progress: \(progress.fractionCompleted)")
- // }.response { response in
- // if response.error == nil, let path = response.destinationURL?.path {
- // UIAlertView(title: nil, message: "File saved to " + path, delegate: nil, cancelButtonTitle: nil).show()
- // }
- // else {
- // UIAlertView(title: nil, message: "Cannot save " + filename!, delegate: nil, cancelButtonTitle: nil).show()
- // }
- // }
- // }
-
public func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
self.startPageTime = currentTimeInMilliSeconds()
onLoadStart(url: (currentURL?.absoluteString)!)
@@ -667,20 +663,6 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi
setNeedsLayout()
}
- public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
-
- }
-
- public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
- guard
- let url = downloadTask.originalRequest?.url
- else {
- return
- }
- let progress = Float(totalBytesWritten) / Float(totalBytesExpectedToWrite)
- let totalSize = ByteCountFormatter.string(fromByteCount: totalBytesExpectedToWrite, countStyle: .file)
- }
-
public func onLoadStart(url: String) {
var arguments: [String: Any] = ["url": url]
if IABController != nil {
@@ -761,6 +743,26 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi
}
}
+ public func onDownloadStart(url: String) {
+ var arguments: [String: Any] = ["url": url]
+ if IABController != nil {
+ arguments["uuid"] = IABController!.uuid
+ }
+ if let channel = getChannel() {
+ channel.invokeMethod("onDownloadStart", arguments: arguments)
+ }
+ }
+
+ public func onLoadResourceCustomScheme(scheme: String, url: String, result: FlutterResult?) {
+ var arguments: [String: Any] = ["scheme": scheme, "url": url]
+ if IABController != nil {
+ arguments["uuid"] = IABController!.uuid
+ }
+ if let channel = getChannel() {
+ channel.invokeMethod("onLoadResourceCustomScheme", arguments: arguments, result: result)
+ }
+ }
+
public func shouldOverrideUrlLoading(url: URL) {
var arguments: [String: Any] = ["url": url.absoluteString]
if IABController != nil {
@@ -771,6 +773,16 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi
}
}
+ public func onTargetBlank(url: URL) {
+ var arguments: [String: Any] = ["url": url.absoluteString]
+ if IABController != nil {
+ arguments["uuid"] = IABController!.uuid
+ }
+ if let channel = getChannel() {
+ channel.invokeMethod("onTargetBlank", arguments: arguments)
+ }
+ }
+
public func onConsoleMessage(sourceURL: String, lineNumber: Int, message: String, messageLevel: String) {
var arguments: [String: Any] = ["sourceURL": sourceURL, "lineNumber": lineNumber, "message": message, "messageLevel": messageLevel]
if IABController != nil {
@@ -870,50 +882,6 @@ public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate, WKNavi
}
private func getChannel() -> FlutterMethodChannel? {
- return (IABController != nil) ? SwiftFlutterPlugin.channel! : ((IAWController != nil) ? IAWController!.channel! : nil);
- }
-}
-
-class Downloader {
- class func load(delegate: URLSessionDelegate, url: URL, completion: @escaping (_ destinationUrl: URL) -> ()) {
- let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last as! URL
- let destinationUrl = documentsUrl.appendingPathComponent(url.lastPathComponent)
-
- if FileManager.default.fileExists(atPath: destinationUrl.path) {
- print("file already exists [\(destinationUrl.path)]")
- //completion(path: destinationUrl.path!, error:nil)
- return
- }
-
- let sessionConfig = URLSessionConfiguration.default
- let session = URLSession(configuration: sessionConfig, delegate: delegate, delegateQueue: nil)
- var request = URLRequest(url: url)
- request.httpMethod = "GET"
-
- let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in
- if let tempLocalUrl = tempLocalUrl, error == nil {
- // Success
- if let statusCode = (response as? HTTPURLResponse)?.statusCode {
- if statusCode == 200 {
- do {
- try FileManager.default.moveItem(at: tempLocalUrl, to: destinationUrl)
- completion(destinationUrl)
- } catch (let writeError) {
- print("error writing file \(destinationUrl) : \(writeError)")
- //completion(path: destinationUrl.path!, error:nil)
- }
- } else {
- //completion(path: destinationUrl.path!, error:nil)
- }
- } else {
- //completion(path: destinationUrl.path!, error:nil)
- }
-
- } else {
- print("Failure: %@", error?.localizedDescription);
- //completion(path: destinationUrl.path!, error:nil)
- }
- }
- task.resume()
+ return (IABController != nil) ? SwiftFlutterPlugin.instance!.channel! : ((IAWController != nil) ? IAWController!.channel! : nil);
}
}
diff --git a/ios/Classes/InAppWebViewOptions.swift b/ios/Classes/InAppWebViewOptions.swift
index 788dd545..996350c4 100755
--- a/ios/Classes/InAppWebViewOptions.swift
+++ b/ios/Classes/InAppWebViewOptions.swift
@@ -12,6 +12,7 @@ public class InAppWebViewOptions: Options {
var useShouldOverrideUrlLoading = false
var useOnLoadResource = false
+ var useOnTargetBlank = false
var clearCache = false
var userAgent = ""
var javaScriptEnabled = true
@@ -19,6 +20,7 @@ public class InAppWebViewOptions: Options {
var mediaPlaybackRequiresUserGesture = true
var verticalScrollBarEnabled = true
var horizontalScrollBarEnabled = true
+ var resourceCustomSchemes: [String] = []
var disallowOverScroll = false
var enableViewportScale = false
diff --git a/ios/Classes/SwiftFlutterPlugin.swift b/ios/Classes/SwiftFlutterPlugin.swift
index 50021edf..16cdf474 100755
--- a/ios/Classes/SwiftFlutterPlugin.swift
+++ b/ios/Classes/SwiftFlutterPlugin.swift
@@ -35,8 +35,9 @@ extension Dictionary where Key: ExpressibleByStringLiteral {
public class SwiftFlutterPlugin: NSObject, FlutterPlugin {
- static var registrar: FlutterPluginRegistrar?
- static var channel: FlutterMethodChannel?
+ static var instance: SwiftFlutterPlugin?
+ var registrar: FlutterPluginRegistrar?
+ var channel: FlutterMethodChannel?
var webViewControllers: [String: InAppBrowserWebViewController?] = [:]
var safariViewControllers: [String: Any?] = [:]
@@ -45,17 +46,14 @@ public class SwiftFlutterPlugin: NSObject, FlutterPlugin {
private var previousStatusBarStyle = -1
public init(with registrar: FlutterPluginRegistrar) {
- SwiftFlutterPlugin.channel = FlutterMethodChannel(name: "com.pichillilorenzo/flutter_inappbrowser", binaryMessenger: registrar.messenger())
+ super.init()
+ self.registrar = registrar
+ self.channel = FlutterMethodChannel(name: "com.pichillilorenzo/flutter_inappbrowser", binaryMessenger: registrar.messenger())
+ registrar.addMethodCallDelegate(self, channel: channel!)
}
public static func register(with registrar: FlutterPluginRegistrar) {
-
- SwiftFlutterPlugin.registrar = registrar
-
- let channel = FlutterMethodChannel(name: "com.pichillilorenzo/flutter_inappbrowser", binaryMessenger: registrar.messenger())
- let instance = SwiftFlutterPlugin(with: registrar)
- registrar.addMethodCallDelegate(instance, channel: channel)
-
+ SwiftFlutterPlugin.instance = SwiftFlutterPlugin(with: registrar)
registrar.register(FlutterWebViewFactory(registrar: registrar) as FlutterPlatformViewFactory, withId: "com.pichillilorenzo/flutter_inappwebview")
if #available(iOS 11.0, *) {
@@ -288,7 +286,7 @@ public class SwiftFlutterPlugin: NSObject, FlutterPlugin {
var openWithSystemBrowser = (arguments["openWithSystemBrowser"] as? Bool)!
if isLocalFile {
- let key = SwiftFlutterPlugin.registrar!.lookupKey(forAsset: url)
+ let key = self.registrar!.lookupKey(forAsset: url)
let assetURL = Bundle.main.url(forResource: key, withExtension: nil)
if assetURL == nil {
result(FlutterError(code: "InAppBrowserFlutterPlugin", message: url + " asset file cannot be found!", details: nil))
@@ -677,28 +675,28 @@ public class SwiftFlutterPlugin: NSObject, FlutterPlugin {
func onBrowserCreated(uuid: String, webView: WKWebView) {
if let webViewController = self.webViewControllers[uuid] {
- SwiftFlutterPlugin.channel!.invokeMethod("onBrowserCreated", arguments: ["uuid": uuid])
+ self.channel!.invokeMethod("onBrowserCreated", arguments: ["uuid": uuid])
}
}
func onExit(uuid: String) {
- SwiftFlutterPlugin.channel!.invokeMethod("onExit", arguments: ["uuid": uuid])
+ self.channel!.invokeMethod("onExit", arguments: ["uuid": uuid])
}
func onChromeSafariBrowserOpened(uuid: String) {
if self.safariViewControllers[uuid] != nil {
- SwiftFlutterPlugin.channel!.invokeMethod("onChromeSafariBrowserOpened", arguments: ["uuid": uuid])
+ self.channel!.invokeMethod("onChromeSafariBrowserOpened", arguments: ["uuid": uuid])
}
}
func onChromeSafariBrowserLoaded(uuid: String) {
if self.safariViewControllers[uuid] != nil {
- SwiftFlutterPlugin.channel!.invokeMethod("onChromeSafariBrowserLoaded", arguments: ["uuid": uuid])
+ self.channel!.invokeMethod("onChromeSafariBrowserLoaded", arguments: ["uuid": uuid])
}
}
func onChromeSafariBrowserClosed(uuid: String) {
- SwiftFlutterPlugin.channel!.invokeMethod("onChromeSafariBrowserClosed", arguments: ["uuid": uuid])
+ self.channel!.invokeMethod("onChromeSafariBrowserClosed", arguments: ["uuid": uuid])
}
func safariExit(uuid: String) {
diff --git a/lib/flutter_inappbrowser.dart b/lib/flutter_inappbrowser.dart
index 22ae6069..c6bdfc52 100644
--- a/lib/flutter_inappbrowser.dart
+++ b/lib/flutter_inappbrowser.dart
@@ -19,1549 +19,13 @@
*
*/
-import 'dart:io';
-import 'dart:async';
-import 'dart:collection';
-import 'dart:typed_data';
-import 'dart:convert';
-
-import 'package:flutter/foundation.dart';
-import 'package:flutter/material.dart';
-import 'package:flutter/services.dart';
-import 'package:flutter/widgets.dart';
-import 'package:flutter/gestures.dart';
-import 'package:uuid/uuid.dart';
-import 'package:mime/mime.dart';
-
-typedef Future ListenerCallback(MethodCall call);
-
-///This type represents a callback, added with [addJavaScriptHandler], that listens to post messages sent from JavaScript.
-///
-///The Android implementation uses [addJavascriptInterface](https://developer.android.com/reference/android/webkit/WebView#addJavascriptInterface(java.lang.Object,%20java.lang.String)).
-///The iOS implementation uses [addScriptMessageHandler](https://developer.apple.com/documentation/webkit/wkusercontentcontroller/1537172-addscriptmessagehandler?language=objc)
-///
-///The JavaScript function that can be used to call the handler is `window.flutter_inappbrowser.callHandler(handlerName , ...args);`, where `args` are [rest parameters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters).
-///The `args` will be stringified automatically using `JSON.stringify(args)` method and then they will be decoded on the Dart side.
-///
-///Also, a [JavaScriptHandlerCallback] can return json data to the JavaScript side.
-///In this case, simply return data that you want to send and it will be automatically json encoded using [jsonEncode] from the `dart:convert` library.
-typedef dynamic JavaScriptHandlerCallback(List arguments);
-
-var _uuidGenerator = new Uuid();
-
-///
-enum ConsoleMessageLevel {
- DEBUG, ERROR, LOG, TIP, WARNING
-}
-
-///Public class representing a resource request of the [InAppBrowser] WebView.
-///It is used by the method [InAppBrowser.onLoadResource()].
-class WebResourceRequest {
-
- String url;
- Map headers;
- String method;
-
- WebResourceRequest(this.url, this.headers, this.method);
-
-}
-
-///Public class representing a resource response of the [InAppBrowser] WebView.
-///It is used by the method [InAppBrowser.onLoadResource()].
-class WebResourceResponse {
-
- String url;
- Map headers;
- int statusCode;
- int startTime;
- int duration;
- Uint8List data;
-
- WebResourceResponse(this.url, this.headers, this.statusCode, this.startTime, this.duration, this.data);
-
-}
-
-///Public class representing a JavaScript console message from WebCore.
-///This could be a issued by a call to one of the console logging functions (e.g. console.log('...')) or a JavaScript error on the page.
-///
-///To receive notifications of these messages, override the [InAppBrowser.onConsoleMessage()] function.
-class ConsoleMessage {
-
- String sourceURL = "";
- int lineNumber = 1;
- String message = "";
- ConsoleMessageLevel messageLevel = ConsoleMessageLevel.LOG;
-
- ConsoleMessage(this.sourceURL, this.lineNumber, this.message, this.messageLevel);
-}
-
-class _ChannelManager {
- static const MethodChannel channel = const MethodChannel('com.pichillilorenzo/flutter_inappbrowser');
- static bool initialized = false;
- static final listeners = HashMap();
-
- static Future _handleMethod(MethodCall call) async {
- String uuid = call.arguments["uuid"];
- return await listeners[uuid](call);
- }
-
- static void addListener(String key, ListenerCallback callback) {
- if (!initialized)
- init();
- listeners.putIfAbsent(key, () => callback);
- }
-
- static void init () {
- channel.setMethodCallHandler(_handleMethod);
- initialized = true;
- }
-}
-
-///InAppBrowser class. [webViewController] can be used to access the [InAppWebView] API.
-///
-///This class uses the native WebView of the platform.
-class InAppBrowser {
-
- String uuid;
- Map javaScriptHandlersMap = HashMap();
- bool _isOpened = false;
- /// WebView Controller that can be used to access the [InAppWebView] API.
- InAppWebViewController webViewController;
-
- ///
- InAppBrowser () {
- uuid = _uuidGenerator.v4();
- _ChannelManager.addListener(uuid, _handleMethod);
- _isOpened = false;
- webViewController = new InAppWebViewController.fromInAppBrowser(uuid, _ChannelManager.channel, this);
- }
-
- Future _handleMethod(MethodCall call) async {
- switch(call.method) {
- case "onBrowserCreated":
- this._isOpened = true;
- onBrowserCreated();
- break;
- case "onExit":
- this._isOpened = false;
- onExit();
- break;
- default:
- return webViewController._handleMethod(call);
- }
- }
-
- ///Opens an [url] in a new [InAppBrowser] instance.
- ///
- ///- [url]: The [url] to load. Call [encodeUriComponent()] on this if the [url] contains Unicode characters. The default value is `about:blank`.
- ///
- ///- [headers]: The additional headers to be used in the HTTP request for this URL, specified as a map from name to value.
- ///
- ///- [options]: Options for the [InAppBrowser].
- ///
- /// - All platforms support:
- /// - __useShouldOverrideUrlLoading__: Set to `true` to be able to listen at the [shouldOverrideUrlLoading()] event. The default value is `false`.
- /// - __useOnLoadResource__: Set to `true` to be able to listen at the [onLoadResource()] event. The default value is `false`.
- /// - __clearCache__: Set to `true` to have all the browser's cache cleared before the new window is opened. The default value is `false`.
- /// - __userAgent__: Set the custom WebView's user-agent.
- /// - __javaScriptEnabled__: Set to `true` to enable JavaScript. The default value is `true`.
- /// - __javaScriptCanOpenWindowsAutomatically__: Set to `true` to allow JavaScript open windows without user interaction. The default value is `false`.
- /// - __hidden__: Set to `true` to create the browser and load the page, but not show it. The `onLoadStop` event fires when loading is complete. Omit or set to `false` (default) to have the browser open and load normally.
- /// - __toolbarTop__: Set to `false` to hide the toolbar at the top of the WebView. The default value is `true`.
- /// - __toolbarTopBackgroundColor__: Set the custom background color of the toolbar at the top.
- /// - __hideUrlBar__: Set to `true` to hide the url bar on the toolbar at the top. The default value is `false`.
- /// - __mediaPlaybackRequiresUserGesture__: Set to `true` to prevent HTML5 audio or video from autoplaying. The default value is `true`.
- /// - __transparentBackground__: Set to `true` to make the background of the WebView transparent. If your app has a dark theme, this can prevent a white flash on initialization. The default value is `false`.
- ///
- /// - **Android** supports these additional options:
- ///
- /// - __hideTitleBar__: Set to `true` if you want the title should be displayed. The default value is `false`.
- /// - __closeOnCannotGoBack__: Set to `false` to not close the InAppBrowser when the user click on the back button and the WebView cannot go back to the history. The default value is `true`.
- /// - __clearSessionCache__: Set to `true` to have the session cookie cache cleared before the new window is opened.
- /// - __builtInZoomControls__: Set to `true` if the WebView should use its built-in zoom mechanisms. The default value is `false`.
- /// - __displayZoomControls__: Set to `true` if the WebView should display on-screen zoom controls when using the built-in zoom mechanisms. The default value is `false`.
- /// - __supportZoom__: Set to `false` if the WebView should not support zooming using its on-screen zoom controls and gestures. The default value is `true`.
- /// - __databaseEnabled__: Set to `true` if you want the database storage API is enabled. The default value is `false`.
- /// - __domStorageEnabled__: Set to `true` if you want the DOM storage API is enabled. The default value is `false`.
- /// - __useWideViewPort__: Set to `true` if the WebView should enable support for the "viewport" HTML meta tag or should use a wide viewport. When the value of the setting is false, the layout width is always set to the width of the WebView control in device-independent (CSS) pixels. When the value is true and the page contains the viewport meta tag, the value of the width specified in the tag is used. If the page does not contain the tag or does not provide a width, then a wide viewport will be used. The default value is `true`.
- /// - __safeBrowsingEnabled__: Set to `true` if you want the Safe Browsing is enabled. Safe Browsing allows WebView to protect against malware and phishing attacks by verifying the links. The default value is `true`.
- /// - __progressBar__: Set to `false` to hide the progress bar at the bottom of the toolbar at the top. The default value is `true`.
- /// - __textZoom__: Set text scaling of the WebView. The default value is `100`.
- /// - __mixedContentMode__: Configures the WebView's behavior when a secure origin attempts to load a resource from an insecure origin. By default, apps that target `Build.VERSION_CODES.KITKAT` or below default to `MIXED_CONTENT_ALWAYS_ALLOW`. Apps targeting `Build.VERSION_CODES.LOLLIPOP` default to `MIXED_CONTENT_NEVER_ALLOW`. The preferred and most secure mode of operation for the WebView is `MIXED_CONTENT_NEVER_ALLOW` and use of `MIXED_CONTENT_ALWAYS_ALLOW` is strongly discouraged.
- ///
- /// - **iOS** supports these additional options:
- ///
- /// - __disallowOverScroll__: Set to `true` to disable the bouncing of the WebView when the scrolling has reached an edge of the content. The default value is `false`.
- /// - __toolbarBottom__: Set to `false` to hide the toolbar at the bottom of the WebView. The default value is `true`.
- /// - __toolbarBottomBackgroundColor__: Set the custom background color of the toolbar at the bottom.
- /// - __toolbarBottomTranslucent__: Set to `true` to set the toolbar at the bottom translucent. The default value is `true`.
- /// - __closeButtonCaption__: Set the custom text for the close button.
- /// - __closeButtonColor__: Set the custom color for the close button.
- /// - __presentationStyle__: Set the custom modal presentation style when presenting the WebView. The default value is `0 //fullscreen`. See [UIModalPresentationStyle](https://developer.apple.com/documentation/uikit/uimodalpresentationstyle) for all the available styles.
- /// - __transitionStyle__: Set to the custom transition style when presenting the WebView. The default value is `0 //crossDissolve`. See [UIModalTransitionStyle](https://developer.apple.com/documentation/uikit/uimodaltransitionStyle) for all the available styles.
- /// - __enableViewportScale__: Set to `true` to allow a viewport meta tag to either disable or restrict the range of user scaling. The default value is `false`.
- /// - __suppressesIncrementalRendering__: Set to `true` if you want the WebView suppresses content rendering until it is fully loaded into memory.. The default value is `false`.
- /// - __allowsAirPlayForMediaPlayback__: Set to `true` to allow AirPlay. The default value is `true`.
- /// - __allowsBackForwardNavigationGestures__: Set to `true` to allow the horizontal swipe gestures trigger back-forward list navigations. The default value is `true`.
- /// - __allowsLinkPreview__: Set to `true` to allow that pressing on a link displays a preview of the destination for the link. The default value is `true`.
- /// - __ignoresViewportScaleLimits__: Set to `true` if you want that the WebView should always allow scaling of the webpage, regardless of the author's intent. The ignoresViewportScaleLimits property overrides the `user-scalable` HTML property in a webpage. The default value is `false`.
- /// - __allowsInlineMediaPlayback__: Set to `true` to allow HTML5 media playback to appear inline within the screen layout, using browser-supplied controls rather than native controls. For this to work, add the `webkit-playsinline` attribute to any `