Isolate extension WebView profiles and follow host proxy settings

This commit is contained in:
Levi committed 2026-09-14 00:30:52 +08:00
1 parent cee5f3336e
commit a0e84a75b1
556 files changed
+71097 -31

No files matched your search

@@ -0,0 +1,171 @@
//
// CredentialDatabase.swift
// flutter_inappwebview
//
// Created by Lorenzo Pichilli on 29/10/2019.
//
import Foundation
public class CredentialDatabase: ChannelDelegate {
static let METHOD_CHANNEL_NAME = "com.pichillilorenzo/flutter_inappwebview_credential_database"
static let credentialStore = URLCredentialStorage.shared
private var plugin: SwiftFlutterPlugin?
init(plugin: SwiftFlutterPlugin) {
super.init(channel: FlutterMethodChannel(name: CredentialDatabase.METHOD_CHANNEL_NAME, binaryMessenger: plugin.registrar!.messenger()))
self.plugin = plugin
}
public override func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
let arguments = call.arguments as? NSDictionary
switch call.method {
case "getAllAuthCredentials":
var allCredentials: [[String: Any?]] = []
for (protectionSpace, credentials) in CredentialDatabase.credentialStore.allCredentials {
var crendentials: [[String: Any?]] = []
for c in credentials {
let credential: [String: Any?] = c.value.toMap()
crendentials.append(credential)
}
if crendentials.count > 0 {
let dict: [String : Any] = [
"protectionSpace": protectionSpace.toMap(),
"credentials": crendentials
]
allCredentials.append(dict)
}
}
result(allCredentials)
break
case "getHttpAuthCredentials":
var crendentials: [[String: Any?]] = []
let host = arguments!["host"] as! String
let urlProtocol = arguments!["protocol"] as? String
let urlPort = arguments!["port"] as? Int ?? 0
var realm = arguments!["realm"] as? String
if let r = realm, r.isEmpty {
realm = nil
}
for (protectionSpace, credentials) in CredentialDatabase.credentialStore.allCredentials {
if protectionSpace.host == host && protectionSpace.realm == realm &&
protectionSpace.protocol == urlProtocol && protectionSpace.port == urlPort {
for c in credentials {
crendentials.append(c.value.toMap())
}
break
}
}
result(crendentials)
break
case "setHttpAuthCredential":
let host = arguments!["host"] as! String
let urlProtocol = arguments!["protocol"] as? String
let urlPort = arguments!["port"] as? Int ?? 0
var realm = arguments!["realm"] as? String
if let r = realm, r.isEmpty {
realm = nil
}
let username = arguments!["username"] as! String
let password = arguments!["password"] as! String
let credential = URLCredential(user: username, password: password, persistence: .permanent)
CredentialDatabase.credentialStore.set(credential,
for: URLProtectionSpace(host: host, port: urlPort, protocol: urlProtocol,
realm: realm, authenticationMethod: NSURLAuthenticationMethodHTTPBasic))
result(true)
break
case "removeHttpAuthCredential":
let host = arguments!["host"] as! String
let urlProtocol = arguments!["protocol"] as? String
let urlPort = arguments!["port"] as? Int ?? 0
var realm = arguments!["realm"] as? String
if let r = realm, r.isEmpty {
realm = nil
}
let username = arguments!["username"] as! String
let password = arguments!["password"] as! String
var credential: URLCredential? = nil
var protectionSpaceCredential: URLProtectionSpace? = nil
for (protectionSpace, credentials) in CredentialDatabase.credentialStore.allCredentials {
if protectionSpace.host == host && protectionSpace.realm == realm &&
protectionSpace.protocol == urlProtocol && protectionSpace.port == urlPort {
for c in credentials {
if c.value.user == username, c.value.password == password {
credential = c.value
protectionSpaceCredential = protectionSpace
break
}
}
}
if credential != nil {
break
}
}
if let c = credential, let protectionSpace = protectionSpaceCredential {
CredentialDatabase.credentialStore.remove(c, for: protectionSpace)
}
result(true)
break
case "removeHttpAuthCredentials":
let host = arguments!["host"] as! String
let urlProtocol = arguments!["protocol"] as? String
let urlPort = arguments!["port"] as? Int ?? 0
var realm = arguments!["realm"] as? String
if let r = realm, r.isEmpty {
realm = nil
}
var credentialsToRemove: [URLCredential] = []
var protectionSpaceCredential: URLProtectionSpace? = nil
for (protectionSpace, credentials) in CredentialDatabase.credentialStore.allCredentials {
if protectionSpace.host == host && protectionSpace.realm == realm &&
protectionSpace.protocol == urlProtocol && protectionSpace.port == urlPort {
protectionSpaceCredential = protectionSpace
for c in credentials {
if let _ = c.value.user, let _ = c.value.password {
credentialsToRemove.append(c.value)
}
}
break
}
}
if let protectionSpace = protectionSpaceCredential {
for credential in credentialsToRemove {
CredentialDatabase.credentialStore.remove(credential, for: protectionSpace)
}
}
result(true)
break
case "clearAllAuthCredentials":
for (protectionSpace, credentials) in CredentialDatabase.credentialStore.allCredentials {
for credential in credentials {
CredentialDatabase.credentialStore.remove(credential.value, for: protectionSpace)
}
}
result(true)
break
default:
result(FlutterMethodNotImplemented)
break
}
}
public override func dispose() {
super.dispose()
plugin = nil
}
deinit {
dispose()
}
}
@@ -0,0 +1,158 @@
//
// FindInteractionChannelDelegate.swift
// flutter_inappwebview
//
// Created by Lorenzo Pichilli on 07/10/22.
//
import Foundation
public class FindInteractionChannelDelegate: ChannelDelegate {
private weak var findInteractionController: FindInteractionController?
public init(findInteractionController: FindInteractionController, channel: FlutterMethodChannel) {
super.init(channel: channel)
self.findInteractionController = findInteractionController
}
public override func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
let arguments = call.arguments as? NSDictionary
switch call.method {
case "findAll":
if let findInteractionController = findInteractionController {
let find = arguments!["find"] as! String
findInteractionController.findAll(find: find, completionHandler: {(value, error) in
if error != nil {
result(FlutterError(code: "FindInteractionChannelDelegate", message: error?.localizedDescription, details: nil))
return
}
result(true)
})
} else {
result(false)
}
break
case "findNext":
if let findInteractionController = findInteractionController {
let forward = arguments!["forward"] as! Bool
findInteractionController.findNext(forward: forward, completionHandler: {(value, error) in
if error != nil {
result(FlutterError(code: "FindInteractionChannelDelegate", message: error?.localizedDescription, details: nil))
return
}
result(true)
})
} else {
result(false)
}
break
case "clearMatches":
if let findInteractionController = findInteractionController {
findInteractionController.clearMatches(completionHandler: {(value, error) in
if error != nil {
result(FlutterError(code: "FindInteractionChannelDelegate", message: error?.localizedDescription, details: nil))
return
}
result(true)
})
} else {
result(false)
}
break
case "setSearchText":
if let findInteractionController = findInteractionController {
let searchText = arguments!["searchText"] as? String
findInteractionController.searchText = searchText
result(true)
} else {
result(false)
}
break
case "getSearchText":
result(findInteractionController?.searchText)
break
case "isFindNavigatorVisible":
if #available(iOS 16.0, *) {
if let interaction = findInteractionController?.webView?.findInteraction {
result(interaction.isFindNavigatorVisible)
} else {
result(false)
}
} else {
result(false)
}
break
case "updateResultCount":
if #available(iOS 16.0, *) {
if let interaction = findInteractionController?.webView?.findInteraction {
interaction.updateResultCount()
result(true)
} else {
result(false)
}
} else {
result(false)
}
break
case "presentFindNavigator":
if #available(iOS 16.0, *) {
if let interaction = findInteractionController?.webView?.findInteraction {
interaction.presentFindNavigator(showingReplace: false)
result(true)
} else {
result(false)
}
} else {
result(false)
}
break
case "dismissFindNavigator":
if #available(iOS 16.0, *) {
if let interaction = findInteractionController?.webView?.findInteraction {
interaction.dismissFindNavigator()
result(true)
} else {
result(false)
}
} else {
result(false)
}
break
case "getActiveFindSession":
if let findInteractionController = findInteractionController {
result(findInteractionController.activeFindSession?.toMap())
} else {
result(nil)
}
break
default:
result(FlutterMethodNotImplemented)
break
}
}
public func onFindResultReceived(activeMatchOrdinal: Int, numberOfMatches: Int, isDoneCounting: Bool) {
if isDoneCounting, let findInteractionController = findInteractionController {
findInteractionController.activeFindSession = FindSession(resultCount: numberOfMatches,
highlightedResultIndex: activeMatchOrdinal,
searchResultDisplayStyle: 2) // matches UIFindSession.SearchResultDisplayStyle.none
}
let arguments: [String : Any?] = [
"activeMatchOrdinal": activeMatchOrdinal,
"numberOfMatches": numberOfMatches,
"isDoneCounting": isDoneCounting
]
channel?.invokeMethod("onFindResultReceived", arguments: arguments)
}
public override func dispose() {
super.dispose()
findInteractionController = nil
}
deinit {
dispose()
}
}
@@ -0,0 +1,162 @@
//
// FindInteractionController.swift
// flutter_inappwebview
//
// Created by Lorenzo Pichilli on 07/10/22.
//
import Foundation
import Flutter
public class FindInteractionController: NSObject, Disposable {
static let METHOD_CHANNEL_NAME_PREFIX = "com.pichillilorenzo/flutter_inappwebview_find_interaction_"
var webView: InAppWebView?
var channelDelegate: FindInteractionChannelDelegate?
private var plugin: SwiftFlutterPlugin?
private var settings: FindInteractionSettings?
private var _searchText: String? = nil
var searchText: String? {
get {
if #available(iOS 16.0, *), let interaction = webView?.findInteraction {
return interaction.searchText
}
return _searchText
}
set {
if #available(iOS 16.0, *), let interaction = webView?.findInteraction {
interaction.searchText = newValue
}
self._searchText = newValue
}
}
private var _activeFindSession: FindSession? = nil
var activeFindSession: FindSession? {
get {
if #available(iOS 16.0, *), let interaction = webView?.findInteraction {
if let activeFindSession = interaction.activeFindSession {
return FindSession.fromUIFindSession(uiFindSession: activeFindSession)
}
return nil
}
return _activeFindSession
}
set {
self._activeFindSession = newValue
}
}
public init(plugin: SwiftFlutterPlugin, id: Any, webView: InAppWebView, settings: FindInteractionSettings?) {
super.init()
self.plugin = plugin
self.webView = webView
self.settings = settings
if let registrar = plugin.registrar {
let channel = FlutterMethodChannel(name: FindInteractionController.METHOD_CHANNEL_NAME_PREFIX + String(describing: id),
binaryMessenger: registrar.messenger())
self.channelDelegate = FindInteractionChannelDelegate(findInteractionController: self, channel: channel)
}
}
public func prepare() {
// if let settings = settings {
//
// }
}
public func findAll(find: String?, completionHandler: ((Any?, Error?) -> Void)?) {
guard let webView else {
if let completionHandler = completionHandler {
completionHandler(nil, nil)
}
return
}
var find = find
if find == nil {
find = searchText
} else {
// updated searchText
searchText = find
}
guard let find else {
if let completionHandler = completionHandler {
completionHandler(nil, nil)
}
return
}
if #available(iOS 16.0, *), webView.isFindInteractionEnabled {
if let interaction = webView.findInteraction {
interaction.searchText = find
interaction.presentFindNavigator(showingReplace: false)
}
if let completionHandler = completionHandler {
completionHandler(nil, nil)
}
} else if find != "" {
let startSearch = "window.\(JAVASCRIPT_BRIDGE_NAME)._findAllAsync('\(find)');"
webView.evaluateJavaScript(startSearch, completionHandler: completionHandler)
}
}
public func findNext(forward: Bool, completionHandler: ((Any?, Error?) -> Void)?) {
guard let webView else {
if let completionHandler = completionHandler {
completionHandler(nil, nil)
}
return
}
if #available(iOS 16.0, *), webView.isFindInteractionEnabled {
if let interaction = webView.findInteraction {
if forward {
interaction.findNext()
} else {
interaction.findPrevious()
}
}
if let completionHandler = completionHandler {
completionHandler(nil, nil)
}
} else {
webView.evaluateJavaScript("window.\(JAVASCRIPT_BRIDGE_NAME)._findNext(\(forward ? "true" : "false"));", completionHandler: completionHandler)
}
}
public func clearMatches(completionHandler: ((Any?, Error?) -> Void)?) {
guard let webView else {
if let completionHandler = completionHandler {
completionHandler(nil, nil)
}
return
}
if #available(iOS 16.0, *), webView.isFindInteractionEnabled {
if let interaction = webView.findInteraction {
interaction.searchText = nil
interaction.dismissFindNavigator()
}
if let completionHandler = completionHandler {
completionHandler(nil, nil)
}
} else {
webView.evaluateJavaScript("window.\(JAVASCRIPT_BRIDGE_NAME)._clearMatches();", completionHandler: completionHandler)
}
}
public func dispose() {
channelDelegate?.dispose()
channelDelegate = nil
webView = nil
activeFindSession = nil
plugin = nil
}
deinit {
debugPrint("FindInteractionControl - dealloc")
dispose()
}
}
@@ -0,0 +1,25 @@
//
// FindInteractionSettings.swift
// flutter_inappwebview
//
// Created by Lorenzo Pichilli on 07/10/22.
//
import Foundation
public class FindInteractionSettings: ISettings<FindInteractionController> {
override init(){
super.init()
}
override func parse(settings: [String: Any?]) -> FindInteractionSettings {
let _ = super.parse(settings: settings)
return self
}
override func getRealSettings(obj: FindInteractionController?) -> [String: Any?] {
let realSettings: [String: Any?] = toMap()
return realSettings
}
}
@@ -0,0 +1,29 @@
// Internal Gopeed host bridge. No extension-facing API.
import Foundation
import WebKit
import Network
import Flutter
final class GopeedProfiles {
private static var stores: [String: WKWebsiteDataStore] = [:]
static func store(_ identifier: String) -> WKWebsiteDataStore? { stores[identifier] }
static func prepare(arguments: NSDictionary?, result: @escaping FlutterResult) {
guard #available(macOS 14.0, iOS 17.0, *),
let identifier = arguments?["gopeedProfileId"] as? String,
let uuid = UUID(uuidString: identifier),
let proxyURL = arguments?["proxyUrl"] as? String,
let url = URL(string: proxyURL), url.scheme == "socks5",
let host = url.host, host == "127.0.0.1",
let port = url.port, port > 0 && port <= 65535 else {
result(FlutterError(code: "UNAVAILABLE", message: "Isolated WebView profiles and proxy require macOS 14 / iOS 17 or newer and valid host configuration", details: nil))
return
}
let store = stores[identifier] ?? WKWebsiteDataStore(forIdentifier: uuid)
let endpoint = nw_endpoint_create_host(host, String(port))
let proxy = nw_proxy_config_create_socksv5(endpoint)
store.__proxyConfigurations = [proxy]
stores[identifier] = store
result(true)
}
}
@@ -0,0 +1,99 @@
//
// HeadlessInAppWebView.swift
// flutter_inappwebview
//
// Created by Lorenzo Pichilli on 26/03/21.
//
import Foundation
public class HeadlessInAppWebView: Disposable {
static let METHOD_CHANNEL_NAME_PREFIX = "com.pichillilorenzo/flutter_headless_inappwebview_"
var id: String
var channelDelegate: HeadlessWebViewChannelDelegate?
var flutterWebView: FlutterWebViewController?
var plugin: SwiftFlutterPlugin?
public init(plugin: SwiftFlutterPlugin, id: String, flutterWebView: FlutterWebViewController) {
self.id = id
self.flutterWebView = flutterWebView
self.plugin = plugin
let channel = FlutterMethodChannel(name: HeadlessInAppWebView.METHOD_CHANNEL_NAME_PREFIX + id,
binaryMessenger: plugin.registrar!.messenger())
self.channelDelegate = HeadlessWebViewChannelDelegate(headlessWebView: self, channel: channel)
}
public func onWebViewCreated() {
channelDelegate?.onWebViewCreated()
}
public func prepare(params: NSDictionary) {
if let view = flutterWebView?.view() {
view.alpha = 0.01
let initialSize = params["initialSize"] as? [String: Any?]
if let size = Size2D.fromMap(map: initialSize) {
setSize(size: size)
} else {
view.frame = CGRect(x: 0.0, y: 0.0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
}
if let keyWindow = UIApplication.shared.keyWindow {
/// Note: The WKWebView behaves very unreliable when rendering offscreen
/// on a device. This is especially true with JavaScript, which simply
/// won't be executed sometimes.
/// So, add the headless WKWebView to the view hierarchy.
/// This way is also possible to take screenshots.
keyWindow.insertSubview(view, at: 0)
keyWindow.sendSubviewToBack(view)
}
}
}
public func setSize(size: Size2D) {
if let view = flutterWebView?.view() {
let width = size.width == -1.0 ? UIScreen.main.bounds.width : CGFloat(size.width)
let height = size.height == -1.0 ? UIScreen.main.bounds.height : CGFloat(size.height)
view.frame = CGRect(x: 0.0, y: 0.0, width: width, height: height)
}
}
public func getSize() -> Size2D? {
if let view = flutterWebView?.view() {
return Size2D(width: Double(view.frame.width), height: Double(view.frame.height))
}
return nil
}
public func disposeAndGetFlutterWebView(withFrame frame: CGRect) -> FlutterWebViewController? {
let newFlutterWebView = flutterWebView
if let view = flutterWebView?.view() {
// restore WebView frame and alpha
view.frame = frame
view.alpha = 1.0
// remove from parent
view.removeFromSuperview()
dispose(disposeWebView: false)
}
return newFlutterWebView
}
public func dispose(disposeWebView: Bool) {
channelDelegate?.dispose()
channelDelegate = nil
plugin?.headlessInAppWebViewManager?.webViews[id] = nil
if disposeWebView {
flutterWebView?.dispose(removeFromSuperview: true)
}
flutterWebView = nil
plugin = nil
}
public func dispose() {
dispose(disposeWebView: true)
}
deinit {
debugPrint("HeadlessInAppWebView - dealloc")
dispose()
}
}
@@ -0,0 +1,71 @@
//
// HeadlessInAppWebViewManager.swift
// flutter_inappwebview
//
// Created by Lorenzo Pichilli on 10/05/2020.
//
import Foundation
import Flutter
import UIKit
import WebKit
import Foundation
import AVFoundation
public class HeadlessInAppWebViewManager: ChannelDelegate {
static let METHOD_CHANNEL_NAME = "com.pichillilorenzo/flutter_headless_inappwebview"
var plugin: SwiftFlutterPlugin?
var webViews: [String: HeadlessInAppWebView?] = [:]
init(plugin: SwiftFlutterPlugin) {
super.init(channel: FlutterMethodChannel(name: HeadlessInAppWebViewManager.METHOD_CHANNEL_NAME, binaryMessenger: plugin.registrar!.messenger()))
self.plugin = plugin
}
public override func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
let arguments = call.arguments as? NSDictionary
let id: String = arguments!["id"] as! String
switch call.method {
case "run":
let params = arguments!["params"] as! [String: Any?]
run(id: id, params: params)
result(true)
break
default:
result(FlutterMethodNotImplemented)
break
}
}
public func run(id: String, params: [String: Any?]) {
guard let plugin = plugin else {
return
}
let flutterWebView = FlutterWebViewController(plugin: plugin,
withFrame: CGRect.zero,
viewIdentifier: id,
params: params as NSDictionary)
let headlessInAppWebView = HeadlessInAppWebView(plugin: plugin, id: id, flutterWebView: flutterWebView)
webViews[id] = headlessInAppWebView
headlessInAppWebView.prepare(params: params as NSDictionary)
headlessInAppWebView.onWebViewCreated()
flutterWebView.makeInitialLoad(params: params as NSDictionary)
}
public override func dispose() {
super.dispose()
let headlessWebViews = webViews.values
headlessWebViews.forEach { (headlessWebView: HeadlessInAppWebView?) in
headlessWebView?.dispose()
}
webViews.removeAll()
plugin = nil
}
deinit {
dispose()
}
}
@@ -0,0 +1,63 @@
//
// HeadlessWebViewChannelDelegate.swift
// flutter_inappwebview
//
// Created by Lorenzo Pichilli on 05/05/22.
//
import Foundation
public class HeadlessWebViewChannelDelegate: ChannelDelegate {
private weak var headlessWebView: HeadlessInAppWebView?
public init(headlessWebView: HeadlessInAppWebView, channel: FlutterMethodChannel) {
super.init(channel: channel)
self.headlessWebView = headlessWebView
}
public override func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
let arguments = call.arguments as? NSDictionary
switch call.method {
case "dispose":
if let headlessWebView = headlessWebView {
headlessWebView.dispose()
result(true)
} else {
result(false)
}
break
case "setSize":
if let headlessWebView = headlessWebView {
let sizeMap = arguments!["size"] as? [String: Any?]
if let size = Size2D.fromMap(map: sizeMap) {
headlessWebView.setSize(size: size)
}
result(true)
} else {
result(false)
}
break
case "getSize":
result(headlessWebView?.getSize()?.toMap())
break
default:
result(FlutterMethodNotImplemented)
break
}
}
public func onWebViewCreated() {
let arguments: [String: Any?] = [:]
channel?.invokeMethod("onWebViewCreated", arguments: arguments)
}
public override func dispose() {
super.dispose()
headlessWebView = nil
}
deinit {
dispose()
}
}
@@ -0,0 +1,50 @@
//
// Options.swift
// flutter_inappwebview
//
// Created by Lorenzo on 26/09/18.
//
import Foundation
@objcMembers
public class ISettings<T>: NSObject {
override init(){
super.init()
}
func parse(settings: [String: Any?]) -> ISettings<T> {
for (key, value) in settings {
if !(value is NSNull), value != nil {
if self.responds(to: Selector(key)) {
self.setValue(value, forKey: key)
} else if self.responds(to: Selector("_" + key)) {
self.setValue(value, forKey: "_" + key)
}
}
}
return self
}
func toMap() -> [String: Any?] {
var settings: [String: Any?] = [:]
var counts = UInt32()
let properties = class_copyPropertyList(object_getClass(self), &counts)
for i in 0..<counts {
if let property = properties?.advanced(by: Int(i)).pointee {
let cName = property_getName(property)
let name = String(cString: cName)
let key = !name.hasPrefix("_") ? name : String(name.suffix(from: name.index(name.startIndex, offsetBy: 1)))
settings[key] = self.value(forKey: key)
}
}
free(properties)
return settings
}
func getRealSettings(obj: T?) -> [String: Any?] {
let realSettings: [String: Any?] = toMap()
return realSettings
}
}
@@ -0,0 +1,35 @@
//
// InAppBrowserChannelDelegate.swift
// flutter_inappwebview
//
// Created by Lorenzo Pichilli on 05/05/22.
//
import Foundation
public class InAppBrowserChannelDelegate: ChannelDelegate {
public override init(channel: FlutterMethodChannel) {
super.init(channel: channel)
}
public func onBrowserCreated() {
let arguments: [String: Any?] = [:]
channel?.invokeMethod("onBrowserCreated", arguments: arguments)
}
public func onMenuItemClicked(menuItem: InAppBrowserMenuItem) {
let arguments: [String: Any?] = [
"id": menuItem.id
]
channel?.invokeMethod("onMenuItemClicked", arguments: arguments)
}
public func onExit() {
let arguments: [String: Any?] = [:]
channel?.invokeMethod("onExit", arguments: arguments)
}
deinit {
dispose()
}
}
@@ -0,0 +1,17 @@
//
// InAppBrowserDelegate.swift
// flutter_inappwebview
//
// Created by Lorenzo Pichilli on 14/02/21.
//
import Foundation
public protocol InAppBrowserDelegate {
func didChangeTitle(title: String?)
func didStartNavigation(url: URL?)
func didUpdateVisitedHistory(url: URL?)
func didFinishNavigation(url: URL?)
func didFailNavigation(url: URL?, error: Error)
func didChangeProgress(progress: Double)
}
@@ -0,0 +1,153 @@
//
// InAppBrowserManager.swift
// flutter_inappwebview
//
// Created by Lorenzo Pichilli on 18/12/2019.
//
import Flutter
import UIKit
import WebKit
import Foundation
import AVFoundation
public class InAppBrowserManager: ChannelDelegate {
static let METHOD_CHANNEL_NAME = "com.pichillilorenzo/flutter_inappbrowser"
static let WEBVIEW_STORYBOARD = "WebView"
static let WEBVIEW_STORYBOARD_CONTROLLER_ID = "viewController"
static let NAV_STORYBOARD_CONTROLLER_ID = "navController"
var plugin: SwiftFlutterPlugin?
private var previousStatusBarStyle = -1
init(plugin: SwiftFlutterPlugin) {
super.init(channel: FlutterMethodChannel(name: InAppBrowserManager.METHOD_CHANNEL_NAME, binaryMessenger: plugin.registrar!.messenger()))
self.plugin = plugin
}
public override func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
let arguments = call.arguments as? NSDictionary
switch call.method {
case "open":
open(arguments: arguments!)
result(true)
break
case "openWithSystemBrowser":
let url = arguments!["url"] as! String
openWithSystemBrowser(url: url, result: result)
break
default:
result(FlutterMethodNotImplemented)
break
}
}
public func prepareInAppBrowserWebViewController(settings: [String: Any?]) -> InAppBrowserWebViewController {
if previousStatusBarStyle == -1 {
previousStatusBarStyle = UIApplication.shared.statusBarStyle.rawValue
}
let browserSettings = InAppBrowserSettings()
let _ = browserSettings.parse(settings: settings)
let webViewSettings = InAppWebViewSettings()
let _ = webViewSettings.parse(settings: settings)
let webViewController = InAppBrowserWebViewController()
webViewController.plugin = plugin
webViewController.browserSettings = browserSettings
webViewController.isHidden = browserSettings.hidden
webViewController.webViewSettings = webViewSettings
webViewController.previousStatusBarStyle = previousStatusBarStyle
return webViewController
}
public func open(arguments: NSDictionary) {
let id = arguments["id"] as! String
let urlRequest = arguments["urlRequest"] as? [String:Any?]
let assetFilePath = arguments["assetFilePath"] as? String
let data = arguments["data"] as? String
let mimeType = arguments["mimeType"] as? String
let encoding = arguments["encoding"] as? String
let baseUrl = arguments["baseUrl"] as? String
let settings = arguments["settings"] as! [String: Any?]
let contextMenu = arguments["contextMenu"] as! [String: Any]
let windowId = arguments["windowId"] as? Int64
let initialUserScripts = arguments["initialUserScripts"] as? [[String: Any]]
let pullToRefreshInitialSettings = arguments["pullToRefreshSettings"] as! [String: Any?]
let menuItems = arguments["menuItems"] as! [[String: Any?]]
let webViewController = prepareInAppBrowserWebViewController(settings: settings)
webViewController.id = id
webViewController.initialUrlRequest = urlRequest != nil ? URLRequest.init(fromPluginMap: urlRequest!) : nil
webViewController.initialFile = assetFilePath
webViewController.initialData = data
webViewController.initialMimeType = mimeType
webViewController.initialEncoding = encoding
webViewController.initialBaseUrl = baseUrl
webViewController.contextMenu = contextMenu
webViewController.windowId = windowId
webViewController.initialUserScripts = initialUserScripts ?? []
webViewController.pullToRefreshInitialSettings = pullToRefreshInitialSettings
for menuItem in menuItems {
webViewController.menuItems.append(InAppBrowserMenuItem.fromMap(map: menuItem)!)
}
presentViewController(webViewController: webViewController)
}
public func presentViewController(webViewController: InAppBrowserWebViewController) {
let storyboard = UIStoryboard(name: InAppBrowserManager.WEBVIEW_STORYBOARD, bundle: Bundle(for: InAppWebViewFlutterPlugin.self))
let navController = storyboard.instantiateViewController(withIdentifier: InAppBrowserManager.NAV_STORYBOARD_CONTROLLER_ID) as! InAppBrowserNavigationController
webViewController.edgesForExtendedLayout = []
navController.pushViewController(webViewController, animated: false)
webViewController.prepareNavigationControllerBeforeViewWillAppear()
var animated = true
if let browserSettings = webViewController.browserSettings, browserSettings.hidden {
animated = false
}
guard let visibleViewController = UIApplication.shared.visibleViewController else {
assertionFailure("Failure init the visibleViewController!")
return
}
if let popover = navController.popoverPresentationController {
let sourceView = visibleViewController.view ?? UIView()
popover.sourceRect = CGRect(x: sourceView.bounds.midX, y: sourceView.bounds.midY, width: 0, height: 0)
popover.permittedArrowDirections = []
popover.sourceView = sourceView
}
visibleViewController.present(navController, animated: animated)
}
public func openWithSystemBrowser(url: String, result: @escaping FlutterResult) {
let absoluteUrl = URL(string: url)!.absoluteURL
if !UIApplication.shared.canOpenURL(absoluteUrl) {
result(FlutterError(code: "InAppBrowserManager", message: url + " cannot be opened!", details: nil))
return
}
else {
if #available(iOS 10.0, *) {
UIApplication.shared.open(absoluteUrl)
} else {
UIApplication.shared.openURL(absoluteUrl)
}
}
result(true)
}
public override func dispose() {
super.dispose()
plugin = nil
}
deinit {
dispose()
}
}
@@ -0,0 +1,19 @@
//
// InAppBrowserNavigationController.swift
// flutter_inappwebview
//
// Created by Lorenzo Pichilli on 14/02/21.
//
import Foundation
public class InAppBrowserNavigationController: UINavigationController {
var tmpWindow: UIWindow?
deinit {
debugPrint("InAppBrowserNavigationController - dealloc")
tmpWindow?.windowLevel = UIWindow.Level(rawValue: 0.0)
tmpWindow = nil
UIApplication.shared.delegate?.window??.makeKeyAndVisible()
}
}
@@ -0,0 +1,62 @@
//
// InAppBrowserOptions.swift
// flutter_inappwebview
//
// Created by Lorenzo on 17/09/18.
//
import Foundation
@objcMembers
public class InAppBrowserSettings: ISettings<InAppBrowserWebViewController> {
var hidden = false
var hideToolbarTop = true
var toolbarTopBackgroundColor: String?
var hideUrlBar = false
var hideProgressBar = false
var toolbarTopTranslucent = true
var toolbarTopBarTintColor: String?
var toolbarTopTintColor: String?
var hideToolbarBottom = true
var toolbarBottomBackgroundColor: String?
var toolbarBottomTintColor: String?
var toolbarBottomTranslucent = true
var closeButtonCaption: String?
var closeButtonColor: String?
var presentationStyle = 0 //fullscreen
var transitionStyle = 0 //crossDissolve
var hideCloseButton = false
var menuButtonColor: String?
override init(){
super.init()
}
override func getRealSettings(obj: InAppBrowserWebViewController?) -> [String: Any?] {
var realOptions: [String: Any?] = toMap()
if let inAppBrowserWebViewController = obj {
realOptions["hidden"] = inAppBrowserWebViewController.isHidden
realOptions["hideUrlBar"] = inAppBrowserWebViewController.searchBar.isHidden
realOptions["hideProgressBar"] = inAppBrowserWebViewController.progressBar.isHidden
realOptions["closeButtonCaption"] = inAppBrowserWebViewController.closeButton.title
realOptions["closeButtonColor"] = inAppBrowserWebViewController.closeButton.tintColor?.hexString
realOptions["menuButtonColor"] = inAppBrowserWebViewController.menuButton?.tintColor?.hexString
if let navController = inAppBrowserWebViewController.navigationController {
realOptions["hideToolbarTop"] = navController.navigationBar.isHidden
realOptions["toolbarTopBackgroundColor"] = navController.navigationBar.backgroundColor?.hexString
realOptions["toolbarTopTranslucent"] = navController.navigationBar.isTranslucent
realOptions["toolbarTopBarTintColor"] = navController.navigationBar.barTintColor?.hexString
realOptions["toolbarTopTintColor"] = navController.navigationBar.tintColor?.hexString
realOptions["hideToolbarBottom"] = navController.toolbar.isHidden
realOptions["toolbarBottomBackgroundColor"] = navController.toolbar.barTintColor?.hexString
realOptions["toolbarBottomTranslucent"] = navController.toolbar.isTranslucent
realOptions["toolbarBottomTintColor"] = navController.toolbar.tintColor?.hexString
realOptions["presentationStyle"] = navController.modalPresentationStyle.rawValue
realOptions["transitionStyle"] = navController.modalTransitionStyle.rawValue
}
}
return realOptions
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,17 @@
//
// ContextMenuOptions.swift
// flutter_inappwebview
//
// Created by Lorenzo Pichilli on 30/05/2020.
//
import Foundation
public class ContextMenuSettings: ISettings<NSObject> {
var hideDefaultSystemContextMenuItems = false
override init(){
super.init()
}
}
@@ -0,0 +1,45 @@
//
// CustomSchemeHandler.swift
// flutter_inappwebview
//
// Created by Lorenzo Pichilli on 25/10/2019.
//
import Flutter
import Foundation
import WebKit
@available(iOS 11.0, *)
public class CustomSchemeHandler: NSObject, WKURLSchemeHandler {
var schemeHandlers: [Int: WKURLSchemeTask] = [:]
public func webView(_ webView: WKWebView, start urlSchemeTask: WKURLSchemeTask) {
schemeHandlers[urlSchemeTask.hash] = urlSchemeTask
let inAppWebView = webView as! InAppWebView
let request = WebResourceRequest.init(fromURLRequest: urlSchemeTask.request)
let callback = WebViewChannelDelegate.LoadResourceWithCustomSchemeCallback()
callback.nonNullSuccess = { (response: CustomSchemeResponse) in
if (self.schemeHandlers[urlSchemeTask.hash] != nil) {
let urlResponse = URLResponse(url: request.url, mimeType: response.contentType, expectedContentLength: -1, textEncodingName: response.contentEncoding)
urlSchemeTask.didReceive(urlResponse)
urlSchemeTask.didReceive(response.data)
urlSchemeTask.didFinish()
self.schemeHandlers.removeValue(forKey: urlSchemeTask.hash)
}
return false
}
callback.error = { (code: String, message: String?, details: Any?) in
print(code + ", " + (message ?? ""))
}
if let channelDelegate = inAppWebView.channelDelegate {
channelDelegate.onLoadResourceWithCustomScheme(request: request, callback: callback)
} else {
callback.defaultBehaviour(nil)
}
}
public func webView(_ webView: WKWebView, stop urlSchemeTask: WKURLSchemeTask) {
schemeHandlers.removeValue(forKey: urlSchemeTask.hash)
}
}
@@ -0,0 +1,213 @@
//
// FlutterWebViewController.swift
// flutter_inappwebview
//
// Created by Lorenzo on 13/11/18.
//
import Foundation
import WebKit
public class FlutterWebViewController: NSObject, FlutterPlatformView, Disposable {
var myView: UIView?
var keepAliveId: String?
init(plugin: SwiftFlutterPlugin, withFrame frame: CGRect, viewIdentifier viewId: Any, params: NSDictionary) {
super.init()
myView = UIView(frame: frame)
myView!.clipsToBounds = true
keepAliveId = params["keepAliveId"] as? String
let initialSettings = params["initialSettings"] as! [String: Any?]
let contextMenu = params["contextMenu"] as? [String: Any]
let windowId = params["windowId"] as? Int64
let initialUserScripts = params["initialUserScripts"] as? [[String: Any]]
let pullToRefreshInitialSettings = params["pullToRefreshSettings"] as! [String: Any?]
var userScripts: [UserScript] = []
if let initialUserScripts = initialUserScripts {
for initialUserScript in initialUserScripts {
userScripts.append(UserScript.fromMap(map: initialUserScript, windowId: windowId)!)
}
}
let settings = InAppWebViewSettings()
let _ = settings.parse(settings: initialSettings)
let preWebviewConfiguration = InAppWebView.preWKWebViewConfiguration(settings: settings)
var webView: InAppWebView?
if let wId = windowId, let webViewTransport = plugin.inAppWebViewManager?.windowWebViews[wId] {
webView = webViewTransport.webView
webView!.id = viewId
webView!.plugin = plugin
if let registrar = plugin.registrar {
let channel = FlutterMethodChannel(name: InAppWebView.METHOD_CHANNEL_NAME_PREFIX + String(describing: viewId),
binaryMessenger: registrar.messenger())
webView!.channelDelegate = WebViewChannelDelegate(webView: webView!, channel: channel)
}
webView!.frame = myView!.bounds
webView!.contextMenu = contextMenu
webView!.initialUserScripts = userScripts
} else {
webView = InAppWebView(id: viewId,
plugin: plugin,
frame: myView!.bounds,
configuration: preWebviewConfiguration,
contextMenu: contextMenu,
userScripts: userScripts)
}
let pullToRefreshSettings = PullToRefreshSettings()
let _ = pullToRefreshSettings.parse(settings: pullToRefreshInitialSettings)
let pullToRefreshControl = PullToRefreshControl(plugin: plugin, id: viewId, settings: pullToRefreshSettings)
webView!.pullToRefreshControl = pullToRefreshControl
pullToRefreshControl.delegate = webView!
pullToRefreshControl.prepare()
let findInteractionController = FindInteractionController(
plugin: plugin,
id: viewId, webView: webView!, settings: nil)
webView!.findInteractionController = findInteractionController
findInteractionController.prepare()
webView!.autoresizingMask = [.flexibleWidth, .flexibleHeight]
myView!.autoresizesSubviews = true
myView!.autoresizingMask = [.flexibleWidth, .flexibleHeight]
myView!.addSubview(webView!)
webView!.settings = settings
webView!.prepare()
webView!.windowCreated = true
}
public func webView() -> InAppWebView? {
for subview in myView?.subviews ?? []
{
if let item = subview as? InAppWebView
{
return item
}
}
return nil
}
public func view() -> UIView {
return myView!
}
public func makeInitialLoad(params: NSDictionary) {
guard let webView = webView() else {
return
}
let windowId = params["windowId"] as? Int64
let initialUrlRequest = params["initialUrlRequest"] as? [String: Any?]
let initialFile = params["initialFile"] as? String
let initialData = params["initialData"] as? [String: String?]
if windowId == nil {
if #available(iOS 11.0, *) {
webView.configuration.userContentController.removeAllContentRuleLists()
if let contentBlockers = webView.settings?.contentBlockers, contentBlockers.count > 0 {
do {
let jsonData = try JSONSerialization.data(withJSONObject: contentBlockers, options: [])
let blockRules = String(data: jsonData, encoding: .utf8)
WKContentRuleListStore.default().compileContentRuleList(
forIdentifier: "ContentBlockingRules",
encodedContentRuleList: blockRules) { (contentRuleList, error) in
if let error = error {
print(error.localizedDescription)
return
}
let configuration = webView.configuration
configuration.userContentController.add(contentRuleList!)
self.load(initialUrlRequest: initialUrlRequest, initialFile: initialFile, initialData: initialData)
}
return
} catch {
print(error.localizedDescription)
}
}
}
load(initialUrlRequest: initialUrlRequest, initialFile: initialFile, initialData: initialData)
}
else if windowId != nil {
webView.runWindowBeforeCreatedCallbacks()
}
}
func load(initialUrlRequest: [String:Any?]?, initialFile: String?, initialData: [String: String?]?) {
guard let webView = webView() else {
return
}
if let initialFile = initialFile {
do {
try webView.loadFile(assetFilePath: initialFile)
}
catch let error as NSError {
dump(error)
}
}
else if let initialData = initialData, let data = initialData["data"]!,
let mimeType = initialData["mimeType"]!, let encoding = initialData["encoding"]!,
let baseUrl = URL(string: initialData["baseUrl"]! ?? "about:blank") {
var allowingReadAccessToURL: URL? = nil
if let allowingReadAccessTo = webView.settings?.allowingReadAccessTo, baseUrl.scheme == "file" {
allowingReadAccessToURL = URL(string: allowingReadAccessTo)
if allowingReadAccessToURL?.scheme != "file" {
allowingReadAccessToURL = nil
}
}
webView.loadData(data: data,
mimeType: mimeType,
encoding: encoding,
baseUrl: baseUrl,
allowingReadAccessTo: allowingReadAccessToURL)
}
else if let initialUrlRequest = initialUrlRequest {
let urlRequest = URLRequest.init(fromPluginMap: initialUrlRequest)
var allowingReadAccessToURL: URL? = nil
if let allowingReadAccessTo = webView.settings?.allowingReadAccessTo, let url = urlRequest.url, url.scheme == "file" {
allowingReadAccessToURL = URL(string: allowingReadAccessTo)
if allowingReadAccessToURL?.scheme != "file" {
allowingReadAccessToURL = nil
}
}
webView.loadUrl(urlRequest: urlRequest, allowingReadAccessTo: allowingReadAccessToURL)
}
}
// method added to fix:
// https://github.com/pichillilorenzo/flutter_inappwebview/issues/1837
public func dispose(removeFromSuperview: Bool) {
if keepAliveId == nil {
if let webView = webView() {
webView.dispose()
if removeFromSuperview {
webView.removeFromSuperview()
}
}
if removeFromSuperview {
myView?.removeFromSuperview()
}
myView = nil
}
}
public func dispose() {
dispose(removeFromSuperview: false)
}
deinit {
debugPrint("FlutterWebViewController - dealloc")
dispose()
}
}
@@ -0,0 +1,74 @@
//
// FlutterWebViewFactory.swift
// flutter_inappwebview
//
// Created by Lorenzo on 13/11/18.
//
import Flutter
import Foundation
public class FlutterWebViewFactory: NSObject, FlutterPlatformViewFactory {
static let VIEW_TYPE_ID = "com.pichillilorenzo/flutter_inappwebview"
private var plugin: SwiftFlutterPlugin
init(plugin: SwiftFlutterPlugin) {
self.plugin = plugin
super.init()
}
public func createArgsCodec() -> FlutterMessageCodec & NSObjectProtocol {
return FlutterStandardMessageCodec.sharedInstance()
}
public func create(withFrame frame: CGRect, viewIdentifier viewId: Int64, arguments args: Any?) -> FlutterPlatformView {
let arguments = args as? NSDictionary
var flutterWebView: FlutterWebViewController?
var id: Any = viewId
let keepAliveId = arguments?["keepAliveId"] as? String
let headlessWebViewId = arguments?["headlessWebViewId"] as? String
let preventGestureDelay = arguments?["preventGestureDelay"] as? Bool ?? false
if let headlessWebViewId = headlessWebViewId,
let headlessWebView = plugin.headlessInAppWebViewManager?.webViews[headlessWebViewId],
let platformView = headlessWebView?.disposeAndGetFlutterWebView(withFrame: frame) {
flutterWebView = platformView
flutterWebView?.keepAliveId = keepAliveId
}
if let keepAliveId = keepAliveId,
flutterWebView == nil,
let keepAliveWebView = plugin.inAppWebViewManager?.keepAliveWebViews[keepAliveId] {
flutterWebView = keepAliveWebView
if let view = flutterWebView?.view() {
// remove from parent
view.removeFromSuperview()
}
}
let shouldMakeInitialLoad = flutterWebView == nil
if flutterWebView == nil {
if let keepAliveId = keepAliveId {
id = keepAliveId
}
flutterWebView = FlutterWebViewController(plugin: plugin,
withFrame: frame,
viewIdentifier: id,
params: arguments!)
}
if let keepAliveId = keepAliveId {
plugin.inAppWebViewManager?.keepAliveWebViews[keepAliveId] = flutterWebView!
}
flutterWebView?.webView()?.preventGestureDelay = preventGestureDelay
if shouldMakeInitialLoad {
flutterWebView?.makeInitialLoad(params: arguments!)
}
return flutterWebView!
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,128 @@
//
// InAppWebViewManager.swift
// flutter_inappwebview
//
// Created by Lorenzo Pichilli on 08/12/2019.
//
import Foundation
import WebKit
public class InAppWebViewManager: ChannelDelegate {
static let METHOD_CHANNEL_NAME = "com.pichillilorenzo/flutter_inappwebview_manager"
var plugin: SwiftFlutterPlugin?
var webViewForUserAgent: WKWebView?
var defaultUserAgent: String?
var keepAliveWebViews: [String:FlutterWebViewController?] = [:]
var windowWebViews: [Int64:WebViewTransport] = [:]
var windowAutoincrementId: Int64 = 0
init(plugin: SwiftFlutterPlugin) {
super.init(channel: FlutterMethodChannel(name: InAppWebViewManager.METHOD_CHANNEL_NAME, binaryMessenger: plugin.registrar!.messenger()))
self.plugin = plugin
}
public override func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
let arguments = call.arguments as? NSDictionary
switch call.method {
case "getDefaultUserAgent":
getDefaultUserAgent(completionHandler: { (value) in
result(value)
})
break
case "handlesURLScheme":
let urlScheme = arguments!["urlScheme"] as! String
if #available(iOS 11.0, *) {
result(WKWebView.handlesURLScheme(urlScheme))
} else {
result(false)
}
break
case "disposeKeepAlive":
let keepAliveId = arguments!["keepAliveId"] as! String
disposeKeepAlive(keepAliveId: keepAliveId)
result(true)
break
case "clearAllCache":
let includeDiskFiles = arguments!["includeDiskFiles"] as! Bool
clearAllCache(includeDiskFiles: includeDiskFiles, completionHandler: {
result(true)
})
default:
result(FlutterMethodNotImplemented)
break
}
}
public func getDefaultUserAgent(completionHandler: @escaping (_ value: String?) -> Void) {
if defaultUserAgent == nil {
webViewForUserAgent = WKWebView()
webViewForUserAgent?.evaluateJavaScript("navigator.userAgent") { (value, error) in
if error != nil {
print("Error occurred to get userAgent")
self.webViewForUserAgent = nil
completionHandler(nil)
return
}
if let unwrappedUserAgent = value as? String {
self.defaultUserAgent = unwrappedUserAgent
completionHandler(self.defaultUserAgent)
} else {
print("Failed to get userAgent")
}
self.webViewForUserAgent = nil
}
} else {
completionHandler(defaultUserAgent)
}
}
public func disposeKeepAlive(keepAliveId: String) {
if let flutterWebView = keepAliveWebViews[keepAliveId] as? FlutterWebViewController {
flutterWebView.keepAliveId = nil
flutterWebView.dispose(removeFromSuperview: true)
keepAliveWebViews[keepAliveId] = nil
}
}
public func clearAllCache(includeDiskFiles: Bool, completionHandler: @escaping () -> Void) {
if #available(iOS 9.0, *) {
var websiteDataTypes = Set([WKWebsiteDataTypeMemoryCache])
if includeDiskFiles {
websiteDataTypes.insert(WKWebsiteDataTypeDiskCache)
if #available(iOS 11.3, *) {
websiteDataTypes.insert(WKWebsiteDataTypeFetchCache)
}
websiteDataTypes.insert(WKWebsiteDataTypeOfflineWebApplicationCache)
}
let date = NSDate(timeIntervalSince1970: 0)
WKWebsiteDataStore.default().removeData(ofTypes: websiteDataTypes, modifiedSince: date as Date, completionHandler: completionHandler)
} else {
URLCache.shared.removeAllCachedResponses()
completionHandler()
}
}
public override func dispose() {
super.dispose()
let keepAliveWebViewValues = keepAliveWebViews.values
keepAliveWebViewValues.forEach {(keepAliveWebView: FlutterWebViewController?) in
if let keepAliveId = keepAliveWebView?.keepAliveId {
disposeKeepAlive(keepAliveId: keepAliveId)
}
}
keepAliveWebViews.removeAll()
windowWebViews.removeAll()
webViewForUserAgent = nil
defaultUserAgent = nil
plugin = nil
}
deinit {
dispose()
}
}
@@ -0,0 +1,181 @@
//
// InAppWebViewSettings.swift
// flutter_inappwebview
//
// Created by Lorenzo on 21/10/18.
//
import Foundation
import WebKit
@objcMembers
public class InAppWebViewSettings: ISettings<InAppWebView> {
var gopeedProfileId = ""
var useShouldOverrideUrlLoading = false
var useOnLoadResource = false
var useOnDownloadStart = false
@available(*, deprecated, message: "Use InAppWebViewManager.clearAllCache instead.")
var clearCache = false
var userAgent = ""
var applicationNameForUserAgent = ""
var javaScriptEnabled = true
var javaScriptCanOpenWindowsAutomatically = false
var mediaPlaybackRequiresUserGesture = true
var verticalScrollBarEnabled = true
var horizontalScrollBarEnabled = true
var resourceCustomSchemes: [String] = []
var contentBlockers: [[String: [String : Any]]] = []
var minimumFontSize = 0
var useShouldInterceptAjaxRequest = false
var interceptOnlyAsyncAjaxRequests = true
var useShouldInterceptFetchRequest = false
var incognito = false
var cacheEnabled = true
var transparentBackground = false
var disableVerticalScroll = false
var disableHorizontalScroll = false
var disableContextMenu = false
var supportZoom = true
var allowUniversalAccessFromFileURLs = false
var allowFileAccessFromFileURLs = false
var disallowOverScroll = false
var enableViewportScale = false
var suppressesIncrementalRendering = false
var allowsAirPlayForMediaPlayback = true
var allowsBackForwardNavigationGestures = true
var allowsLinkPreview = true
var ignoresViewportScaleLimits = false
var allowsInlineMediaPlayback = false
var allowsPictureInPictureMediaPlayback = true
var isFraudulentWebsiteWarningEnabled = true
var selectionGranularity = 0
var dataDetectorTypes: [String] = ["NONE"] // WKDataDetectorTypeNone
var preferredContentMode = 0
var sharedCookiesEnabled = false
var automaticallyAdjustsScrollIndicatorInsets = false
var accessibilityIgnoresInvertColors = false
var decelerationRate = "NORMAL" // UIScrollView.DecelerationRate.normal
var alwaysBounceVertical = false
var alwaysBounceHorizontal = false
var scrollsToTop = true
var isPagingEnabled = false
var maximumZoomScale = 1.0
var minimumZoomScale = 1.0
var contentInsetAdjustmentBehavior = 2 // UIScrollView.ContentInsetAdjustmentBehavior.never
var isDirectionalLockEnabled = false
var mediaType: String? = nil
var pageZoom = 1.0
var limitsNavigationsToAppBoundDomains = false
var useOnNavigationResponse = false
var applePayAPIEnabled = false
var allowingReadAccessTo: String? = nil
var disableLongPressContextMenuOnLinks = false
var disableInputAccessoryView = false
var underPageBackgroundColor: String?
var isTextInteractionEnabled = true
var isSiteSpecificQuirksModeEnabled = true
var upgradeKnownHostsToHTTPS = true
var isElementFullscreenEnabled = true
var isFindInteractionEnabled = false
var minimumViewportInset: UIEdgeInsets? = nil
var maximumViewportInset: UIEdgeInsets? = nil
var isInspectable = false
var shouldPrintBackgrounds = false
override init(){
super.init()
}
override func parse(settings: [String: Any?]) -> InAppWebViewSettings {
var settings = settings // re-assing to be able to use removeValue
if let minimumViewportInsetMap = settings["minimumViewportInset"] as? [String : Double] {
minimumViewportInset = UIEdgeInsets.fromMap(map: minimumViewportInsetMap)
settings.removeValue(forKey: "minimumViewportInset")
}
if let maximumViewportInsetMap = settings["maximumViewportInset"] as? [String : Double] {
maximumViewportInset = UIEdgeInsets.fromMap(map: maximumViewportInsetMap)
settings.removeValue(forKey: "maximumViewportInset")
}
let _ = super.parse(settings: settings)
if #available(iOS 13.0, *) {} else {
applePayAPIEnabled = false
}
return self
}
override func getRealSettings(obj: InAppWebView?) -> [String: Any?] {
var realSettings: [String: Any?] = toMap()
if let webView = obj {
let configuration = webView.configuration
if #available(iOS 9.0, *) {
realSettings["userAgent"] = webView.customUserAgent
realSettings["applicationNameForUserAgent"] = configuration.applicationNameForUserAgent
realSettings["allowsAirPlayForMediaPlayback"] = configuration.allowsAirPlayForMediaPlayback
realSettings["allowsLinkPreview"] = webView.allowsLinkPreview
realSettings["allowsPictureInPictureMediaPlayback"] = configuration.allowsPictureInPictureMediaPlayback
}
realSettings["javaScriptCanOpenWindowsAutomatically"] = configuration.preferences.javaScriptCanOpenWindowsAutomatically
if #available(iOS 10.0, *) {
realSettings["mediaPlaybackRequiresUserGesture"] = configuration.mediaTypesRequiringUserActionForPlayback == .all
realSettings["ignoresViewportScaleLimits"] = configuration.ignoresViewportScaleLimits
realSettings["dataDetectorTypes"] = Util.getDataDetectorTypeString(type: configuration.dataDetectorTypes)
} else {
realSettings["mediaPlaybackRequiresUserGesture"] = configuration.mediaPlaybackRequiresUserAction
}
realSettings["minimumFontSize"] = Int(configuration.preferences.minimumFontSize)
realSettings["suppressesIncrementalRendering"] = configuration.suppressesIncrementalRendering
realSettings["allowsBackForwardNavigationGestures"] = webView.allowsBackForwardNavigationGestures
realSettings["allowsInlineMediaPlayback"] = configuration.allowsInlineMediaPlayback
if #available(iOS 13.0, *) {
realSettings["isFraudulentWebsiteWarningEnabled"] = configuration.preferences.isFraudulentWebsiteWarningEnabled
realSettings["preferredContentMode"] = configuration.defaultWebpagePreferences.preferredContentMode.rawValue
realSettings["automaticallyAdjustsScrollIndicatorInsets"] = webView.scrollView.automaticallyAdjustsScrollIndicatorInsets
}
realSettings["selectionGranularity"] = configuration.selectionGranularity.rawValue
if #available(iOS 11.0, *) {
realSettings["accessibilityIgnoresInvertColors"] = webView.accessibilityIgnoresInvertColors
realSettings["contentInsetAdjustmentBehavior"] = webView.scrollView.contentInsetAdjustmentBehavior.rawValue
}
realSettings["decelerationRate"] = Util.getDecelerationRateString(type: webView.scrollView.decelerationRate)
realSettings["alwaysBounceVertical"] = webView.scrollView.alwaysBounceVertical
realSettings["alwaysBounceHorizontal"] = webView.scrollView.alwaysBounceHorizontal
realSettings["scrollsToTop"] = webView.scrollView.scrollsToTop
realSettings["isPagingEnabled"] = webView.scrollView.isPagingEnabled
realSettings["maximumZoomScale"] = webView.scrollView.maximumZoomScale
realSettings["minimumZoomScale"] = webView.scrollView.minimumZoomScale
realSettings["allowUniversalAccessFromFileURLs"] = configuration.value(forKey: "allowUniversalAccessFromFileURLs")
realSettings["allowFileAccessFromFileURLs"] = configuration.preferences.value(forKey: "allowFileAccessFromFileURLs")
realSettings["isDirectionalLockEnabled"] = webView.scrollView.isDirectionalLockEnabled
realSettings["javaScriptEnabled"] = configuration.preferences.javaScriptEnabled
if #available(iOS 14.0, *) {
realSettings["mediaType"] = webView.mediaType
realSettings["pageZoom"] = Float(webView.pageZoom)
realSettings["limitsNavigationsToAppBoundDomains"] = configuration.limitsNavigationsToAppBoundDomains
realSettings["javaScriptEnabled"] = configuration.defaultWebpagePreferences.allowsContentJavaScript
}
if #available(iOS 15.0, *) {
realSettings["isTextInteractionEnabled"] = configuration.preferences.isTextInteractionEnabled
realSettings["upgradeKnownHostsToHTTPS"] = configuration.upgradeKnownHostsToHTTPS
realSettings["underPageBackgroundColor"] = webView.underPageBackgroundColor.hexString
}
if #available(iOS 15.4, *) {
realSettings["isSiteSpecificQuirksModeEnabled"] = configuration.preferences.isSiteSpecificQuirksModeEnabled
realSettings["isElementFullscreenEnabled"] = configuration.preferences.isElementFullscreenEnabled
}
if #available(iOS 15.5, *) {
realSettings["minimumViewportInset"] = webView.minimumViewportInset.toMap()
realSettings["maximumViewportInset"] = webView.maximumViewportInset.toMap()
}
if #available(iOS 16.0, *) {
realSettings["isFindInteractionEnabled"] = webView.isFindInteractionEnabled
}
if #available(iOS 16.4, *) {
realSettings["isInspectable"] = webView.isInspectable
realSettings["shouldPrintBackgrounds"] = configuration.preferences.shouldPrintBackgrounds
}
}
return realSettings
}
}
@@ -0,0 +1,79 @@
//
// WebMessageChannel.swift
// flutter_inappwebview
//
// Created by Lorenzo Pichilli on 10/03/21.
//
import Foundation
public class WebMessageChannel: FlutterMethodCallDelegate {
static var METHOD_CHANNEL_NAME_PREFIX = "com.pichillilorenzo/flutter_inappwebview_web_message_channel_"
var id: String
var plugin: SwiftFlutterPlugin?
var channelDelegate: WebMessageChannelChannelDelegate?
weak var webView: InAppWebView?
var ports: [WebMessagePort] = []
public init(plugin: SwiftFlutterPlugin, id: String) {
self.id = id
self.plugin = plugin
super.init()
if let registrar = plugin.registrar {
let channel = FlutterMethodChannel(name: WebMessageChannel.METHOD_CHANNEL_NAME_PREFIX + id,
binaryMessenger: registrar.messenger())
self.channelDelegate = WebMessageChannelChannelDelegate(webMessageChannel: self, channel: channel)
}
self.ports = [
WebMessagePort(name: "port1", index: 0, webMessageChannelId: self.id, webMessageChannel: self),
WebMessagePort(name: "port2", index: 1, webMessageChannelId: self.id, webMessageChannel: self)
]
}
public func initJsInstance(webView: InAppWebView, completionHandler: ((WebMessageChannel?) -> Void)? = nil) {
self.webView = webView
if let webView = self.webView {
webView.evaluateJavascript(source: """
(function() {
\(WEB_MESSAGE_CHANNELS_VARIABLE_NAME)["\(id)"] = new MessageChannel();
})();
""") { (_) in
completionHandler?(self)
}
} else {
completionHandler?(nil)
}
}
public func toMap() -> [String:Any?] {
return [
"id": id
]
}
public func dispose() {
channelDelegate?.dispose()
channelDelegate = nil
for port in ports {
port.dispose()
}
ports.removeAll()
webView?.evaluateJavascript(source: """
(function() {
var webMessageChannel = \(WEB_MESSAGE_CHANNELS_VARIABLE_NAME)["\(id)"];
if (webMessageChannel != null) {
webMessageChannel.port1.close();
webMessageChannel.port2.close();
delete \(WEB_MESSAGE_CHANNELS_VARIABLE_NAME)["\(id)"];
}
})();
""")
webView = nil
plugin = nil
}
deinit {
debugPrint("WebMessageChannel - dealloc")
dispose()
}
}
@@ -0,0 +1,102 @@
//
// WebMessageChannelChannelDelegate.swift
// flutter_inappwebview
//
// Created by Lorenzo Pichilli on 07/05/22.
//
import Foundation
public class WebMessageChannelChannelDelegate: ChannelDelegate {
private weak var webMessageChannel: WebMessageChannel?
public init(webMessageChannel: WebMessageChannel, channel: FlutterMethodChannel) {
super.init(channel: channel)
self.webMessageChannel = webMessageChannel
}
public override func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
let arguments = call.arguments as? NSDictionary
switch call.method {
case "setWebMessageCallback":
if let _ = webMessageChannel?.webView, let ports = webMessageChannel?.ports, ports.count > 0 {
let index = arguments!["index"] as! Int
let port = ports[index]
do {
try port.setWebMessageCallback { (_) in
result(true)
}
} catch let error as NSError {
result(FlutterError(code: "WebMessageChannel", message: error.domain, details: nil))
}
} else {
result(true)
}
break
case "postMessage":
if let webView = webMessageChannel?.webView, let ports = webMessageChannel?.ports, ports.count > 0 {
let index = arguments!["index"] as! Int
let port = ports[index]
let message = WebMessage.fromMap(map: arguments!["message"] as! [String: Any?])
var ports: [WebMessagePort] = []
if let notConnectedPorts = message.ports {
for notConnectedPort in notConnectedPorts {
if let webMessageChannel = webView.webMessageChannels[notConnectedPort.webMessageChannelId] {
ports.append(webMessageChannel.ports[Int(notConnectedPort.index)])
}
}
}
message.ports = ports
do {
try port.postMessage(message: message) { (_) in
result(true)
}
} catch let error as NSError {
result(FlutterError(code: "WebMessageChannel", message: error.domain, details: nil))
}
} else {
result(true)
}
break
case "close":
if let _ = webMessageChannel?.webView, let ports = webMessageChannel?.ports, ports.count > 0 {
let index = arguments!["index"] as! Int
let port = ports[index]
do {
try port.close { (_) in
result(true)
}
} catch let error as NSError {
result(FlutterError(code: "WebMessageChannel", message: error.domain, details: nil))
}
} else {
result(true)
}
break
default:
result(FlutterMethodNotImplemented)
break
}
}
public func onMessage(index: Int64, message: WebMessage?) {
let arguments: [String:Any?] = [
"index": index,
"message": message?.toMap()
]
channel?.invokeMethod("onMessage", arguments: arguments)
}
public override func dispose() {
super.dispose()
webMessageChannel = nil
}
deinit {
dispose()
}
}
@@ -0,0 +1,192 @@
//
// WebMessageListener.swift
// flutter_inappwebview
//
// Created by Lorenzo Pichilli on 10/03/21.
//
import Foundation
import WebKit
public class WebMessageListener: FlutterMethodCallDelegate {
static var METHOD_CHANNEL_NAME_PREFIX = "com.pichillilorenzo/flutter_inappwebview_web_message_listener_"
var id: String
var jsObjectName: String
var allowedOriginRules: Set<String>
var channelDelegate: WebMessageListenerChannelDelegate?
weak var webView: InAppWebView?
var plugin: SwiftFlutterPlugin?
public init(plugin: SwiftFlutterPlugin, id: String, jsObjectName: String, allowedOriginRules: Set<String>) {
self.id = id
self.plugin = plugin
self.jsObjectName = jsObjectName
self.allowedOriginRules = allowedOriginRules
super.init()
if let registrar = plugin.registrar {
let channel = FlutterMethodChannel(name: WebMessageListener.METHOD_CHANNEL_NAME_PREFIX + self.id + "_" + self.jsObjectName,
binaryMessenger: registrar.messenger())
self.channelDelegate = WebMessageListenerChannelDelegate(webMessageListener: self, channel: channel)
}
}
public func assertOriginRulesValid() throws {
for (index, originRule) in allowedOriginRules.enumerated() {
if originRule.isEmpty {
throw NSError(domain: "allowedOriginRules[\(index)] is empty", code: 0)
}
if originRule == "*" {
continue
}
if let url = URL(string: originRule) {
guard let scheme = url.scheme else {
throw NSError(domain: "allowedOriginRules \(originRule) is invalid", code: 0)
}
if scheme == "http" || scheme == "https", url.host == nil || url.host!.isEmpty {
throw NSError(domain: "allowedOriginRules \(originRule) is invalid", code: 0)
}
if scheme != "http", scheme != "https", url.host != nil || url.port != nil {
throw NSError(domain: "allowedOriginRules \(originRule) is invalid", code: 0)
}
if url.host == nil || url.host!.isEmpty, url.port != nil {
throw NSError(domain: "allowedOriginRules \(originRule) is invalid", code: 0)
}
if !url.path.isEmpty {
throw NSError(domain: "allowedOriginRules \(originRule) is invalid", code: 0)
}
if let hostname = url.host {
if let firstIndex = hostname.firstIndex(of: "*") {
let distance = hostname.distance(from: hostname.startIndex, to: firstIndex)
if distance != 0 || (distance == 0 && hostname.prefix(2) != "*.") {
throw NSError(domain: "allowedOriginRules \(originRule) is invalid", code: 0)
}
}
if hostname.hasPrefix("[") {
if !hostname.hasSuffix("]") {
throw NSError(domain: "allowedOriginRules \(originRule) is invalid", code: 0)
}
let fromIndex = hostname.index(hostname.startIndex, offsetBy: 1)
let toIndex = hostname.index(hostname.startIndex, offsetBy: hostname.count - 1)
let indexRange = Range<String.Index>(uncheckedBounds: (lower: fromIndex, upper: toIndex))
let ipv6 = String(hostname[indexRange])
if !Util.isIPv6(address: ipv6) {
throw NSError(domain: "allowedOriginRules \(originRule) is invalid", code: 0)
}
}
}
} else {
throw NSError(domain: "allowedOriginRules \(originRule) is invalid", code: 0)
}
}
}
public func initJsInstance(webView: InAppWebView) {
self.webView = webView
if let webView = self.webView {
let jsObjectNameEscaped = jsObjectName.replacingOccurrences(of: "\'", with: "\\'")
let allowedOriginRulesString = allowedOriginRules.map { (allowedOriginRule) -> String in
if allowedOriginRule == "*" {
return "'*'"
}
let rule = URL(string: allowedOriginRule)!
let host = rule.host != nil ? "'" + rule.host!.replacingOccurrences(of: "\'", with: "\\'") + "'" : "null"
return """
{scheme: '\(rule.scheme!)', host: \(host), port: \(rule.port != nil ? String(rule.port!) : "null")}
"""
}.joined(separator: ", ")
let source = """
(function() {
var allowedOriginRules = [\(allowedOriginRulesString)];
var isPageBlank = window.location.href === "about:blank";
var scheme = !isPageBlank ? window.location.protocol.replace(":", "") : null;
var host = !isPageBlank ? window.location.hostname : null;
var port = !isPageBlank ? window.location.port : null;
if (window.\(JAVASCRIPT_BRIDGE_NAME)._isOriginAllowed(allowedOriginRules, scheme, host, port)) {
window['\(jsObjectNameEscaped)'] = new FlutterInAppWebViewWebMessageListener('\(jsObjectNameEscaped)');
}
})();
"""
webView.configuration.userContentController.addPluginScript(PluginScript(
groupName: "WebMessageListener-" + id + "-" + jsObjectName,
source: source,
injectionTime: .atDocumentStart,
forMainFrameOnly: false,
requiredInAllContentWorlds: false,
messageHandlerNames: ["onWebMessageListenerPostMessageReceived"]
))
webView.configuration.userContentController.sync(scriptMessageHandler: webView)
}
}
public static func fromMap(plugin: SwiftFlutterPlugin, map: [String:Any?]?) -> WebMessageListener? {
guard let map = map else {
return nil
}
return WebMessageListener(
plugin: plugin,
id: map["id"] as! String,
jsObjectName: map["jsObjectName"] as! String,
allowedOriginRules: Set(map["allowedOriginRules"] as! [String])
)
}
public func isOriginAllowed(scheme: String?, host: String?, port: Int?) -> Bool {
for allowedOriginRule in allowedOriginRules {
if allowedOriginRule == "*" {
return true
}
if scheme == nil || scheme!.isEmpty {
continue
}
if scheme == nil || scheme!.isEmpty, host == nil || host!.isEmpty, port == nil || port == 0 {
continue
}
if let rule = URL(string: allowedOriginRule) {
let rulePort = rule.port == nil || rule.port == 0 ? (rule.scheme == "https" ? 443 : 80) : rule.port!
let currentPort = port == nil || port == 0 ? (scheme == "https" ? 443 : 80) : port!
var IPv6: String? = nil
if let hostname = rule.host, hostname.hasPrefix("[") {
let fromIndex = hostname.index(hostname.startIndex, offsetBy: 1)
let toIndex = hostname.index(hostname.startIndex, offsetBy: hostname.count - 1)
let indexRange = Range<String.Index>(uncheckedBounds: (lower: fromIndex, upper: toIndex))
do {
IPv6 = try Util.normalizeIPv6(address: String(hostname[indexRange]))
} catch {}
}
var hostIPv6: String? = nil
if let host = host, Util.isIPv6(address: host) {
do {
hostIPv6 = try Util.normalizeIPv6(address: host)
} catch {}
}
let schemeAllowed = scheme != nil && !scheme!.isEmpty && scheme == rule.scheme
let hostAllowed = rule.host == nil ||
rule.host!.isEmpty ||
host == rule.host ||
(rule.host!.hasPrefix("*") && host != nil && host!.hasSuffix(rule.host!.split(separator: "*", omittingEmptySubsequences: false)[1])) ||
(hostIPv6 != nil && IPv6 != nil && hostIPv6 == IPv6)
let portAllowed = rulePort == currentPort
if schemeAllowed, hostAllowed, portAllowed {
return true
}
}
}
return false
}
public func dispose() {
channelDelegate?.dispose()
channelDelegate = nil
webView = nil
plugin = nil
}
deinit {
debugPrint("WebMessageListener - dealloc")
dispose()
}
}
@@ -0,0 +1,72 @@
//
// WebMessageListenerChannelDelegate.swift
// flutter_inappwebview
//
// Created by Lorenzo Pichilli on 07/05/22.
//
import Foundation
public class WebMessageListenerChannelDelegate: ChannelDelegate {
private weak var webMessageListener: WebMessageListener?
public init(webMessageListener: WebMessageListener, channel: FlutterMethodChannel) {
super.init(channel: channel)
self.webMessageListener = webMessageListener
}
public override func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
let arguments = call.arguments as? NSDictionary
switch call.method {
case "postMessage":
if let webView = webMessageListener?.webView, let jsObjectName = webMessageListener?.jsObjectName {
let jsObjectNameEscaped = jsObjectName.replacingOccurrences(of: "\'", with: "\\'")
let message = WebMessage.fromMap(map: arguments!["message"] as! [String: Any?])
let source = """
(function() {
var webMessageListener = window['\(jsObjectNameEscaped)'];
if (webMessageListener != null) {
var event = {data: \(message.jsData)};
if (webMessageListener.onmessage != null) {
webMessageListener.onmessage(event);
}
for (var listener of webMessageListener.listeners) {
listener(event);
}
}
})();
"""
webView.evaluateJavascript(source: source) { (_) in
result(true)
}
} else {
result(true)
}
break
default:
result(FlutterMethodNotImplemented)
break
}
}
public func onPostMessage(message: WebMessage?, sourceOrigin: URL?, isMainFrame: Bool) {
let arguments: [String:Any?] = [
"message": message?.toMap(),
"sourceOrigin": sourceOrigin?.absoluteString,
"isMainFrame": isMainFrame
]
channel?.invokeMethod("onPostMessage", arguments: arguments)
}
public override func dispose() {
super.dispose()
webMessageListener = nil
}
deinit {
dispose()
}
}
@@ -0,0 +1,93 @@
//
// WebViewChannelDelegateMethods.swift
// flutter_inappwebview
//
// Created by Lorenzo Pichilli on 08/10/22.
//
import Foundation
public enum WebViewChannelDelegateMethods: String {
case getUrl = "getUrl"
case getTitle = "getTitle"
case getProgress = "getProgress"
case loadUrl = "loadUrl"
case postUrl = "postUrl"
case loadData = "loadData"
case loadFile = "loadFile"
case evaluateJavascript = "evaluateJavascript"
case injectJavascriptFileFromUrl = "injectJavascriptFileFromUrl"
case injectCSSCode = "injectCSSCode"
case injectCSSFileFromUrl = "injectCSSFileFromUrl"
case reload = "reload"
case goBack = "goBack"
case canGoBack = "canGoBack"
case goForward = "goForward"
case canGoForward = "canGoForward"
case goBackOrForward = "goBackOrForward"
case canGoBackOrForward = "canGoBackOrForward"
case stopLoading = "stopLoading"
case isLoading = "isLoading"
case takeScreenshot = "takeScreenshot"
case setSettings = "setSettings"
case getSettings = "getSettings"
case close = "close"
case show = "show"
case hide = "hide"
case isHidden = "isHidden"
case getCopyBackForwardList = "getCopyBackForwardList"
@available(*, deprecated, message: "Use FindInteractionController.findAll instead.")
case findAll = "findAll"
@available(*, deprecated, message: "Use FindInteractionController.findNext instead.")
case findNext = "findNext"
@available(*, deprecated, message: "Use FindInteractionController.clearMatches instead.")
case clearMatches = "clearMatches"
@available(*, deprecated, message: "Use InAppWebViewManager.clearAllCache instead.")
case clearCache = "clearCache"
case scrollTo = "scrollTo"
case scrollBy = "scrollBy"
case pauseTimers = "pauseTimers"
case resumeTimers = "resumeTimers"
case printCurrentPage = "printCurrentPage"
case getContentHeight = "getContentHeight"
case getContentWidth = "getContentWidth"
case zoomBy = "zoomBy"
case reloadFromOrigin = "reloadFromOrigin"
case getOriginalUrl = "getOriginalUrl"
case getZoomScale = "getZoomScale"
case hasOnlySecureContent = "hasOnlySecureContent"
case getSelectedText = "getSelectedText"
case getHitTestResult = "getHitTestResult"
case clearFocus = "clearFocus"
case setContextMenu = "setContextMenu"
case requestFocusNodeHref = "requestFocusNodeHref"
case requestImageRef = "requestImageRef"
case getScrollX = "getScrollX"
case getScrollY = "getScrollY"
case getCertificate = "getCertificate"
case addUserScript = "addUserScript"
case removeUserScript = "removeUserScript"
case removeUserScriptsByGroupName = "removeUserScriptsByGroupName"
case removeAllUserScripts = "removeAllUserScripts"
case callAsyncJavaScript = "callAsyncJavaScript"
case createPdf = "createPdf"
case createWebArchiveData = "createWebArchiveData"
case saveWebArchive = "saveWebArchive"
case isSecureContext = "isSecureContext"
case createWebMessageChannel = "createWebMessageChannel"
case postWebMessage = "postWebMessage"
case addWebMessageListener = "addWebMessageListener"
case canScrollVertically = "canScrollVertically"
case canScrollHorizontally = "canScrollHorizontally"
case pauseAllMediaPlayback = "pauseAllMediaPlayback"
case setAllMediaPlaybackSuspended = "setAllMediaPlaybackSuspended"
case closeAllMediaPresentations = "closeAllMediaPresentations"
case requestMediaPlaybackState = "requestMediaPlaybackState"
case getMetaThemeColor = "getMetaThemeColor"
case isInFullscreen = "isInFullscreen"
case getCameraCaptureState = "getCameraCaptureState"
case setCameraCaptureState = "setCameraCaptureState"
case getMicrophoneCaptureState = "getMicrophoneCaptureState"
case setMicrophoneCaptureState = "setMicrophoneCaptureState"
case loadSimulatedRequest = "loadSimulatedRequest"
}
@@ -0,0 +1,23 @@
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
#import <Flutter/Flutter.h>
@interface InAppWebViewFlutterPlugin : NSObject<FlutterPlugin>
+ (void)registerWithRegistrar:(nonnull NSObject<FlutterPluginRegistrar> *)registrar;
@end
@@ -0,0 +1,32 @@
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
#import "InAppWebViewFlutterPlugin.h"
#if __has_include(<flutter_inappwebview_ios/flutter_inappwebview_ios-Swift.h>)
#import <flutter_inappwebview_ios/flutter_inappwebview_ios-Swift.h>
#else
// Support project import fallback if the generated compatibility header
// is not copied when this plugin is created as a library.
// https://forums.swift.org/t/swift-static-libraries-dont-copy-generated-objective-c-header/19816
#import "flutter_inappwebview_ios-Swift.h"
#endif
@implementation InAppWebViewFlutterPlugin : NSObject
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
[SwiftFlutterPlugin registerWithRegistrar:registrar];
}
@end
@@ -0,0 +1,25 @@
//
// LeakAvoider.swift
// flutter_inappwebview
//
// Created by Lorenzo Pichilli on 15/12/2019.
//
import Foundation
public class LeakAvoider: NSObject {
weak var delegate : FlutterMethodCallDelegate?
init(delegate: FlutterMethodCallDelegate) {
super.init()
self.delegate = delegate
}
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
self.delegate?.handle(call, result: result)
}
deinit {
debugPrint("LeakAvoider - dealloc")
}
}
@@ -0,0 +1,314 @@
//
// MyCookieManager.swift
// flutter_inappwebview
//
// Created by Lorenzo on 26/10/18.
//
import Foundation
import WebKit
@available(iOS 11.0, *)
public class MyCookieManager: ChannelDelegate {
static let METHOD_CHANNEL_NAME = "com.pichillilorenzo/flutter_inappwebview_cookiemanager"
static let httpCookieStore = WKWebsiteDataStore.default().httpCookieStore
private var plugin: SwiftFlutterPlugin?
init(plugin: SwiftFlutterPlugin) {
super.init(channel: FlutterMethodChannel(name: MyCookieManager.METHOD_CHANNEL_NAME, binaryMessenger: plugin.registrar!.messenger()))
self.plugin = plugin
}
public override func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
let arguments = call.arguments as? NSDictionary
if call.method == "gopeed.prepareProfile" {
GopeedProfiles.prepare(arguments: arguments, result: result)
return
}
let profileID = arguments?["gopeedProfileId"] as? String ?? ""
let selectedStore = GopeedProfiles.store(profileID)
if !profileID.isEmpty && selectedStore == nil {
result(FlutterError(code: "UNAVAILABLE", message: "WebView profile is not initialized", details: nil))
return
}
let cookieStore = (selectedStore ?? WKWebsiteDataStore.default()).httpCookieStore
switch call.method {
case "setCookie":
let url = arguments!["url"] as! String
let name = arguments!["name"] as! String
let value = arguments!["value"] as! String
let path = arguments!["path"] as! String
var expiresDate: Int64?
if let expiresDateString = arguments!["expiresDate"] as? String {
expiresDate = Int64(expiresDateString)
}
let maxAge = arguments!["maxAge"] as? Int64
let isSecure = arguments!["isSecure"] as? Bool
let isHttpOnly = arguments!["isHttpOnly"] as? Bool
let sameSite = arguments!["sameSite"] as? String
let domain = arguments!["domain"] as? String
MyCookieManager.setCookie(url: url,
name: name,
value: value,
path: path,
domain: domain,
expiresDate: expiresDate,
maxAge: maxAge,
isSecure: isSecure,
isHttpOnly: isHttpOnly,
sameSite: sameSite,
result: result, cookieStore: cookieStore)
break
case "getCookies":
let url = arguments!["url"] as! String
MyCookieManager.getCookies(url: url, result: result, cookieStore: cookieStore)
break
case "getAllCookies":
MyCookieManager.getAllCookies(result: result, cookieStore: cookieStore)
break
case "deleteCookie":
let url = arguments!["url"] as! String
let name = arguments!["name"] as! String
let path = arguments!["path"] as! String
let domain = arguments!["domain"] as? String
MyCookieManager.deleteCookie(url: url, name: name, path: path, domain: domain, result: result, cookieStore: cookieStore)
break
case "deleteCookies":
let url = arguments!["url"] as! String
let path = arguments!["path"] as! String
let domain = arguments!["domain"] as? String
MyCookieManager.deleteCookies(url: url, path: path, domain: domain, result: result, cookieStore: cookieStore)
break
case "deleteAllCookies":
MyCookieManager.deleteAllCookies(result: result, cookieStore: cookieStore)
break
default:
result(FlutterMethodNotImplemented)
break
}
}
public static func setCookie(url: String,
name: String,
value: String,
path: String,
domain: String?,
expiresDate: Int64?,
maxAge: Int64?,
isSecure: Bool?,
isHttpOnly: Bool?,
sameSite: String?,
result: @escaping FlutterResult, cookieStore: WKHTTPCookieStore = WKWebsiteDataStore.default().httpCookieStore) {
var properties: [HTTPCookiePropertyKey: Any] = [:]
properties[.originURL] = url
properties[.name] = name
properties[.value] = value
properties[.path] = path
if domain != nil {
properties[.domain] = domain
}
if expiresDate != nil {
// convert from milliseconds
properties[.expires] = Date(timeIntervalSince1970: TimeInterval(Double(expiresDate!)/1000))
}
if maxAge != nil {
properties[.maximumAge] = String(maxAge!)
}
if isSecure != nil && isSecure! {
properties[.secure] = "TRUE"
}
if isHttpOnly != nil && isHttpOnly! {
properties[.init("HttpOnly")] = "YES"
}
if sameSite != nil {
if #available(iOS 13.0, *) {
var sameSiteValue = HTTPCookieStringPolicy(rawValue: "None")
switch sameSite {
case "Lax":
sameSiteValue = HTTPCookieStringPolicy.sameSiteLax
case "Strict":
sameSiteValue = HTTPCookieStringPolicy.sameSiteStrict
default:
break
}
properties[.sameSitePolicy] = sameSiteValue
} else {
properties[.init("SameSite")] = sameSite
}
}
if let cookie = HTTPCookie(properties: properties) {
cookieStore.setCookie(cookie, completionHandler: {() in
result(true)
})
} else {
result(false)
}
}
public static func getCookies(url: String, result: @escaping FlutterResult, cookieStore: WKHTTPCookieStore = WKWebsiteDataStore.default().httpCookieStore) {
var cookieList: [[String: Any?]] = []
if let urlHost = URL(string: url)?.host {
cookieStore.getAllCookies { (cookies) in
for cookie in cookies {
if urlHost.hasSuffix(cookie.domain) || ".\(urlHost)".hasSuffix(cookie.domain) {
var sameSite: String? = nil
if #available(iOS 13.0, *) {
if let sameSiteValue = cookie.sameSitePolicy?.rawValue {
sameSite = sameSiteValue.prefix(1).capitalized + sameSiteValue.dropFirst()
}
}
var expiresDateTimestamp: Int64 = -1
if let expiresDate = cookie.expiresDate?.timeIntervalSince1970 {
// convert to milliseconds
expiresDateTimestamp = Int64(expiresDate * 1000)
}
cookieList.append([
"name": cookie.name,
"value": cookie.value,
"expiresDate": expiresDateTimestamp != -1 ? expiresDateTimestamp : nil,
"isSessionOnly": cookie.isSessionOnly,
"domain": cookie.domain,
"sameSite": sameSite,
"isSecure": cookie.isSecure,
"isHttpOnly": cookie.isHTTPOnly,
"path": cookie.path,
])
}
}
result(cookieList)
}
return
} else {
print("Cannot get WebView cookies. No HOST found for URL: \(url)")
}
result(cookieList)
}
public static func getAllCookies(result: @escaping FlutterResult, cookieStore: WKHTTPCookieStore = WKWebsiteDataStore.default().httpCookieStore) {
var cookieList: [[String: Any?]] = []
cookieStore.getAllCookies { (cookies) in
for cookie in cookies {
var sameSite: String? = nil
if #available(iOS 13.0, *) {
if let sameSiteValue = cookie.sameSitePolicy?.rawValue {
sameSite = sameSiteValue.prefix(1).capitalized + sameSiteValue.dropFirst()
}
}
var expiresDateTimestamp: Int64 = -1
if let expiresDate = cookie.expiresDate?.timeIntervalSince1970 {
// convert to milliseconds
expiresDateTimestamp = Int64(expiresDate * 1000)
}
cookieList.append([
"name": cookie.name,
"value": cookie.value,
"expiresDate": expiresDateTimestamp != -1 ? expiresDateTimestamp : nil,
"isSessionOnly": cookie.isSessionOnly,
"domain": cookie.domain,
"sameSite": sameSite,
"isSecure": cookie.isSecure,
"isHttpOnly": cookie.isHTTPOnly,
"path": cookie.path,
])
}
result(cookieList)
}
}
public static func deleteCookie(url: String, name: String, path: String, domain: String?, result: @escaping FlutterResult, cookieStore: WKHTTPCookieStore = WKWebsiteDataStore.default().httpCookieStore) {
var domain = domain
cookieStore.getAllCookies { (cookies) in
for cookie in cookies {
var originURL = url
if cookie.properties![.originURL] is String {
originURL = cookie.properties![.originURL] as! String
}
else if cookie.properties![.originURL] is URL {
originURL = (cookie.properties![.originURL] as! URL).absoluteString
}
if domain == nil, let domainUrl = URL(string: originURL) {
if #available(iOS 16.0, *) {
domain = domainUrl.host()
} else {
domain = domainUrl.host
}
}
if let domain = domain, cookie.domain == domain, cookie.name == name, cookie.path == path {
cookieStore.delete(cookie, completionHandler: {
result(true)
})
return
}
}
result(false)
}
}
public static func deleteCookies(url: String, path: String, domain: String?, result: @escaping FlutterResult, cookieStore: WKHTTPCookieStore = WKWebsiteDataStore.default().httpCookieStore) {
var domain = domain
let dispatchGroup = DispatchGroup()
cookieStore.getAllCookies { (cookies) in
for cookie in cookies {
var originURL = url
if cookie.properties![.originURL] is String {
originURL = cookie.properties![.originURL] as! String
}
else if cookie.properties![.originURL] is URL {
originURL = (cookie.properties![.originURL] as! URL).absoluteString
}
if domain == nil, let domainUrl = URL(string: originURL) {
if #available(iOS 16.0, *) {
domain = domainUrl.host()
} else {
domain = domainUrl.host
}
}
if let domain = domain, cookie.domain == domain, cookie.path == path {
dispatchGroup.enter()
cookieStore.delete(cookie) {
dispatchGroup.leave()
}
}
}
dispatchGroup.notify(queue: .main) {
result(true)
}
}
}
public static func deleteAllCookies(result: @escaping FlutterResult, cookieStore: WKHTTPCookieStore = WKWebsiteDataStore.default().httpCookieStore) {
cookieStore.getAllCookies { cookies in
let group = DispatchGroup()
for cookie in cookies {
group.enter()
cookieStore.delete(cookie) { group.leave() }
}
group.notify(queue: .main) { result(true) }
}
}
public override func dispose() {
super.dispose()
plugin = nil
}
deinit {
dispose()
}
}
@@ -0,0 +1,96 @@
//
// MyWebStorageManager.swift
// connectivity
//
// Created by Lorenzo Pichilli on 16/12/2019.
//
import Foundation
import WebKit
@available(iOS 9.0, *)
public class MyWebStorageManager: ChannelDelegate {
static let METHOD_CHANNEL_NAME = "com.pichillilorenzo/flutter_inappwebview_webstoragemanager"
static let websiteDataStore = WKWebsiteDataStore.default()
private var plugin: SwiftFlutterPlugin?
init(plugin: SwiftFlutterPlugin) {
super.init(channel: FlutterMethodChannel(name: MyWebStorageManager.METHOD_CHANNEL_NAME, binaryMessenger: plugin.registrar!.messenger()))
self.plugin = plugin
}
public override func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
let arguments = call.arguments as? NSDictionary
switch call.method {
case "fetchDataRecords":
let dataTypes = Set(arguments!["dataTypes"] as! [String])
MyWebStorageManager.fetchDataRecords(dataTypes: dataTypes, result: result)
break
case "removeDataFor":
let dataTypes = Set(arguments!["dataTypes"] as! [String])
let recordList = arguments!["recordList"] as! [[String: Any?]]
MyWebStorageManager.removeDataFor(dataTypes: dataTypes, recordList: recordList, result: result)
break
case "removeDataModifiedSince":
let dataTypes = Set(arguments!["dataTypes"] as! [String])
let timestamp = arguments!["timestamp"] as! Int64
MyWebStorageManager.removeDataModifiedSince(dataTypes: dataTypes, timestamp: timestamp, result: result)
break
default:
result(FlutterMethodNotImplemented)
break
}
}
public static func fetchDataRecords(dataTypes: Set<String>, result: @escaping FlutterResult) {
var recordList: [[String: Any?]] = []
MyWebStorageManager.websiteDataStore.fetchDataRecords(ofTypes: dataTypes) { (data) in
for record in data {
recordList.append([
"displayName": record.displayName,
"dataTypes": record.dataTypes.map({ (dataType) -> String in
return dataType
})
])
}
result(recordList)
}
}
public static func removeDataFor(dataTypes: Set<String>, recordList: [[String: Any?]], result: @escaping FlutterResult) {
var records: [WKWebsiteDataRecord] = []
MyWebStorageManager.websiteDataStore.fetchDataRecords(ofTypes: dataTypes) { (data) in
for record in data {
for r in recordList {
let displayName = r["displayName"] as! String
if (record.displayName == displayName) {
records.append(record)
break
}
}
}
MyWebStorageManager.websiteDataStore.removeData(ofTypes: dataTypes, for: records) {
result(true)
}
}
}
public static func removeDataModifiedSince(dataTypes: Set<String>, timestamp: Int64, result: @escaping FlutterResult) {
let date = NSDate(timeIntervalSince1970: TimeInterval(timestamp))
MyWebStorageManager.websiteDataStore.removeData(ofTypes: dataTypes, modifiedSince: date as Date) {
result(true)
}
}
public override func dispose() {
super.dispose()
plugin = nil
}
deinit {
dispose()
}
}
@@ -0,0 +1,66 @@
//
// PlatformUtil.swift
// flutter_inappwebview
//
// Created by Lorenzo Pichilli on 01/03/21.
//
import Foundation
public class PlatformUtil: ChannelDelegate {
static let METHOD_CHANNEL_NAME = "com.pichillilorenzo/flutter_inappwebview_platformutil"
var plugin: SwiftFlutterPlugin?
init(plugin: SwiftFlutterPlugin) {
super.init(channel: FlutterMethodChannel(name: PlatformUtil.METHOD_CHANNEL_NAME, binaryMessenger: plugin.registrar!.messenger()))
self.plugin = plugin
}
public override func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
let arguments = call.arguments as? NSDictionary
switch call.method {
case "getSystemVersion":
let device = UIDevice.current
result(device.systemVersion)
break
case "formatDate":
let date = arguments!["date"] as! Int64
let format = arguments!["format"] as! String
let locale = PlatformUtil.getLocaleFromString(locale: arguments!["locale"] as? String)
let timezone = TimeZone.init(abbreviation: arguments!["timezone"] as? String ?? "UTC")!
result(PlatformUtil.formatDate(date: date, format: format, locale: locale, timezone: timezone))
break
default:
result(FlutterMethodNotImplemented)
break
}
}
static public func getLocaleFromString(locale: String?) -> Locale {
guard let locale = locale else {
return Locale.init(identifier: "en_US")
}
return Locale.init(identifier: locale)
}
static public func getDateFromMilliseconds(date: Int64) -> Date {
return Date(timeIntervalSince1970: TimeInterval(Double(date)/1000))
}
static public func formatDate(date: Int64, format: String, locale: Locale, timezone: TimeZone) -> String {
let formatter = DateFormatter()
formatter.dateFormat = format
formatter.timeZone = timezone
return formatter.string(from: PlatformUtil.getDateFromMilliseconds(date: date))
}
public override func dispose() {
super.dispose()
plugin = nil
}
deinit {
dispose()
}
}
@@ -0,0 +1,21 @@
//
// CallAsyncJavaScriptBelowIOS14WrapperJS.swift
// flutter_inappwebview
//
// Created by Lorenzo Pichilli on 16/02/21.
//
import Foundation
let CALL_ASYNC_JAVASCRIPT_BELOW_IOS_14_WRAPPER_JS = """
(function(obj) {
(async function(\(PluginScriptsUtil.VAR_FUNCTION_ARGUMENT_NAMES) {
\(PluginScriptsUtil.VAR_FUNCTION_BODY)
})(\(PluginScriptsUtil.VAR_FUNCTION_ARGUMENT_VALUES)).then(function(value) {
window.webkit.messageHandlers['onCallAsyncJavaScriptResultBelowIOS14Received'].postMessage({'value': value, 'error': null, 'resultUuid': '\(PluginScriptsUtil.VAR_RESULT_UUID)'});
}).catch(function(error) {
window.webkit.messageHandlers['onCallAsyncJavaScriptResultBelowIOS14Received'].postMessage({'value': null, 'error': error + '', 'resultUuid': '\(PluginScriptsUtil.VAR_RESULT_UUID)'});
});
return null;
})(\(PluginScriptsUtil.VAR_FUNCTION_ARGUMENTS_OBJ));
"""
@@ -0,0 +1,52 @@
//
// ConsoleLogJS.swift
// flutter_inappwebview
//
// Created by Lorenzo Pichilli on 16/02/21.
//
import Foundation
let CONSOLE_LOG_JS_PLUGIN_SCRIPT_GROUP_NAME = "IN_APP_WEBVIEW_CONSOLE_LOG_JS_PLUGIN_SCRIPT"
let CONSOLE_LOG_JS_PLUGIN_SCRIPT = PluginScript(
groupName: CONSOLE_LOG_JS_PLUGIN_SCRIPT_GROUP_NAME,
source: CONSOLE_LOG_JS_SOURCE,
injectionTime: .atDocumentStart,
forMainFrameOnly: false,
requiredInAllContentWorlds: true,
messageHandlerNames: ["consoleLog", "consoleDebug", "consoleError", "consoleInfo", "consoleWarn"])
// the message needs to be concatenated with '' in order to have the same behavior like on Android
let CONSOLE_LOG_JS_SOURCE = """
(function(console) {
function _callHandler(oldLog, args) {
var message = '';
for (var i in args) {
try {
message += message === '' ? args[i] : ' ' + args[i];
} catch(ignored) {}
}
var _windowId = \(WINDOW_ID_VARIABLE_JS_SOURCE);
window.webkit.messageHandlers[oldLog].postMessage({'message': message, '_windowId': _windowId});
}
var oldLogs = {
'consoleLog': console.log,
'consoleDebug': console.debug,
'consoleError': console.error,
'consoleInfo': console.info,
'consoleWarn': console.warn
};
for (var k in oldLogs) {
(function(oldLog) {
console[oldLog.replace('console', '').toLowerCase()] = function() {
oldLogs[oldLog].apply(null, arguments);
_callHandler(oldLog, arguments);
}
})(k);
}
})(window.console);
"""
@@ -0,0 +1,36 @@
//
// EnableViewportScaleJS.swift
// flutter_inappwebview
//
// Created by Lorenzo Pichilli on 16/02/21.
//
import Foundation
let ENABLE_VIEWPORT_SCALE_JS_PLUGIN_SCRIPT_GROUP_NAME = "IN_APP_WEBVIEW_ENABLE_VIEWPORT_SCALE_JS_PLUGIN_SCRIPT"
let ENABLE_VIEWPORT_SCALE_JS_PLUGIN_SCRIPT = PluginScript(
groupName: ENABLE_VIEWPORT_SCALE_JS_PLUGIN_SCRIPT_GROUP_NAME,
source: ENABLE_VIEWPORT_SCALE_JS_SOURCE,
injectionTime: .atDocumentEnd,
forMainFrameOnly: true,
requiredInAllContentWorlds: false,
messageHandlerNames: [])
let ENABLE_VIEWPORT_SCALE_JS_SOURCE = """
(function() {
var meta = document.createElement('meta');
meta.setAttribute('name', 'viewport');
meta.setAttribute('content', 'width=device-width');
document.getElementsByTagName('head')[0].appendChild(meta);
})()
"""
let NOT_ENABLE_VIEWPORT_SCALE_JS_SOURCE = """
(function() {
var meta = document.createElement('meta');
meta.setAttribute('name', 'viewport');
meta.setAttribute('content', window.\(JAVASCRIPT_BRIDGE_NAME)._originalViewPortMetaTagContent);
document.getElementsByTagName('head')[0].appendChild(meta);
})()
"""
@@ -0,0 +1,73 @@
//
// FindElementsAtPointJS.swift
// flutter_inappwebview
//
// Created by Lorenzo Pichilli on 16/02/21.
//
import Foundation
let FIND_ELEMENTS_AT_POINT_JS_PLUGIN_SCRIPT_GROUP_NAME = "IN_APP_WEBVIEW_FIND_ELEMENTS_AT_POINT_JS_PLUGIN_SCRIPT"
let FIND_ELEMENTS_AT_POINT_JS_PLUGIN_SCRIPT = PluginScript(
groupName: FIND_ELEMENTS_AT_POINT_JS_PLUGIN_SCRIPT_GROUP_NAME,
source: FIND_ELEMENTS_AT_POINT_JS_SOURCE,
injectionTime: .atDocumentStart,
forMainFrameOnly: true,
requiredInAllContentWorlds: false,
messageHandlerNames: [])
/**
https://developer.android.com/reference/android/webkit/WebView.HitTestResult
*/
let FIND_ELEMENTS_AT_POINT_JS_SOURCE = """
window.\(JAVASCRIPT_BRIDGE_NAME)._findElementsAtPoint = function(x, y) {
var hitTestResultType = {
UNKNOWN_TYPE: 0,
PHONE_TYPE: 2,
GEO_TYPE: 3,
EMAIL_TYPE: 4,
IMAGE_TYPE: 5,
SRC_ANCHOR_TYPE: 7,
SRC_IMAGE_ANCHOR_TYPE: 8,
EDIT_TEXT_TYPE: 9
};
var element = document.elementFromPoint(x, y);
var data = {
type: 0,
extra: null
};
while (element) {
if (element.tagName === 'IMG' && element.src) {
if (element.parentNode && element.parentNode.tagName === 'A' && element.parentNode.href) {
data.type = hitTestResultType.SRC_IMAGE_ANCHOR_TYPE;
} else {
data.type = hitTestResultType.IMAGE_TYPE;
}
data.extra = element.src;
break;
} else if (element.tagName === 'A' && element.href) {
if (element.href.indexOf('mailto:') === 0) {
data.type = hitTestResultType.EMAIL_TYPE;
data.extra = element.href.replace('mailto:', '');
} else if (element.href.indexOf('tel:') === 0) {
data.type = hitTestResultType.PHONE_TYPE;
data.extra = element.href.replace('tel:', '');
} else if (element.href.indexOf('geo:') === 0) {
data.type = hitTestResultType.GEO_TYPE;
data.extra = element.href.replace('geo:', '');
} else {
data.type = hitTestResultType.SRC_ANCHOR_TYPE;
data.extra = element.href;
}
break;
} else if (
(element.tagName === 'INPUT' && ['text', 'email', 'password', 'number', 'search', 'tel', 'url'].indexOf(element.type) >= 0) ||
element.tagName === 'TEXTAREA') {
data.type = hitTestResultType.EDIT_TEXT_TYPE
}
element = element.parentNode;
}
return data;
}
"""
@@ -0,0 +1,187 @@
//
// FindTextHighlightJS.swift
// flutter_inappwebview
//
// Created by Lorenzo Pichilli on 16/02/21.
//
import Foundation
let FIND_TEXT_HIGHLIGHT_JS_PLUGIN_SCRIPT_GROUP_NAME = "IN_APP_WEBVIEW_FIND_TEXT_HIGHLIGHT_JS_PLUGIN_SCRIPT"
let FIND_TEXT_HIGHLIGHT_SEARCH_RESULT_COUNT_JS_SOURCE = "window.\(JAVASCRIPT_BRIDGE_NAME)._searchResultCount"
let FIND_TEXT_HIGHLIGHT_CURRENT_HIGHLIGHT_JS_SOURCE = "window.\(JAVASCRIPT_BRIDGE_NAME)._currentHighlight"
let FIND_TEXT_HIGHLIGHT_IS_DONE_COUNTING_JS_SOURCE = "window.\(JAVASCRIPT_BRIDGE_NAME)._isDoneCounting"
let FIND_TEXT_HIGHLIGHT_JS_PLUGIN_SCRIPT = PluginScript(
groupName: FIND_TEXT_HIGHLIGHT_JS_PLUGIN_SCRIPT_GROUP_NAME,
source: FIND_TEXT_HIGHLIGHT_JS_SOURCE,
injectionTime: .atDocumentStart,
forMainFrameOnly: true,
requiredInAllContentWorlds: false,
messageHandlerNames: ["onFindResultReceived"])
let FIND_TEXT_HIGHLIGHT_JS_SOURCE = """
\(FIND_TEXT_HIGHLIGHT_SEARCH_RESULT_COUNT_JS_SOURCE) = 0;
\(FIND_TEXT_HIGHLIGHT_CURRENT_HIGHLIGHT_JS_SOURCE) = 0;
\(FIND_TEXT_HIGHLIGHT_IS_DONE_COUNTING_JS_SOURCE) = false;
window.\(JAVASCRIPT_BRIDGE_NAME)._findAllAsyncForElement = function(element, keyword) {
if (element) {
if (element.nodeType == 3) {
// Text node
var elementTmp = element;
while (true) {
var value = elementTmp.nodeValue; // Search for keyword in text node
var idx = value.toLowerCase().indexOf(keyword);
if (idx < 0) break;
var span = document.createElement("span");
var text = document.createTextNode(value.substr(idx, keyword.length));
span.appendChild(text);
span.setAttribute(
"id",
"\(JAVASCRIPT_BRIDGE_NAME)_SEARCH_WORD_" + \(FIND_TEXT_HIGHLIGHT_SEARCH_RESULT_COUNT_JS_SOURCE)
);
span.setAttribute("class", "\(JAVASCRIPT_BRIDGE_NAME)_Highlight");
var backgroundColor = \(FIND_TEXT_HIGHLIGHT_SEARCH_RESULT_COUNT_JS_SOURCE) == 0 ? "#FF9732" : "#FFFF00";
span.setAttribute("style", "color: #000 !important; background: " + backgroundColor + " !important; padding: 0px !important; margin: 0px !important; border: 0px !important;");
text = document.createTextNode(value.substr(idx + keyword.length));
element.deleteData(idx, value.length - idx);
var next = element.nextSibling;
element.parentNode.insertBefore(span, next);
element.parentNode.insertBefore(text, next);
element = text;
\(FIND_TEXT_HIGHLIGHT_SEARCH_RESULT_COUNT_JS_SOURCE)++;
elementTmp = document.createTextNode(
value.substr(idx + keyword.length)
);
var _windowId = \(WINDOW_ID_VARIABLE_JS_SOURCE);
window.webkit.messageHandlers["onFindResultReceived"].postMessage(
{
'findResult': {
'activeMatchOrdinal': \(FIND_TEXT_HIGHLIGHT_CURRENT_HIGHLIGHT_JS_SOURCE),
'numberOfMatches': \(FIND_TEXT_HIGHLIGHT_SEARCH_RESULT_COUNT_JS_SOURCE),
'isDoneCounting': \(FIND_TEXT_HIGHLIGHT_IS_DONE_COUNTING_JS_SOURCE)
},
'_windowId': _windowId
}
);
}
} else if (element.nodeType == 1) {
// Element node
if (
element.style.display != "none" &&
element.nodeName.toLowerCase() != "select"
) {
for (var i = element.childNodes.length - 1; i >= 0; i--) {
window.\(JAVASCRIPT_BRIDGE_NAME)._findAllAsyncForElement(
element.childNodes[element.childNodes.length - 1 - i],
keyword
);
}
}
}
}
}
// the main entry point to start the search
window.\(JAVASCRIPT_BRIDGE_NAME)._findAllAsync = function(keyword) {
window.\(JAVASCRIPT_BRIDGE_NAME)._clearMatches();
window.\(JAVASCRIPT_BRIDGE_NAME)._findAllAsyncForElement(document.body, keyword.toLowerCase());
\(FIND_TEXT_HIGHLIGHT_IS_DONE_COUNTING_JS_SOURCE) = true;
var _windowId = \(WINDOW_ID_VARIABLE_JS_SOURCE);
window.webkit.messageHandlers["onFindResultReceived"].postMessage(
{
'findResult': {
'activeMatchOrdinal': \(FIND_TEXT_HIGHLIGHT_CURRENT_HIGHLIGHT_JS_SOURCE),
'numberOfMatches': \(FIND_TEXT_HIGHLIGHT_SEARCH_RESULT_COUNT_JS_SOURCE),
'isDoneCounting': \(FIND_TEXT_HIGHLIGHT_IS_DONE_COUNTING_JS_SOURCE)
},
'_windowId': _windowId
}
);
}
// helper function, recursively removes the highlights in elements and their children
window.\(JAVASCRIPT_BRIDGE_NAME)._clearMatchesForElement = function(element) {
if (element) {
if (element.nodeType == 1) {
if (element.getAttribute("class") == "\(JAVASCRIPT_BRIDGE_NAME)_Highlight") {
var text = element.removeChild(element.firstChild);
element.parentNode.insertBefore(text, element);
element.parentNode.removeChild(element);
return true;
} else {
var normalize = false;
for (var i = element.childNodes.length - 1; i >= 0; i--) {
if (window.\(JAVASCRIPT_BRIDGE_NAME)._clearMatchesForElement(element.childNodes[i])) {
normalize = true;
}
}
if (normalize) {
element.normalize();
}
}
}
}
return false;
}
// the main entry point to remove the highlights
window.\(JAVASCRIPT_BRIDGE_NAME)._clearMatches = function() {
\(FIND_TEXT_HIGHLIGHT_SEARCH_RESULT_COUNT_JS_SOURCE) = 0;
\(FIND_TEXT_HIGHLIGHT_CURRENT_HIGHLIGHT_JS_SOURCE) = 0;
\(FIND_TEXT_HIGHLIGHT_IS_DONE_COUNTING_JS_SOURCE) = false;
window.\(JAVASCRIPT_BRIDGE_NAME)._clearMatchesForElement(document.body);
}
window.\(JAVASCRIPT_BRIDGE_NAME)._findNext = function(forward) {
if (\(FIND_TEXT_HIGHLIGHT_SEARCH_RESULT_COUNT_JS_SOURCE) <= 0) return;
var idx = \(FIND_TEXT_HIGHLIGHT_CURRENT_HIGHLIGHT_JS_SOURCE) + (forward ? +1 : -1);
idx =
idx < 0
? \(FIND_TEXT_HIGHLIGHT_SEARCH_RESULT_COUNT_JS_SOURCE) - 1
: idx >= \(FIND_TEXT_HIGHLIGHT_SEARCH_RESULT_COUNT_JS_SOURCE)
? 0
: idx;
\(FIND_TEXT_HIGHLIGHT_CURRENT_HIGHLIGHT_JS_SOURCE) = idx;
var scrollTo = document.getElementById("\(JAVASCRIPT_BRIDGE_NAME)_SEARCH_WORD_" + idx);
if (scrollTo) {
var highlights = document.getElementsByClassName("\(JAVASCRIPT_BRIDGE_NAME)_Highlight");
for (var i = 0; i < highlights.length; i++) {
var span = highlights[i];
span.style.backgroundColor = "#FFFF00";
}
scrollTo.style.backgroundColor = "#FF9732";
scrollTo.scrollIntoView({
behavior: "auto",
block: "center"
});
var _windowId = \(WINDOW_ID_VARIABLE_JS_SOURCE);
window.webkit.messageHandlers["onFindResultReceived"].postMessage(
{
'findResult': {
'activeMatchOrdinal': \(FIND_TEXT_HIGHLIGHT_CURRENT_HIGHLIGHT_JS_SOURCE),
'numberOfMatches': \(FIND_TEXT_HIGHLIGHT_SEARCH_RESULT_COUNT_JS_SOURCE),
'isDoneCounting': \(FIND_TEXT_HIGHLIGHT_IS_DONE_COUNTING_JS_SOURCE)
},
'_windowId': _windowId
}
);
}
}
"""
@@ -0,0 +1,267 @@
//
// InterceptAjaxRequestsJS.swift
// flutter_inappwebview
//
// Created by Lorenzo Pichilli on 16/02/21.
//
import Foundation
let INTERCEPT_AJAX_REQUEST_JS_PLUGIN_SCRIPT_GROUP_NAME = "IN_APP_WEBVIEW_INTERCEPT_AJAX_REQUEST_JS_PLUGIN_SCRIPT"
let FLAG_VARIABLE_FOR_SHOULD_INTERCEPT_AJAX_REQUEST_JS_SOURCE = "window.\(JAVASCRIPT_BRIDGE_NAME)._useShouldInterceptAjaxRequest"
let FLAG_VARIABLE_FOR_INTERCEPT_ONLY_ASYNC_AJAX_REQUESTS_JS_SOURCE = "window.\(JAVASCRIPT_BRIDGE_NAME)._interceptOnlyAsyncAjaxRequests";
let INTERCEPT_AJAX_REQUEST_JS_PLUGIN_SCRIPT = PluginScript(
groupName: INTERCEPT_AJAX_REQUEST_JS_PLUGIN_SCRIPT_GROUP_NAME,
source: INTERCEPT_AJAX_REQUEST_JS_SOURCE,
injectionTime: .atDocumentStart,
forMainFrameOnly: false,
requiredInAllContentWorlds: true,
messageHandlerNames: [])
func createInterceptOnlyAsyncAjaxRequestsPluginScript(onlyAsync: Bool) -> PluginScript {
return PluginScript(groupName: INTERCEPT_AJAX_REQUEST_JS_PLUGIN_SCRIPT_GROUP_NAME,
source: "\(FLAG_VARIABLE_FOR_INTERCEPT_ONLY_ASYNC_AJAX_REQUESTS_JS_SOURCE) = \(onlyAsync);",
injectionTime: .atDocumentStart,
forMainFrameOnly: false,
requiredInAllContentWorlds: true,
messageHandlerNames: []
);
}
let INTERCEPT_AJAX_REQUEST_JS_SOURCE = """
\(FLAG_VARIABLE_FOR_SHOULD_INTERCEPT_AJAX_REQUEST_JS_SOURCE) = true;
(function(ajax) {
var send = ajax.prototype.send;
var open = ajax.prototype.open;
var setRequestHeader = ajax.prototype.setRequestHeader;
ajax.prototype._flutter_inappwebview_url = null;
ajax.prototype._flutter_inappwebview_method = null;
ajax.prototype._flutter_inappwebview_isAsync = null;
ajax.prototype._flutter_inappwebview_user = null;
ajax.prototype._flutter_inappwebview_password = null;
ajax.prototype._flutter_inappwebview_password = null;
ajax.prototype._flutter_inappwebview_already_onreadystatechange_wrapped = false;
ajax.prototype._flutter_inappwebview_request_headers = {};
function convertRequestResponse(request, callback) {
if (request.response != null && request.responseType != null) {
switch (request.responseType) {
case 'arraybuffer':
callback(new Uint8Array(request.response));
return;
case 'blob':
const reader = new FileReader();
reader.addEventListener('loadend', function() {
callback(new Uint8Array(reader.result));
});
reader.readAsArrayBuffer(blob);
return;
case 'document':
callback(request.response.documentElement.outerHTML);
return;
case 'json':
callback(request.response);
return;
};
}
callback(null);
};
ajax.prototype.open = function(method, url, isAsync, user, password) {
isAsync = (isAsync != null) ? isAsync : true;
this._flutter_inappwebview_url = url;
this._flutter_inappwebview_method = method;
this._flutter_inappwebview_isAsync = isAsync;
this._flutter_inappwebview_user = user;
this._flutter_inappwebview_password = password;
this._flutter_inappwebview_request_headers = {};
open.call(this, method, url, isAsync, user, password);
};
ajax.prototype.setRequestHeader = function(header, value) {
this._flutter_inappwebview_request_headers[header] = value;
setRequestHeader.call(this, header, value);
};
function handleEvent(e) {
var self = this;
if (\(FLAG_VARIABLE_FOR_SHOULD_INTERCEPT_AJAX_REQUEST_JS_SOURCE) == null || \(FLAG_VARIABLE_FOR_SHOULD_INTERCEPT_AJAX_REQUEST_JS_SOURCE) == true) {
var headers = this.getAllResponseHeaders();
var responseHeaders = {};
if (headers != null) {
var arr = headers.trim().split(/[\\r\\n]+/);
arr.forEach(function (line) {
var parts = line.split(': ');
var header = parts.shift();
var value = parts.join(': ');
responseHeaders[header] = value;
});
}
convertRequestResponse(this, function(response) {
var ajaxRequest = {
method: self._flutter_inappwebview_method,
url: self._flutter_inappwebview_url,
isAsync: self._flutter_inappwebview_isAsync,
user: self._flutter_inappwebview_user,
password: self._flutter_inappwebview_password,
withCredentials: self.withCredentials,
headers: self._flutter_inappwebview_request_headers,
readyState: self.readyState,
status: self.status,
responseURL: self.responseURL,
responseType: self.responseType,
response: response,
responseText: (self.responseType == 'text' || self.responseType == '') ? self.responseText : null,
responseXML: (self.responseType == 'document' && self.responseXML != null) ? self.responseXML.documentElement.outerHTML : null,
statusText: self.statusText,
responseHeaders, responseHeaders,
event: {
type: e.type,
loaded: e.loaded,
lengthComputable: e.lengthComputable,
total: e.total
}
};
window.\(JAVASCRIPT_BRIDGE_NAME).callHandler('onAjaxProgress', ajaxRequest).then(function(result) {
if (result != null) {
switch (result) {
case 0:
self.abort();
return;
};
}
});
});
}
};
ajax.prototype.send = function(data) {
var self = this;
var canBeIntercepted = self._flutter_inappwebview_isAsync || \(FLAG_VARIABLE_FOR_INTERCEPT_ONLY_ASYNC_AJAX_REQUESTS_JS_SOURCE) === false;
if (canBeIntercepted && (\(FLAG_VARIABLE_FOR_SHOULD_INTERCEPT_AJAX_REQUEST_JS_SOURCE) == null || \(FLAG_VARIABLE_FOR_SHOULD_INTERCEPT_AJAX_REQUEST_JS_SOURCE) == true)) {
if (!this._flutter_inappwebview_already_onreadystatechange_wrapped) {
this._flutter_inappwebview_already_onreadystatechange_wrapped = true;
var onreadystatechange = this.onreadystatechange;
this.onreadystatechange = function() {
if (\(FLAG_VARIABLE_FOR_SHOULD_INTERCEPT_AJAX_REQUEST_JS_SOURCE) == null || \(FLAG_VARIABLE_FOR_SHOULD_INTERCEPT_AJAX_REQUEST_JS_SOURCE) == true) {
var headers = this.getAllResponseHeaders();
var responseHeaders = {};
if (headers != null) {
var arr = headers.trim().split(/[\\r\\n]+/);
arr.forEach(function (line) {
var parts = line.split(': ');
var header = parts.shift();
var value = parts.join(': ');
responseHeaders[header] = value;
});
}
convertRequestResponse(this, function(response) {
var ajaxRequest = {
method: self._flutter_inappwebview_method,
url: self._flutter_inappwebview_url,
isAsync: self._flutter_inappwebview_isAsync,
user: self._flutter_inappwebview_user,
password: self._flutter_inappwebview_password,
withCredentials: self.withCredentials,
headers: self._flutter_inappwebview_request_headers,
readyState: self.readyState,
status: self.status,
responseURL: self.responseURL,
responseType: self.responseType,
response: response,
responseText: (self.responseType == 'text' || self.responseType == '') ? self.responseText : null,
responseXML: (self.responseType == 'document' && self.responseXML != null) ? self.responseXML.documentElement.outerHTML : null,
statusText: self.statusText,
responseHeaders: responseHeaders
};
window.\(JAVASCRIPT_BRIDGE_NAME).callHandler('onAjaxReadyStateChange', ajaxRequest).then(function(result) {
if (result != null) {
switch (result) {
case 0:
self.abort();
return;
};
}
if (onreadystatechange != null) {
onreadystatechange();
}
});
});
} else if (onreadystatechange != null) {
onreadystatechange();
}
};
}
this.addEventListener('loadstart', handleEvent);
this.addEventListener('load', handleEvent);
this.addEventListener('loadend', handleEvent);
this.addEventListener('progress', handleEvent);
this.addEventListener('error', handleEvent);
this.addEventListener('abort', handleEvent);
this.addEventListener('timeout', handleEvent);
\(JAVASCRIPT_UTIL_VAR_NAME).convertBodyRequest(data).then(function(data) {
var ajaxRequest = {
data: data,
method: self._flutter_inappwebview_method,
url: self._flutter_inappwebview_url,
isAsync: self._flutter_inappwebview_isAsync,
user: self._flutter_inappwebview_user,
password: self._flutter_inappwebview_password,
withCredentials: self.withCredentials,
headers: self._flutter_inappwebview_request_headers,
responseType: self.responseType
};
window.\(JAVASCRIPT_BRIDGE_NAME).callHandler('shouldInterceptAjaxRequest', ajaxRequest).then(function(result) {
if (result != null) {
switch (result) {
case 0:
self.abort();
return;
};
if (result.data != null && !\(JAVASCRIPT_UTIL_VAR_NAME).isString(result.data) && result.data.length > 0) {
var bodyString = \(JAVASCRIPT_UTIL_VAR_NAME).arrayBufferToString(result.data);
if (\(JAVASCRIPT_UTIL_VAR_NAME).isBodyFormData(bodyString)) {
var formDataContentType = \(JAVASCRIPT_UTIL_VAR_NAME).getFormDataContentType(bodyString);
if (result.headers != null) {
result.headers['Content-Type'] = result.headers['Content-Type'] == null ? formDataContentType : result.headers['Content-Type'];
} else {
result.headers = { 'Content-Type': formDataContentType };
}
}
}
if (\(JAVASCRIPT_UTIL_VAR_NAME).isString(result.data) || result.data == null) {
data = result.data;
} else if (result.data.length > 0) {
data = new Uint8Array(result.data);
}
self.withCredentials = result.withCredentials;
if (result.responseType != null && self._flutter_inappwebview_isAsync) {
self.responseType = result.responseType;
};
if (result.headers != null) {
for (var header in result.headers) {
var value = result.headers[header];
var flutter_inappwebview_value = self._flutter_inappwebview_request_headers[header];
if (flutter_inappwebview_value == null) {
self._flutter_inappwebview_request_headers[header] = value;
} else {
self._flutter_inappwebview_request_headers[header] += ', ' + value;
}
setRequestHeader.call(self, header, value);
};
}
if ((self._flutter_inappwebview_method != result.method && result.method != null) ||
(self._flutter_inappwebview_url != result.url && result.url != null) ||
(self._flutter_inappwebview_isAsync != result.isAsync && result.isAsync != null) ||
(self._flutter_inappwebview_user != result.user && result.user != null) ||
(self._flutter_inappwebview_password != result.password && result.password != null)) {
self.abort();
self.open(result.method, result.url, result.isAsync, result.user, result.password);
}
}
send.call(self, data);
});
});
} else {
send.call(this, data);
}
};
})(window.XMLHttpRequest);
"""
@@ -0,0 +1,153 @@
//
// InterceptFetchRequestsJS.swift
// flutter_inappwebview
//
// Created by Lorenzo Pichilli on 16/02/21.
//
import Foundation
let INTERCEPT_FETCH_REQUEST_JS_PLUGIN_SCRIPT_GROUP_NAME = "IN_APP_WEBVIEW_INTERCEPT_FETCH_REQUEST_JS_PLUGIN_SCRIPT"
let FLAG_VARIABLE_FOR_SHOULD_INTERCEPT_FETCH_REQUEST_JS_SOURCE = "window.\(JAVASCRIPT_BRIDGE_NAME)._useShouldInterceptFetchRequest"
let INTERCEPT_FETCH_REQUEST_JS_PLUGIN_SCRIPT = PluginScript(
groupName: INTERCEPT_FETCH_REQUEST_JS_PLUGIN_SCRIPT_GROUP_NAME,
source: INTERCEPT_FETCH_REQUEST_JS_SOURCE,
injectionTime: .atDocumentStart,
forMainFrameOnly: false,
requiredInAllContentWorlds: true,
messageHandlerNames: [])
let INTERCEPT_FETCH_REQUEST_JS_SOURCE = """
\(FLAG_VARIABLE_FOR_SHOULD_INTERCEPT_FETCH_REQUEST_JS_SOURCE) = true;
(function(fetch) {
if (fetch == null) {
return;
}
window.fetch = async function(resource, init) {
if (\(FLAG_VARIABLE_FOR_SHOULD_INTERCEPT_FETCH_REQUEST_JS_SOURCE) == null || \(FLAG_VARIABLE_FOR_SHOULD_INTERCEPT_FETCH_REQUEST_JS_SOURCE) == true) {
var fetchRequest = {
url: null,
method: null,
headers: null,
body: null,
mode: null,
credentials: null,
cache: null,
redirect: null,
referrer: null,
referrerPolicy: null,
integrity: null,
keepalive: null
};
if (resource instanceof Request) {
fetchRequest.url = resource.url;
fetchRequest.method = resource.method;
fetchRequest.headers = resource.headers;
fetchRequest.body = resource.body;
fetchRequest.mode = resource.mode;
fetchRequest.credentials = resource.credentials;
fetchRequest.cache = resource.cache;
fetchRequest.redirect = resource.redirect;
fetchRequest.referrer = resource.referrer;
fetchRequest.referrerPolicy = resource.referrerPolicy;
fetchRequest.integrity = resource.integrity;
fetchRequest.keepalive = resource.keepalive;
} else {
fetchRequest.url = resource != null ? resource.toString() : null;
if (init != null) {
fetchRequest.method = init.method;
fetchRequest.headers = init.headers;
fetchRequest.body = init.body;
fetchRequest.mode = init.mode;
fetchRequest.credentials = init.credentials;
fetchRequest.cache = init.cache;
fetchRequest.redirect = init.redirect;
fetchRequest.referrer = init.referrer;
fetchRequest.referrerPolicy = init.referrerPolicy;
fetchRequest.integrity = init.integrity;
fetchRequest.keepalive = init.keepalive;
}
}
if (fetchRequest.headers instanceof Headers) {
fetchRequest.headers = \(JAVASCRIPT_UTIL_VAR_NAME).convertHeadersToJson(fetchRequest.headers);
}
fetchRequest.credentials = \(JAVASCRIPT_UTIL_VAR_NAME).convertCredentialsToJson(fetchRequest.credentials);
return \(JAVASCRIPT_UTIL_VAR_NAME).convertBodyRequest(fetchRequest.body).then(function(body) {
fetchRequest.body = body;
return window.\(JAVASCRIPT_BRIDGE_NAME).callHandler('shouldInterceptFetchRequest', fetchRequest).then(function(result) {
if (result != null) {
switch (result.action) {
case 0:
var controller = new AbortController();
if (init != null) {
init.signal = controller.signal;
} else {
init = {
signal: controller.signal
};
}
controller.abort();
break;
}
if (result.body != null && !\(JAVASCRIPT_UTIL_VAR_NAME).isString(result.body) && result.body.length > 0) {
var bodyString = \(JAVASCRIPT_UTIL_VAR_NAME).arrayBufferToString(result.body);
if (\(JAVASCRIPT_UTIL_VAR_NAME).isBodyFormData(bodyString)) {
var formDataContentType = \(JAVASCRIPT_UTIL_VAR_NAME).getFormDataContentType(bodyString);
if (result.headers != null) {
result.headers['Content-Type'] = result.headers['Content-Type'] == null ? formDataContentType : result.headers['Content-Type'];
} else {
result.headers = { 'Content-Type': formDataContentType };
}
}
}
resource = result.url;
if (init == null) {
init = {};
}
if (result.method != null && result.method.length > 0) {
init.method = result.method;
}
if (result.headers != null && Object.keys(result.headers).length > 0) {
init.headers = \(JAVASCRIPT_UTIL_VAR_NAME).convertJsonToHeaders(result.headers);
}
if (\(JAVASCRIPT_UTIL_VAR_NAME).isString(result.body) || result.body == null) {
init.body = result.body;
} else if (result.body.length > 0) {
init.body = new Uint8Array(result.body);
}
if (result.mode != null && result.mode.length > 0) {
init.mode = result.mode;
}
if (result.credentials != null) {
init.credentials = \(JAVASCRIPT_UTIL_VAR_NAME).convertJsonToCredential(result.credentials);
}
if (result.cache != null && result.cache.length > 0) {
init.cache = result.cache;
}
if (result.redirect != null && result.redirect.length > 0) {
init.redirect = result.redirect;
}
if (result.referrer != null && result.referrer.length > 0) {
init.referrer = result.referrer;
}
if (result.referrerPolicy != null && result.referrerPolicy.length > 0) {
init.referrerPolicy = result.referrerPolicy;
}
if (result.integrity != null && result.integrity.length > 0) {
init.integrity = result.integrity;
}
if (result.keepalive != null) {
init.keepalive = result.keepalive;
}
return fetch(resource, init);
}
return fetch(resource, init);
});
});
} else {
return fetch(resource, init);
}
};
})(window.fetch);
"""
@@ -0,0 +1,243 @@
//
// javaScriptBridgeJS.swift
// flutter_inappwebview
//
// Created by Lorenzo Pichilli on 16/02/21.
//
import Foundation
let JAVASCRIPT_BRIDGE_NAME = "flutter_inappwebview"
let JAVASCRIPT_BRIDGE_JS_PLUGIN_SCRIPT_GROUP_NAME = "IN_APP_WEBVIEW_JAVASCRIPT_BRIDGE_JS_PLUGIN_SCRIPT"
let JAVASCRIPT_BRIDGE_JS_PLUGIN_SCRIPT = PluginScript(
groupName: JAVASCRIPT_BRIDGE_JS_PLUGIN_SCRIPT_GROUP_NAME,
source: JAVASCRIPT_BRIDGE_JS_SOURCE,
injectionTime: .atDocumentStart,
forMainFrameOnly: false,
requiredInAllContentWorlds: true,
messageHandlerNames: ["callHandler"])
let JAVASCRIPT_BRIDGE_JS_SOURCE = """
window.\(JAVASCRIPT_BRIDGE_NAME) = {};
\(WEB_MESSAGE_CHANNELS_VARIABLE_NAME) = {};
window.\(JAVASCRIPT_BRIDGE_NAME).callHandler = function() {
var _windowId = \(WINDOW_ID_VARIABLE_JS_SOURCE);
var _callHandlerID = setTimeout(function(){});
window.webkit.messageHandlers['callHandler'].postMessage( {'handlerName': arguments[0], '_callHandlerID': _callHandlerID, 'args': JSON.stringify(Array.prototype.slice.call(arguments, 1)), '_windowId': _windowId} );
return new Promise(function(resolve, reject) {
window.\(JAVASCRIPT_BRIDGE_NAME)[_callHandlerID] = {resolve: resolve, reject: reject};
});
};
\(WEB_MESSAGE_LISTENER_JS_SOURCE)
\(UTIL_JS_SOURCE)
"""
let PLATFORM_READY_JS_SOURCE = "window.dispatchEvent(new Event('flutterInAppWebViewPlatformReady'));";
let JAVASCRIPT_UTIL_VAR_NAME = "window.\(JAVASCRIPT_BRIDGE_NAME)._Util"
/*
https://github.com/github/fetch/blob/master/fetch.js
*/
let UTIL_JS_SOURCE = """
\(JAVASCRIPT_UTIL_VAR_NAME) = {
support: {
searchParams: 'URLSearchParams' in window,
iterable: 'Symbol' in window && 'iterator' in Symbol,
blob:
'FileReader' in window &&
'Blob' in window &&
(function() {
try {
new Blob();
return true;
} catch (e) {
return false;
}
})(),
formData: 'FormData' in window,
arrayBuffer: 'ArrayBuffer' in window
},
isDataView: function(obj) {
return obj && DataView.prototype.isPrototypeOf(obj);
},
fileReaderReady: function(reader) {
return new Promise(function(resolve, reject) {
reader.onload = function() {
resolve(reader.result);
};
reader.onerror = function() {
reject(reader.error);
};
});
},
readBlobAsArrayBuffer: function(blob) {
var reader = new FileReader();
var promise = \(JAVASCRIPT_UTIL_VAR_NAME).fileReaderReady(reader);
reader.readAsArrayBuffer(blob);
return promise;
},
convertBodyToArrayBuffer: function(body) {
var viewClasses = [
'[object Int8Array]',
'[object Uint8Array]',
'[object Uint8ClampedArray]',
'[object Int16Array]',
'[object Uint16Array]',
'[object Int32Array]',
'[object Uint32Array]',
'[object Float32Array]',
'[object Float64Array]'
];
var isArrayBufferView = null;
if (\(JAVASCRIPT_UTIL_VAR_NAME).support.arrayBuffer) {
isArrayBufferView =
ArrayBuffer.isView ||
function(obj) {
return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1;
};
}
var bodyUsed = false;
this._bodyInit = body;
if (!body) {
this._bodyText = '';
} else if (typeof body === 'string') {
this._bodyText = body;
} else if (\(JAVASCRIPT_UTIL_VAR_NAME).support.blob && Blob.prototype.isPrototypeOf(body)) {
this._bodyBlob = body;
} else if (\(JAVASCRIPT_UTIL_VAR_NAME).support.formData && FormData.prototype.isPrototypeOf(body)) {
this._bodyFormData = body;
} else if (\(JAVASCRIPT_UTIL_VAR_NAME).support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {
this._bodyText = body.toString();
} else if (\(JAVASCRIPT_UTIL_VAR_NAME).support.arrayBuffer && \(JAVASCRIPT_UTIL_VAR_NAME).support.blob && \(JAVASCRIPT_UTIL_VAR_NAME).isDataView(body)) {
this._bodyArrayBuffer = bufferClone(body.buffer);
this._bodyInit = new Blob([this._bodyArrayBuffer]);
} else if (\(JAVASCRIPT_UTIL_VAR_NAME).support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) {
this._bodyArrayBuffer = bufferClone(body);
} else {
this._bodyText = body = Object.prototype.toString.call(body);
}
this.blob = function () {
if (bodyUsed) {
return Promise.reject(new TypeError('Already read'));
}
bodyUsed = true;
if (this._bodyBlob) {
return Promise.resolve(this._bodyBlob);
} else if (this._bodyArrayBuffer) {
return Promise.resolve(new Blob([this._bodyArrayBuffer]));
} else if (this._bodyFormData) {
throw new Error('could not read FormData body as blob');
} else {
return Promise.resolve(new Blob([this._bodyText]));
}
};
if (this._bodyArrayBuffer) {
if (bodyUsed) {
return Promise.reject(new TypeError('Already read'));
}
bodyUsed = true;
if (ArrayBuffer.isView(this._bodyArrayBuffer)) {
return Promise.resolve(
this._bodyArrayBuffer.buffer.slice(
this._bodyArrayBuffer.byteOffset,
this._bodyArrayBuffer.byteOffset + this._bodyArrayBuffer.byteLength
)
);
} else {
return Promise.resolve(this._bodyArrayBuffer);
}
}
return this.blob().then(\(JAVASCRIPT_UTIL_VAR_NAME).readBlobAsArrayBuffer);
},
isString: function(variable) {
return typeof variable === 'string' || variable instanceof String;
},
convertBodyRequest: function(body) {
if (body == null) {
return new Promise((resolve, reject) => resolve(null));
}
if (\(JAVASCRIPT_UTIL_VAR_NAME).isString(body) || (\(JAVASCRIPT_UTIL_VAR_NAME).support.searchParams && body instanceof URLSearchParams)) {
return new Promise((resolve, reject) => resolve(body.toString()));
}
if (window.Response != null) {
return new Response(body).arrayBuffer().then(function(arrayBuffer) {
return Array.from(new Uint8Array(arrayBuffer));
});
}
return \(JAVASCRIPT_UTIL_VAR_NAME).convertBodyToArrayBuffer(body).then(function(arrayBuffer) {
return Array.from(new Uint8Array(arrayBuffer));
});
},
arrayBufferToString: function(arrayBuffer) {
var uint8Array = new Uint8Array(arrayBuffer);
return uint8Array.reduce(function(acc, i) { return acc += String.fromCharCode.apply(null, [i]); }, '');
},
isBodyFormData: function(bodyString) {
return bodyString.indexOf('------WebKitFormBoundary') >= 0;
},
getFormDataContentType: function(bodyString) {
var boundary = bodyString.substr(2, 40);
return 'multipart/form-data; boundary=' + boundary;
},
convertHeadersToJson: function(headers) {
var headersObj = {};
for (var header of headers.keys()) {
var value = headers.get(header);
headersObj[header] = value;
}
return headersObj;
},
convertJsonToHeaders: function(headersJson) {
return new Headers(headersJson);
},
convertCredentialsToJson: function(credentials) {
var credentialsObj = {};
if (window.FederatedCredential != null && credentials instanceof FederatedCredential) {
credentialsObj.type = credentials.type;
credentialsObj.id = credentials.id;
credentialsObj.name = credentials.name;
credentialsObj.protocol = credentials.protocol;
credentialsObj.provider = credentials.provider;
credentialsObj.iconURL = credentials.iconURL;
} else if (window.PasswordCredential != null && credentials instanceof PasswordCredential) {
credentialsObj.type = credentials.type;
credentialsObj.id = credentials.id;
credentialsObj.name = credentials.name;
credentialsObj.password = credentials.password;
credentialsObj.iconURL = credentials.iconURL;
} else {
credentialsObj.type = 'default';
credentialsObj.value = credentials;
}
return credentialsObj;
},
convertJsonToCredential: function(credentialsJson) {
var credentials;
if (window.FederatedCredential != null && credentialsJson.type === 'federated') {
credentials = new FederatedCredential({
id: credentialsJson.id,
name: credentialsJson.name,
protocol: credentialsJson.protocol,
provider: credentialsJson.provider,
iconURL: credentialsJson.iconURL
});
} else if (window.PasswordCredential != null && credentialsJson.type === 'password') {
credentials = new PasswordCredential({
id: credentialsJson.id,
name: credentialsJson.name,
password: credentialsJson.password,
iconURL: credentialsJson.iconURL
});
} else {
credentials = credentialsJson.value == null ? undefined : credentialsJson.value;
}
return credentials;
}
};
"""
@@ -0,0 +1,62 @@
//
// LastTouchedAnchorOrImageJS.swift
// flutter_inappwebview
//
// Created by Lorenzo Pichilli on 16/02/21.
//
import Foundation
let LAST_TOUCHED_ANCHOR_OR_IMAGE_JS_PLUGIN_SCRIPT_GROUP_NAME = "IN_APP_WEBVIEW_LAST_TOUCHED_ANCHOR_OR_IMAGE_JS_PLUGIN_SCRIPT"
let LAST_TOUCHED_ANCHOR_OR_IMAGE_JS_PLUGIN_SCRIPT = PluginScript(
groupName: LAST_TOUCHED_ANCHOR_OR_IMAGE_JS_PLUGIN_SCRIPT_GROUP_NAME,
source: LAST_TOUCHED_ANCHOR_OR_IMAGE_JS_SOURCE,
injectionTime: .atDocumentStart,
forMainFrameOnly: true,
requiredInAllContentWorlds: false,
messageHandlerNames: [])
let LAST_TOUCHED_ANCHOR_OR_IMAGE_JS_SOURCE = """
window.\(JAVASCRIPT_BRIDGE_NAME)._lastAnchorOrImageTouched = null;
window.\(JAVASCRIPT_BRIDGE_NAME)._lastImageTouched = null;
(function() {
document.addEventListener('touchstart', function(event) {
var target = event.target;
while (target) {
if (target.tagName === 'IMG') {
var img = target;
window.\(JAVASCRIPT_BRIDGE_NAME)._lastImageTouched = {
url: img.src
};
var parent = img.parentNode;
while (parent) {
if (parent.tagName === 'A') {
window.\(JAVASCRIPT_BRIDGE_NAME)._lastAnchorOrImageTouched = {
title: parent.textContent,
url: parent.href,
src: img.src
};
break;
}
parent = parent.parentNode;
}
return;
} else if (target.tagName === 'A') {
var link = target;
var images = link.getElementsByTagName('img');
var img = (images.length > 0) ? images[0] : null;
var imgSrc = (img != null) ? img.src : null;
window.\(JAVASCRIPT_BRIDGE_NAME)._lastImageTouched = (img != null) ? {url: imgSrc} : window.\(JAVASCRIPT_BRIDGE_NAME)._lastImageTouched;
window.\(JAVASCRIPT_BRIDGE_NAME)._lastAnchorOrImageTouched = {
title: link.textContent,
url: link.href,
src: imgSrc
};
return;
}
target = target.parentNode;
}
});
})();
"""
@@ -0,0 +1,39 @@
//
// resourceObserverJS.swift
// flutter_inappwebview
//
// Created by Lorenzo Pichilli on 16/02/21.
//
import Foundation
let ON_LOAD_RESOURCE_JS_PLUGIN_SCRIPT_GROUP_NAME = "IN_APP_WEBVIEW_ON_LOAD_RESOURCE_JS_PLUGIN_SCRIPT"
let FLAG_VARIABLE_FOR_ON_LOAD_RESOURCE_JS_SOURCE = "window.\(JAVASCRIPT_BRIDGE_NAME)._useOnLoadResource"
let ON_LOAD_RESOURCE_JS_PLUGIN_SCRIPT = PluginScript(
groupName: ON_LOAD_RESOURCE_JS_PLUGIN_SCRIPT_GROUP_NAME,
source: ON_LOAD_RESOURCE_JS_SOURCE,
injectionTime: .atDocumentStart,
forMainFrameOnly: false,
requiredInAllContentWorlds: false,
messageHandlerNames: [])
let ON_LOAD_RESOURCE_JS_SOURCE = """
\(FLAG_VARIABLE_FOR_ON_LOAD_RESOURCE_JS_SOURCE) = true;
(function() {
var observer = new PerformanceObserver(function(list) {
list.getEntries().forEach(function(entry) {
if (\(FLAG_VARIABLE_FOR_ON_LOAD_RESOURCE_JS_SOURCE) == null || \(FLAG_VARIABLE_FOR_ON_LOAD_RESOURCE_JS_SOURCE) == true) {
var resource = {
"url": entry.name,
"initiatorType": entry.initiatorType,
"startTime": entry.startTime,
"duration": entry.duration
};
window.\(JAVASCRIPT_BRIDGE_NAME).callHandler("onLoadResource", resource);
}
});
});
observer.observe({entryTypes: ['resource']});
})();
"""
@@ -0,0 +1,26 @@
//
// OnWindowBlurEventJS.swift
// flutter_inappwebview
//
// Created by Lorenzo Pichilli on 16/02/21.
//
import Foundation
let ON_WINDOW_BLUR_EVENT_JS_PLUGIN_SCRIPT_GROUP_NAME = "IN_APP_WEBVIEW_ON_WINDOW_BLUR_EVENT_JS_PLUGIN_SCRIPT"
let ON_WINDOW_BLUR_EVENT_JS_PLUGIN_SCRIPT = PluginScript(
groupName: ON_WINDOW_BLUR_EVENT_JS_PLUGIN_SCRIPT_GROUP_NAME,
source: ON_WINDOW_BLUR_EVENT_JS_SOURCE,
injectionTime: .atDocumentStart,
forMainFrameOnly: true,
requiredInAllContentWorlds: false,
messageHandlerNames: [])
let ON_WINDOW_BLUR_EVENT_JS_SOURCE = """
(function(){
window.addEventListener('blur', function(e) {
window.\(JAVASCRIPT_BRIDGE_NAME).callHandler('onWindowBlur');
});
})();
"""
@@ -0,0 +1,26 @@
//
// OnWindowFocusEventJS.swift
// flutter_inappwebview
//
// Created by Lorenzo Pichilli on 16/02/21.
//
import Foundation
let ON_WINDOW_FOCUS_EVENT_JS_PLUGIN_SCRIPT_GROUP_NAME = "IN_APP_WEBVIEW_ON_WINDOW_FOCUS_EVENT_JS_PLUGIN_SCRIPT"
let ON_WINDOW_FOCUS_EVENT_JS_PLUGIN_SCRIPT = PluginScript(
groupName: ON_WINDOW_FOCUS_EVENT_JS_SOURCE,
source: ON_WINDOW_FOCUS_EVENT_JS_SOURCE,
injectionTime: .atDocumentStart,
forMainFrameOnly: true,
requiredInAllContentWorlds: false,
messageHandlerNames: [])
let ON_WINDOW_FOCUS_EVENT_JS_SOURCE = """
(function(){
window.addEventListener('focus', function(e) {
window.\(JAVASCRIPT_BRIDGE_NAME).callHandler('onWindowFocus');
});
})();
"""
@@ -0,0 +1,31 @@
//
// OriginalViewPortMetaTagContentJS.swift
// flutter_inappwebview
//
// Created by Lorenzo Pichilli on 16/02/21.
//
import Foundation
let ORIGINAL_VIEWPORT_METATAG_CONTENT_JS_PLUGIN_SCRIPT_GROUP_NAME = "IN_APP_WEBVIEW_ORIGINAL_VIEWPORT_METATAG_CONTENT_JS_PLUGIN_SCRIPT"
let ORIGINAL_VIEWPORT_METATAG_CONTENT_JS_PLUGIN_SCRIPT = PluginScript(
groupName: ORIGINAL_VIEWPORT_METATAG_CONTENT_JS_PLUGIN_SCRIPT_GROUP_NAME,
source: ORIGINAL_VIEWPORT_METATAG_CONTENT_JS_SOURCE,
injectionTime: .atDocumentEnd,
forMainFrameOnly: true,
requiredInAllContentWorlds: false,
messageHandlerNames: [])
let ORIGINAL_VIEWPORT_METATAG_CONTENT_JS_SOURCE = """
window.\(JAVASCRIPT_BRIDGE_NAME)._originalViewPortMetaTagContent = "";
(function() {
var metaTagNodes = document.head.getElementsByTagName('meta');
for (var i = 0; i < metaTagNodes.length; i++) {
var metaTagNode = metaTagNodes[i];
if (metaTagNode.name === "viewport") {
window.\(JAVASCRIPT_BRIDGE_NAME)._originalViewPortMetaTagContent = metaTagNode.content;
}
}
})();
"""
@@ -0,0 +1,31 @@
//
// PluginScripts.swift
// flutter_inappwebview
//
// Created by Lorenzo Pichilli on 16/02/21.
//
import Foundation
public class PluginScriptsUtil {
public static let VAR_PLACEHOLDER_VALUE = "$IN_APP_WEBVIEW_PLACEHOLDER_VALUE"
public static let VAR_FUNCTION_ARGUMENT_NAMES = "$IN_APP_WEBVIEW_FUNCTION_ARGUMENT_NAMES"
public static let VAR_FUNCTION_ARGUMENT_VALUES = "$IN_APP_WEBVIEW_FUNCTION_ARGUMENT_VALUES"
public static let VAR_FUNCTION_ARGUMENTS_OBJ = "$IN_APP_WEBVIEW_FUNCTION_ARGUMENTS_OBJ"
public static let VAR_FUNCTION_BODY = "$IN_APP_WEBVIEW_FUNCTION_BODY"
public static let VAR_RESULT_UUID = "$IN_APP_WEBVIEW_RESULT_UUID"
public static let GET_SELECTED_TEXT_JS_SOURCE = """
(function(){
var txt;
if (window.getSelection) {
txt = window.getSelection().toString();
} else if (window.document.getSelection) {
txt = window.document.getSelection().toString();
} else if (window.document.selection) {
txt = window.document.selection.createRange().text;
}
return txt;
})();
"""
}
@@ -0,0 +1,24 @@
//
// PrintJS.swift
// flutter_inappwebview
//
// Created by Lorenzo Pichilli on 16/02/21.
//
import Foundation
let PRINT_JS_PLUGIN_SCRIPT_GROUP_NAME = "IN_APP_WEBVIEW_PRINT_JS_PLUGIN_SCRIPT"
let PRINT_JS_PLUGIN_SCRIPT = PluginScript(
groupName: PRINT_JS_PLUGIN_SCRIPT_GROUP_NAME,
source: PRINT_JS_SOURCE,
injectionTime: .atDocumentStart,
forMainFrameOnly: false,
requiredInAllContentWorlds: true,
messageHandlerNames: [])
let PRINT_JS_SOURCE = """
window.print = function() {
window.\(JAVASCRIPT_BRIDGE_NAME).callHandler("onPrintRequest", window.location.href);
}
"""
@@ -0,0 +1,27 @@
//
// PromisePolyfillJS.swift
// flutter_inappwebview
//
// Created by Lorenzo Pichilli on 16/02/21.
//
import Foundation
import WebKit
let PROMISE_POLYFILL_JS_PLUGIN_SCRIPT_GROUP_NAME = "IN_APP_WEBVIEW_PROMISE_POLYFILL_JS_PLUGIN_SCRIPT"
let PROMISE_POLYFILL_JS_PLUGIN_SCRIPT = PluginScript(
groupName: PROMISE_POLYFILL_JS_PLUGIN_SCRIPT_GROUP_NAME,
source: PROMISE_POLYFILL_JS_SOURCE,
injectionTime: .atDocumentStart,
forMainFrameOnly: false,
requiredInAllContentWorlds: true,
messageHandlerNames: [])
// https://github.com/tildeio/rsvp.js
let PROMISE_POLYFILL_JS_SOURCE = """
if (window.Promise == null) {
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e(t.RSVP={})}(this,function(t){"use strict";function e(t){var e=t._promiseCallbacks;return e||(e=t._promiseCallbacks={}),e}var r={mixin:function(t){return t.on=this.on,t.off=this.off,t.trigger=this.trigger,t._promiseCallbacks=void 0,t},on:function(t,r){if("function"!=typeof r)throw new TypeError("Callback must be a function");var n=e(this),o=n[t];o||(o=n[t]=[]),-1===o.indexOf(r)&&o.push(r)},off:function(t,r){var n=e(this);if(r){var o=n[t],i=o.indexOf(r);-1!==i&&o.splice(i,1)}else n[t]=[]},trigger:function(t,r,n){var o=e(this)[t];if(o)for(var i=0;i<o.length;i++)(0,o[i])(r,n)}},n={instrument:!1};function o(t,e){if(2!==arguments.length)return n[t];n[t]=e}r.mixin(n);var i=[];function s(t,e,r){1===i.push({name:t,payload:{key:e._guidKey,id:e._id,eventName:t,detail:e._result,childId:r&&r._id,label:e._label,timeStamp:Date.now(),error:n["instrument-with-stack"]?new Error(e._label):null}})&&setTimeout(function(){for(var t=0;t<i.length;t++){var e=i[t],r=e.payload;r.guid=r.key+r.id,r.childGuid=r.key+r.childId,r.error&&(r.stack=r.error.stack),n.trigger(e.name,e.payload)}i.length=0},50)}function u(t,e){if(t&&"object"==typeof t&&t.constructor===this)return t;var r=new this(c,e);return m(r,t),r}function c(){}var a=void 0,f=1,l=2,h={error:null};function p(t){try{return t.then}catch(t){return h.error=t,h}}var y=void 0;function _(){try{var t=y;return y=null,t.apply(this,arguments)}catch(t){return h.error=t,h}}function v(t){return y=t,_}function d(t,e,r){if(e.constructor===t.constructor&&r===A&&t.constructor.resolve===u)!function(t,e){e._state===f?b(t,e._result):e._state===l?(e._onError=null,g(t,e._result)):j(e,void 0,function(r){e===r?b(t,r):m(t,r)},function(e){return g(t,e)})}(t,e);else if(r===h){var o=h.error;h.error=null,g(t,o)}else"function"==typeof r?function(t,e,r){n.async(function(t){var n=!1,o=v(r).call(e,function(r){n||(n=!0,e===r?b(t,r):m(t,r))},function(e){n||(n=!0,g(t,e))},"Settle: "+(t._label||" unknown promise"));if(!n&&o===h){n=!0;var i=h.error;h.error=null,g(t,i)}},t)}(t,e,r):b(t,e)}function m(t,e){var r,n;t===e?b(t,e):(n=typeof(r=e),null===r||"object"!==n&&"function"!==n?b(t,e):d(t,e,p(e)))}function w(t){t._onError&&t._onError(t._result),O(t)}function b(t,e){t._state===a&&(t._result=e,t._state=f,0===t._subscribers.length?n.instrument&&s("fulfilled",t):n.async(O,t))}function g(t,e){t._state===a&&(t._state=l,t._result=e,n.async(w,t))}function j(t,e,r,o){var i=t._subscribers,s=i.length;t._onError=null,i[s]=e,i[s+f]=r,i[s+l]=o,0===s&&t._state&&n.async(O,t)}function O(t){var e=t._subscribers,r=t._state;if(n.instrument&&s(r===f?"fulfilled":"rejected",t),0!==e.length){for(var o=void 0,i=void 0,u=t._result,c=0;c<e.length;c+=3)o=e[c],i=e[c+r],o?E(r,o,i,u):i(u);t._subscribers.length=0}}function E(t,e,r,n){var o="function"==typeof r,i=void 0;if(i=o?v(r)(n):n,e._state!==a);else if(i===e)g(e,new TypeError("A promises callback cannot return that same promise."));else if(i===h){var s=h.error;h.error=null,g(e,s)}else o?m(e,i):t===f?b(e,i):t===l&&g(e,i)}function A(t,e,r){var o=this._state;if(o===f&&!t||o===l&&!e)return n.instrument&&s("chained",this,this),this;this._onError=null;var i=new this.constructor(c,r),u=this._result;if(n.instrument&&s("chained",this,i),o===a)j(this,i,t,e);else{var h=o===f?t:e;n.async(function(){return E(o,i,h,u)})}return i}var T=function(){function t(t,e,r,n){this._instanceConstructor=t,this.promise=new t(c,n),this._abortOnReject=r,this._isUsingOwnPromise=t===k,this._isUsingOwnResolve=t.resolve===u,this._init.apply(this,arguments)}return t.prototype._init=function(t,e){var r=e.length||0;this.length=r,this._remaining=r,this._result=new Array(r),this._enumerate(e)},t.prototype._enumerate=function(t){for(var e=this.length,r=this.promise,n=0;r._state===a&&n<e;n++)this._eachEntry(t[n],n,!0);this._checkFullfillment()},t.prototype._checkFullfillment=function(){if(0===this._remaining){var t=this._result;b(this.promise,t),this._result=null}},t.prototype._settleMaybeThenable=function(t,e,r){var n=this._instanceConstructor;if(this._isUsingOwnResolve){var o=p(t);if(o===A&&t._state!==a)t._onError=null,this._settledAt(t._state,e,t._result,r);else if("function"!=typeof o)this._settledAt(f,e,t,r);else if(this._isUsingOwnPromise){var i=new n(c);d(i,t,o),this._willSettleAt(i,e,r)}else this._willSettleAt(new n(function(e){return e(t)}),e,r)}else this._willSettleAt(n.resolve(t),e,r)},t.prototype._eachEntry=function(t,e,r){null!==t&&"object"==typeof t?this._settleMaybeThenable(t,e,r):this._setResultAt(f,e,t,r)},t.prototype._settledAt=function(t,e,r,n){var o=this.promise;o._state===a&&(this._abortOnReject&&t===l?g(o,r):(this._setResultAt(t,e,r,n),this._checkFullfillment()))},t.prototype._setResultAt=function(t,e,r,n){this._remaining--,this._result[e]=r},t.prototype._willSettleAt=function(t,e,r){var n=this;j(t,void 0,function(t){return n._settledAt(f,e,t,r)},function(t){return n._sLine truncated
window.Promise = RSVP.Promise;
}
"""
Loaded 50 of 556 files, more files were not shown because too many files have changed in this diff. Show more