InAppBrowserWebViewController.swift 39.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
//
//  InAppBrowserWebViewController.swift
//  flutter_inappbrowser
//
//  Created by Lorenzo on 17/09/18.
//

import Flutter
import UIKit
import WebKit
import Foundation
import AVFoundation

typealias OlderClosureType =  @convention(c) (Any, Selector, UnsafeRawPointer, Bool, Bool, Any?) -> Void
typealias NewerClosureType =  @convention(c) (Any, Selector, UnsafeRawPointer, Bool, Bool, Bool, Any?) -> Void

17
// the message needs to be concatenated with '' in order to have the same behavior like on Android
18
let consoleLogJS = """
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
(function() {
    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() {
                var message = '';
                for (var i in arguments) {
                    if (message == '') {
                        message += arguments[i];
                    }
                    else {
                        message += ' ' + arguments[i];
                    }
                }
                window.webkit.messageHandlers[oldLog].postMessage(message);
            }
        })(k);
    }
})();
"""

47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
let resourceObserverJS = """
(function() {
    var observer = new PerformanceObserver(function(list) {
        list.getEntries().forEach(function(entry) {
            window.webkit.messageHandlers['resourceLoaded'].postMessage(JSON.stringify(entry));
        });
    });
    observer.observe({entryTypes: ['resource', 'mark', 'measure']});
})();
"""

let JAVASCRIPT_BRIDGE_NAME = "flutter_inappbrowser"

let javaScriptBridgeJS = """
window.\(JAVASCRIPT_BRIDGE_NAME) = {};
window.\(JAVASCRIPT_BRIDGE_NAME).callHandler = function(handlerName, ...args) {
    window.webkit.messageHandlers['callHandler'].postMessage( {'handlerName': handlerName, 'args': JSON.stringify(args)} );
}
"""

func currentTimeInMilliSeconds() -> Int {
    let currentDate = Date()
    let since1970 = currentDate.timeIntervalSince1970
    return Int(since1970 * 1000)
}

func convertToDictionary(text: String) -> [String: Any]? {
    if let data = text.data(using: .utf8) {
        do {
            return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
        } catch {
            print(error.localizedDescription)
79 80
        }
    }
81
    return nil
82 83
}

84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
//extension WKWebView{
//
//    var keyboardDisplayRequiresUserAction: Bool? {
//        get {
//            return self.keyboardDisplayRequiresUserAction
//        }
//        set {
//            self.setKeyboardRequiresUserInteraction(newValue ?? true)
//        }
//    }
//
//    func setKeyboardRequiresUserInteraction( _ value: Bool) {
//
//        guard
//            let WKContentViewClass: AnyClass = NSClassFromString("WKContentView") else {
//                print("Cannot find the WKContentView class")
//                return
//        }
//
//        let olderSelector: Selector = sel_getUid("_startAssistingNode:userIsInteracting:blurPreviousNode:userObject:")
//        let newerSelector: Selector = sel_getUid("_startAssistingNode:userIsInteracting:blurPreviousNode:changingActivityState:userObject:")
//
//        if let method = class_getInstanceMethod(WKContentViewClass, olderSelector) {
//
//            let originalImp: IMP = method_getImplementation(method)
//            let original: OlderClosureType = unsafeBitCast(originalImp, to: OlderClosureType.self)
//            let block : @convention(block) (Any, UnsafeRawPointer, Bool, Bool, Any?) -> Void = { (me, arg0, arg1, arg2, arg3) in
//                original(me, olderSelector, arg0, !value, arg2, arg3)
//            }
//            let imp: IMP = imp_implementationWithBlock(block)
//            method_setImplementation(method, imp)
//        }
//
//        if let method = class_getInstanceMethod(WKContentViewClass, newerSelector) {
//
//            let originalImp: IMP = method_getImplementation(method)
//            let original: NewerClosureType = unsafeBitCast(originalImp, to: NewerClosureType.self)
//            let block : @convention(block) (Any, UnsafeRawPointer, Bool, Bool, Bool, Any?) -> Void = { (me, arg0, arg1, arg2, arg3, arg4) in
//                original(me, newerSelector, arg0, !value, arg2, arg3, arg4)
//            }
//            let imp: IMP = imp_implementationWithBlock(block)
//            method_setImplementation(method, imp)
//        }
//
//    }
//
//}

pichillilorenzo's avatar
pichillilorenzo committed
132
class InAppWebView_IBWrapper: InAppWebView {
133 134 135 136 137 138 139
    required convenience init?(coder: NSCoder) {
        let config = WKWebViewConfiguration()
        self.init(frame: .zero, configuration: config)
        self.translatesAutoresizingMaskIntoConstraints = false
    }
}

140
class InAppBrowserWebViewController: UIViewController, WKUIDelegate, WKNavigationDelegate, UITextFieldDelegate, WKScriptMessageHandler {
pichillilorenzo's avatar
pichillilorenzo committed
141
    
pichillilorenzo's avatar
pichillilorenzo committed
142
    @IBOutlet var webView: InAppWebView_IBWrapper!
143 144 145 146 147 148 149 150 151 152
    @IBOutlet var closeButton: UIButton!
    @IBOutlet var reloadButton: UIBarButtonItem!
    @IBOutlet var backButton: UIBarButtonItem!
    @IBOutlet var forwardButton: UIBarButtonItem!
    @IBOutlet var shareButton: UIBarButtonItem!
    @IBOutlet var spinner: UIActivityIndicatorView!
    @IBOutlet var toolbarTop: UIView!
    @IBOutlet var toolbarBottom: UIToolbar!
    @IBOutlet var urlField: UITextField!
    
pichillilorenzo's avatar
pichillilorenzo committed
153 154 155 156 157
    @IBOutlet var toolbarTop_BottomToWebViewTopConstraint: NSLayoutConstraint!
    @IBOutlet var toolbarBottom_TopToWebViewBottomConstraint: NSLayoutConstraint!
    @IBOutlet var webView_BottomFullScreenConstraint: NSLayoutConstraint!
    @IBOutlet var webView_TopFullScreenConstraint: NSLayoutConstraint!
    
158 159 160 161
    weak var navigationDelegate: SwiftFlutterPlugin?
    var currentURL: URL?
    var tmpWindow: UIWindow?
    var browserOptions: InAppBrowserOptions?
pichillilorenzo's avatar
pichillilorenzo committed
162
    var webViewOptions: InAppWebViewOptions?
163
    var initHeaders: [String: String]?
164
    var isHidden = false
165
    var uuid: String = ""
166 167
    var WKNavigationMap: [String: [String: Any]] = [:]
    var startPageTime = 0
pichillilorenzo's avatar
pichillilorenzo committed
168
    var viewPrepared = false
169 170 171 172 173 174
    
    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)!
    }
    
    override func viewWillAppear(_ animated: Bool) {
pichillilorenzo's avatar
pichillilorenzo committed
175 176 177 178 179
        if !viewPrepared {
            prepareConstraints()
            prepareWebView()
        }
        viewPrepared = true
180
        super.viewWillAppear(animated)
181 182
    }
    
pichillilorenzo's avatar
pichillilorenzo committed
183
    
184
    override func viewDidLoad() {
185 186
        super.viewDidLoad()
        
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
        webView.uiDelegate = self
        webView.navigationDelegate = self
        
        urlField.delegate = self
        urlField.text = self.currentURL?.absoluteString
        
        closeButton.addTarget(self, action: #selector(self.close), for: .touchUpInside)
        
        forwardButton.target = self
        forwardButton.action = #selector(self.goForward)
        
        forwardButton.target = self
        forwardButton.action = #selector(self.goForward)
        
        backButton.target = self
        backButton.action = #selector(self.goBack)
        
        reloadButton.target = self
        reloadButton.action = #selector(self.reload)
        
        shareButton.target = self
        shareButton.action = #selector(self.share)
        
        spinner.hidesWhenStopped = true
        spinner.isHidden = false
        spinner.stopAnimating()
pichillilorenzo's avatar
pichillilorenzo committed
213

214
        loadUrl(url: self.currentURL!, headers: self.initHeaders)
215
        
216 217 218 219
    }
    
    // Prevent crashes on closing windows
    deinit {
pichillilorenzo's avatar
pichillilorenzo committed
220 221
        webView.removeObserver(self, forKeyPath: "estimatedProgress")
        webView.uiDelegate = nil
222 223 224 225 226 227
    }
    
    override func viewWillDisappear (_ animated: Bool) {
        super.viewWillDisappear(animated)
    }
    
pichillilorenzo's avatar
pichillilorenzo committed
228 229 230 231 232
    func prepareConstraints () {
        webView_BottomFullScreenConstraint = NSLayoutConstraint(item: self.webView, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.bottom, multiplier: 1, constant: 0)
        webView_TopFullScreenConstraint = NSLayoutConstraint(item: self.webView, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.top, multiplier: 1, constant: 0)
    }
    
233
    func prepareWebView() {
234 235
        //UIApplication.shared.statusBarStyle = preferredStatusBarStyle
        
pichillilorenzo's avatar
pichillilorenzo committed
236 237 238 239 240
        self.webView.addObserver(self,
                            forKeyPath: #keyPath(WKWebView.estimatedProgress),
                            options: .new,
                            context: nil)
        
pichillilorenzo's avatar
pichillilorenzo committed
241 242 243
        self.webView.configuration.userContentController = WKUserContentController()
        self.webView.configuration.preferences = WKPreferences()
        
244 245 246 247 248 249
        if (browserOptions?.hideUrlBar)! {
            self.urlField.isHidden = true
            self.urlField.isEnabled = false
        }
        
        if (browserOptions?.toolbarTop)! {
250 251
            if browserOptions?.toolbarTopBackgroundColor != "" {
                self.toolbarTop.backgroundColor = color(fromHexString: (browserOptions?.toolbarTopBackgroundColor)!)
252 253 254
            }
        }
        else {
pichillilorenzo's avatar
pichillilorenzo committed
255 256 257
            self.toolbarTop.isHidden = true
            self.toolbarTop_BottomToWebViewTopConstraint.isActive = false
            self.webView_TopFullScreenConstraint.isActive = true
258 259 260
        }
        
        if (browserOptions?.toolbarBottom)! {
261 262
            if browserOptions?.toolbarBottomBackgroundColor != "" {
                self.toolbarBottom.backgroundColor = color(fromHexString: (browserOptions?.toolbarBottomBackgroundColor)!)
263 264 265 266
            }
            self.toolbarBottom.isTranslucent = (browserOptions?.toolbarBottomTranslucent)!
        }
        else {
pichillilorenzo's avatar
pichillilorenzo committed
267 268 269
            self.toolbarBottom.isHidden = true
            self.toolbarBottom_TopToWebViewBottomConstraint.isActive = false
            self.webView_BottomFullScreenConstraint.isActive = true
270 271 272 273 274 275 276 277 278 279 280 281 282
        }
        
        if browserOptions?.closeButtonCaption != "" {
            closeButton.setTitle(browserOptions?.closeButtonCaption, for: .normal)
        }
        if browserOptions?.closeButtonColor != "" {
            closeButton.tintColor = color(fromHexString: (browserOptions?.closeButtonColor)!)
        }
        
        self.modalPresentationStyle = UIModalPresentationStyle(rawValue: (browserOptions?.presentationStyle)!)!
        self.modalTransitionStyle = UIModalTransitionStyle(rawValue: (browserOptions?.transitionStyle)!)!
        
        // prevent webView from bouncing
pichillilorenzo's avatar
pichillilorenzo committed
283
        if (webViewOptions?.disallowOverScroll)! {
284 285 286 287 288 289 290 291 292 293 294 295
            if self.webView.responds(to: #selector(getter: self.webView.scrollView)) {
                self.webView.scrollView.bounces = false
            }
            else {
                for subview: UIView in self.webView.subviews {
                    if subview is UIScrollView {
                        (subview as! UIScrollView).bounces = false
                    }
                }
            }
        }
        
pichillilorenzo's avatar
pichillilorenzo committed
296
        if (webViewOptions?.enableViewportScale)! {
297 298 299 300 301 302 303 304 305
            let jscript = "var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);"
            let userScript = WKUserScript(source: jscript, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
            self.webView.configuration.userContentController.addUserScript(userScript)
        }
        
        // Prevents long press on links that cause WKWebView exit
        let jscriptWebkitTouchCallout = WKUserScript(source: "document.body.style.webkitTouchCallout='none';", injectionTime: .atDocumentEnd, forMainFrameOnly: true)
        self.webView.configuration.userContentController.addUserScript(jscriptWebkitTouchCallout)
        
306 307 308
        
        let consoleLogJSScript = WKUserScript(source: consoleLogJS, injectionTime: .atDocumentStart, forMainFrameOnly: false)
        self.webView.configuration.userContentController.addUserScript(consoleLogJSScript)
309 310 311 312 313
        self.webView.configuration.userContentController.add(self, name: "consoleLog")
        self.webView.configuration.userContentController.add(self, name: "consoleDebug")
        self.webView.configuration.userContentController.add(self, name: "consoleError")
        self.webView.configuration.userContentController.add(self, name: "consoleInfo")
        self.webView.configuration.userContentController.add(self, name: "consoleWarn")
314
        
315 316 317 318
        let javaScriptBridgeJSScript = WKUserScript(source: javaScriptBridgeJS, injectionTime: .atDocumentStart, forMainFrameOnly: false)
        self.webView.configuration.userContentController.addUserScript(javaScriptBridgeJSScript)
        self.webView.configuration.userContentController.add(self, name: "callHandler")
        
pichillilorenzo's avatar
pichillilorenzo committed
319 320 321
        let resourceObserverJSScript = WKUserScript(source: resourceObserverJS, injectionTime: .atDocumentStart, forMainFrameOnly: false)
        self.webView.configuration.userContentController.addUserScript(resourceObserverJSScript)
        self.webView.configuration.userContentController.add(self, name: "resourceLoaded")
322
        
323
        if #available(iOS 10.0, *) {
pichillilorenzo's avatar
pichillilorenzo committed
324
            self.webView.configuration.mediaTypesRequiringUserActionForPlayback = ((webViewOptions?.mediaPlaybackRequiresUserGesture)!) ? .all : []
325 326
        } else {
            // Fallback on earlier versions
pichillilorenzo's avatar
pichillilorenzo committed
327
            self.webView.configuration.mediaPlaybackRequiresUserAction = (webViewOptions?.mediaPlaybackRequiresUserGesture)!
328 329
        }
        
330
        
pichillilorenzo's avatar
pichillilorenzo committed
331
        self.webView.configuration.allowsInlineMediaPlayback = (webViewOptions?.allowsInlineMediaPlayback)!
332 333 334
        
        //self.webView.keyboardDisplayRequiresUserAction = browserOptions?.keyboardDisplayRequiresUserAction
        
pichillilorenzo's avatar
pichillilorenzo committed
335 336
        self.webView.configuration.suppressesIncrementalRendering = (webViewOptions?.suppressesIncrementalRendering)!
        self.webView.allowsBackForwardNavigationGestures = (webViewOptions?.allowsBackForwardNavigationGestures)!
pichillilorenzo's avatar
pichillilorenzo committed
337
        if #available(iOS 9.0, *) {
pichillilorenzo's avatar
pichillilorenzo committed
338
            self.webView.allowsLinkPreview = (webViewOptions?.allowsLinkPreview)!
pichillilorenzo's avatar
pichillilorenzo committed
339
        }
pichillilorenzo's avatar
pichillilorenzo committed
340
        
pichillilorenzo's avatar
pichillilorenzo committed
341
        if #available(iOS 10.0, *) {
pichillilorenzo's avatar
pichillilorenzo committed
342
            self.webView.configuration.ignoresViewportScaleLimits = (webViewOptions?.ignoresViewportScaleLimits)!
pichillilorenzo's avatar
pichillilorenzo committed
343
        }
pichillilorenzo's avatar
pichillilorenzo committed
344
        
pichillilorenzo's avatar
pichillilorenzo committed
345
        self.webView.configuration.allowsInlineMediaPlayback = (webViewOptions?.allowsInlineMediaPlayback)!
pichillilorenzo's avatar
pichillilorenzo committed
346
        
pichillilorenzo's avatar
pichillilorenzo committed
347
        if #available(iOS 9.0, *) {
pichillilorenzo's avatar
pichillilorenzo committed
348
            self.webView.configuration.allowsPictureInPictureMediaPlayback = (webViewOptions?.allowsPictureInPictureMediaPlayback)!
pichillilorenzo's avatar
pichillilorenzo committed
349
        }
pichillilorenzo's avatar
pichillilorenzo committed
350
        
pichillilorenzo's avatar
pichillilorenzo committed
351
        self.webView.configuration.preferences.javaScriptCanOpenWindowsAutomatically = (webViewOptions?.javaScriptCanOpenWindowsAutomatically)!
pichillilorenzo's avatar
pichillilorenzo committed
352
        
pichillilorenzo's avatar
pichillilorenzo committed
353
        self.webView.configuration.preferences.javaScriptEnabled = (webViewOptions?.javaScriptEnabled)!
354
        
pichillilorenzo's avatar
pichillilorenzo committed
355
        if ((webViewOptions?.userAgent)! != "") {
356
            if #available(iOS 9.0, *) {
pichillilorenzo's avatar
pichillilorenzo committed
357
                self.webView.customUserAgent = (webViewOptions?.userAgent)!
358 359 360
            }
        }
        
pichillilorenzo's avatar
pichillilorenzo committed
361
        if (webViewOptions?.clearCache)! {
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
            clearCache()
        }
        
    }
    
    func loadUrl(url: URL, headers: [String: String]?) {
        var request = URLRequest(url: url)
        currentURL = url
        updateUrlTextField(url: (currentURL?.absoluteString)!)
        
        if headers != nil {
            for (key, value) in headers! {
                request.setValue(value, forHTTPHeaderField: key)
            }
        }
        
        webView.load(request)
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
    }
    
    // Load user requested url
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        if textField.text != nil && textField.text != "" {
            let url = textField.text?.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
            let request = URLRequest(url: URL(string: url!)!)
            webView.load(request)
        }
        else {
            updateUrlTextField(url: (currentURL?.absoluteString)!)
        }
        //var list : WKBackForwardList = self.webView.backForwardList
        return false
    }
    
    func setWebViewFrame(_ frame: CGRect) {
        print("Setting the WebView's frame to \(NSStringFromCGRect(frame))")
        webView.frame = frame
    }
    
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418
    func clearCache() {
        if #available(iOS 9.0, *) {
            //let websiteDataTypes = NSSet(array: [WKWebsiteDataTypeDiskCache, WKWebsiteDataTypeMemoryCache])
            let date = NSDate(timeIntervalSince1970: 0)
            WKWebsiteDataStore.default().removeData(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes(), modifiedSince: date as Date, completionHandler:{ })
        } else {
            var libraryPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.libraryDirectory, FileManager.SearchPathDomainMask.userDomainMask, false).first!
            libraryPath += "/Cookies"
            
            do {
                try FileManager.default.removeItem(atPath: libraryPath)
            } catch {
                print("can't clear cache")
            }
            URLCache.shared.removeAllCachedResponses()
        }
    }
    
419 420 421 422 423 424 425 426 427 428
    @objc func reload () {
        webView.reload()
    }
    
    @objc func share () {
        let vc = UIActivityViewController(activityItems: [currentURL ?? ""], applicationActivities: [])
        present(vc, animated: true, completion: nil)
    }
    
    @objc func close() {
pichillilorenzo's avatar
pichillilorenzo committed
429
        //currentURL = nil
pichillilorenzo's avatar
pichillilorenzo committed
430
        
431 432 433 434 435 436 437 438
        weak var weakSelf = self
        
        // Run later to avoid the "took a long time" log message.
        DispatchQueue.main.async(execute: {() -> Void in
            if (weakSelf?.responds(to: #selector(getter: self.presentingViewController)))! {
                weakSelf?.presentingViewController?.dismiss(animated: true, completion: {() -> Void in
                    self.tmpWindow?.windowLevel = 0.0
                    UIApplication.shared.delegate?.window??.makeKeyAndVisible()
pichillilorenzo's avatar
pichillilorenzo committed
439 440 441
                    if (self.navigationDelegate != nil) {
                        self.navigationDelegate?.browserExit(uuid: self.uuid)
                    }
442 443 444 445 446 447
                })
            }
            else {
                weakSelf?.parent?.dismiss(animated: true, completion: {() -> Void in
                    self.tmpWindow?.windowLevel = 0.0
                    UIApplication.shared.delegate?.window??.makeKeyAndVisible()
pichillilorenzo's avatar
pichillilorenzo committed
448 449 450
                    if (self.navigationDelegate != nil) {
                        self.navigationDelegate?.browserExit(uuid: self.uuid)
                    }
451 452 453 454 455
                })
            }
        })
    }
    
456 457
    func canGoBack() -> Bool {
        return webView.canGoBack
458 459
    }
    
pichillilorenzo's avatar
pichillilorenzo committed
460
    @objc func goBack() {
461
        if canGoBack() {
pichillilorenzo's avatar
pichillilorenzo committed
462 463 464
            webView.goBack()
            updateUrlTextField(url: (webView?.url?.absoluteString)!)
        }
465 466
    }
    
467 468 469 470
    func canGoForward() -> Bool {
        return webView.canGoForward
    }
    
pichillilorenzo's avatar
pichillilorenzo committed
471
    @objc func goForward() {
472
        if canGoForward() {
pichillilorenzo's avatar
pichillilorenzo committed
473 474 475
            webView.goForward()
            updateUrlTextField(url: (webView?.url?.absoluteString)!)
        }
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
    }
    
    func updateUrlTextField(url: String) {
        urlField.text = url
    }
    
    //
    // On iOS 7 the status bar is part of the view's dimensions, therefore it's height has to be taken into account.
    // The height of it could be hardcoded as 20 pixels, but that would assume that the upcoming releases of iOS won't
    // change that value.
    //
    
    func getStatusBarOffset() -> Float {
        let statusBarFrame: CGRect = UIApplication.shared.statusBarFrame
        let statusBarOffset: Float = Float(min(statusBarFrame.size.width, statusBarFrame.size.height))
        return statusBarOffset
    }
    
    // Helper function to convert hex color string to UIColor
    // Assumes input like "#00FF00" (#RRGGBB).
    // Taken from https://stackoverflow.com/questions/1560081/how-can-i-create-a-uicolor-from-a-hex-string
    
    func color(fromHexString: String, alpha:CGFloat? = 1.0) -> UIColor {
        
        // Convert hex string to an integer
        let hexint = Int(self.intFromHexString(hexStr: fromHexString))
        let red = CGFloat((hexint & 0xff0000) >> 16) / 255.0
        let green = CGFloat((hexint & 0xff00) >> 8) / 255.0
        let blue = CGFloat((hexint & 0xff) >> 0) / 255.0
        let alpha = alpha!
        
        // Create color object, specifying alpha as well
        let color = UIColor(red: red, green: green, blue: blue, alpha: alpha)
        return color
    }
    
    func intFromHexString(hexStr: String) -> UInt32 {
        var hexInt: UInt32 = 0
        // Create scanner
        let scanner: Scanner = Scanner(string: hexStr)
        // Tell scanner to skip the # character
        scanner.charactersToBeSkipped = CharacterSet(charactersIn: "#")
        // Scan hex value
        scanner.scanHexInt32(&hexInt)
        return hexInt
    }
    
pichillilorenzo's avatar
pichillilorenzo committed
523 524 525 526
    func webView(_ webView: WKWebView,
                 decidePolicyFor navigationAction: WKNavigationAction,
                 decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        
527 528
        if let url = navigationAction.request.url {
            
pichillilorenzo's avatar
pichillilorenzo committed
529
            if url.absoluteString != self.currentURL?.absoluteString && (webViewOptions?.useOnLoadResource)! {
530 531 532 533 534 535
                WKNavigationMap[url.absoluteString] = [
                    "startTime": currentTimeInMilliSeconds(),
                    "request": navigationAction.request
                ]
            }
            
pichillilorenzo's avatar
pichillilorenzo committed
536
            if navigationAction.navigationType == .linkActivated && (webViewOptions?.useShouldOverrideUrlLoading)! {
pichillilorenzo's avatar
pichillilorenzo committed
537 538 539
                if navigationDelegate != nil {
                    navigationDelegate?.shouldOverrideUrlLoading(uuid: self.uuid, webView: webView, url: url)
                }
540 541 542 543 544 545 546 547
                decisionHandler(.cancel)
                return
            }
            
            if navigationAction.navigationType == .linkActivated || navigationAction.navigationType == .backForward {
                currentURL = url
                updateUrlTextField(url: (url.absoluteString))
            }
548 549
        }
        
pichillilorenzo's avatar
pichillilorenzo committed
550 551 552 553
        
        decisionHandler(.allow)
    }
    
554 555 556
    func webView(_ webView: WKWebView,
                 decidePolicyFor navigationResponse: WKNavigationResponse,
                 decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
557
        
pichillilorenzo's avatar
pichillilorenzo committed
558
        if (webViewOptions?.useOnLoadResource)! {
559 560 561 562 563 564 565 566 567 568
            if let url = navigationResponse.response.url {
                if WKNavigationMap[url.absoluteString] != nil {
                    let startResourceTime = (WKNavigationMap[url.absoluteString]!["startTime"] as! Int)
                    let startTime = startResourceTime - startPageTime;
                    let duration = currentTimeInMilliSeconds() - startResourceTime;
                    self.didReceiveResourceResponse(navigationResponse.response, fromRequest: WKNavigationMap[url.absoluteString]!["request"] as? URLRequest, withData: Data(), startTime: startTime, duration: duration)
                }
            }
        }
        
569 570 571
        decisionHandler(.allow)
    }

572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
//    func webView(_ webView: WKWebView,
//                 decidePolicyFor navigationResponse: WKNavigationResponse,
//                 decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
//        let mimeType = navigationResponse.response.mimeType
//        if mimeType != nil && !mimeType!.starts(with: "text/") {
//            download(url: webView.url)
//            decisionHandler(.cancel)
//            return
//        }
//        decisionHandler(.allow)
//    }
//
//    func download (url: URL?) {
//        let filename = url?.lastPathComponent
//
//        let destination: DownloadRequest.DownloadFileDestination = { _, _ in
//            let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
//            let fileURL = documentsURL.appendingPathComponent(filename!)
//
//            return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
//        }
//
//        Alamofire.download((url?.absoluteString)!, to: destination).downloadProgress { progress in
//            print("Download Progress: \(progress.fractionCompleted)")
//            }.response { response in
//                if response.error == nil, let path = response.destinationURL?.path {
//                    UIAlertView(title: nil, message: "File saved to " + path, delegate: nil, cancelButtonTitle: nil).show()
//                }
//                else {
//                   UIAlertView(title: nil, message: "Cannot save " + filename!, delegate: nil, cancelButtonTitle: nil).show()
//                }
//            }
//    }
    
606
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
607 608 609
        
        self.startPageTime = currentTimeInMilliSeconds()
        
610 611 612
        // loading url, start spinner, update back/forward
        backButton.isEnabled = webView.canGoBack
        forwardButton.isEnabled = webView.canGoForward
pichillilorenzo's avatar
pichillilorenzo committed
613

614 615 616 617
        if (browserOptions?.spinner)! {
            spinner.startAnimating()
        }
        
pichillilorenzo's avatar
pichillilorenzo committed
618 619 620
        if navigationDelegate != nil {
            navigationDelegate?.onLoadStart(uuid: self.uuid, webView: webView)
        }
621 622 623
    }
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
624
        self.WKNavigationMap = [:]
625 626 627 628 629 630
        // update url, stop spinner, update back/forward
        currentURL = webView.url
        updateUrlTextField(url: (currentURL?.absoluteString)!)
        backButton.isEnabled = webView.canGoBack
        forwardButton.isEnabled = webView.canGoForward
        spinner.stopAnimating()
pichillilorenzo's avatar
pichillilorenzo committed
631 632 633 634
        
        if navigationDelegate != nil {
            navigationDelegate?.onLoadStop(uuid: self.uuid, webView: webView)
        }
635 636
    }
    
637 638 639 640 641
    func webView(_ view: WKWebView,
                      didFailProvisionalNavigation navigation: WKNavigation!,
                      withError error: Error) {
        webView(view, didFail: navigation, withError: error)
    }
642
    
643 644 645 646
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        backButton.isEnabled = webView.canGoBack
        forwardButton.isEnabled = webView.canGoForward
        spinner.stopAnimating()
pichillilorenzo's avatar
pichillilorenzo committed
647 648 649 650
        
        if navigationDelegate != nil {
            navigationDelegate?.onLoadError(uuid: self.uuid, webView: webView, error: error)
        }
651
    }
652
    
653
    func didReceiveResourceResponse(_ response: URLResponse, fromRequest request: URLRequest?, withData data: Data, startTime: Int, duration: Int) {
pichillilorenzo's avatar
pichillilorenzo committed
654 655 656
        if navigationDelegate != nil {
            navigationDelegate?.onLoadResource(uuid: self.uuid, webView: webView, response: response, fromRequest: request, withData: data, startTime: startTime, duration: duration)
        }
657 658
    }
    
659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        if message.name.starts(with: "console") {
            var messageLevel = "LOG"
            switch (message.name) {
                case "consoleLog":
                    messageLevel = "LOG"
                    break;
                case "consoleDebug":
                    // on Android, console.debug is TIP
                    messageLevel = "TIP"
                    break;
                case "consoleError":
                    messageLevel = "ERROR"
                    break;
                case "consoleInfo":
                    // on Android, console.info is LOG
                    messageLevel = "LOG"
                    break;
                case "consoleWarn":
                    messageLevel = "WARNING"
                    break;
                default:
                    messageLevel = "LOG"
                    break;
            }
pichillilorenzo's avatar
pichillilorenzo committed
684 685 686
            if navigationDelegate != nil {
                navigationDelegate?.onConsoleMessage(uuid: self.uuid, sourceURL: "", lineNumber: 1, message: message.body as! String, messageLevel: messageLevel)
            }
687
        }
pichillilorenzo's avatar
pichillilorenzo committed
688
        else if message.name == "resourceLoaded" && (webViewOptions?.useOnLoadResource)! {
689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717
            if let resource = convertToDictionary(text: message.body as! String) {
                let url = URL(string: resource["name"] as! String)!
                if !UIApplication.shared.canOpenURL(url) {
                    return
                }
                let startTime = Int(resource["startTime"] as! Double)
                let duration = Int(resource["duration"] as! Double)
                var urlRequest = URLRequest(url: url)
                urlRequest.allHTTPHeaderFields = [:]
                let config = URLSessionConfiguration.default
                let session = URLSession(configuration: config)
                let task = session.dataTask(with: urlRequest) { (data, response, error) in
                    if error != nil {
                        print(error)
                        return
                    }
                    var withData = data
                    if withData == nil {
                        withData = Data()
                    }
                    self.didReceiveResourceResponse(response!, fromRequest: urlRequest, withData: withData!, startTime: startTime, duration: duration)
                }
                task.resume()
            }
        }
        else if message.name == "callHandler" {
            let body = message.body as! [String: Any]
            let handlerName = body["handlerName"] as! String
            let args = body["args"] as! String
pichillilorenzo's avatar
pichillilorenzo committed
718 719 720
            if navigationDelegate != nil {
                self.navigationDelegate?.onCallJsHandler(uuid: self.uuid, webView: webView, handlerName: handlerName, args: args)
            }
721
        }
722
    }
pichillilorenzo's avatar
pichillilorenzo committed
723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
    
    func takeScreenshot (completionHandler: @escaping (_ screenshot: Data?) -> Void) {
        if #available(iOS 11.0, *) {
            self.webView.takeSnapshot(with: nil, completionHandler: {(image, error) -> Void in
                var imageData: Data? = nil
                if let screenshot = image {
                    imageData = UIImagePNGRepresentation(screenshot)!
                }
                completionHandler(imageData)
            })
        } else {
            completionHandler(nil)
        }
    }

    func setOptions(newOptions: InAppBrowserOptions, newOptionsMap: [String: Any]) {
        
pichillilorenzo's avatar
pichillilorenzo committed
740 741 742
        let newInAppWebViewOptions = InAppWebViewOptions()
        newInAppWebViewOptions.parse(options: newOptionsMap)
        
pichillilorenzo's avatar
pichillilorenzo committed
743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796
        if newOptionsMap["hidden"] != nil && browserOptions?.hidden != newOptions.hidden {
            if newOptions.hidden {
                self.navigationDelegate?.hide(uuid: self.uuid)
            }
            else {
                self.navigationDelegate?.show(uuid: self.uuid)
            }
        }

        if newOptionsMap["hideUrlBar"] != nil && browserOptions?.hideUrlBar != newOptions.hideUrlBar {
            self.urlField.isHidden = newOptions.hideUrlBar
            self.urlField.isEnabled = !newOptions.hideUrlBar
        }
        
        if newOptionsMap["toolbarTop"] != nil && browserOptions?.toolbarTop != newOptions.toolbarTop {
            self.webView_TopFullScreenConstraint.isActive = !newOptions.toolbarTop
            self.toolbarTop.isHidden = !newOptions.toolbarTop
            self.toolbarTop_BottomToWebViewTopConstraint.isActive = newOptions.toolbarTop
        }
        
        if newOptionsMap["toolbarTopBackgroundColor"] != nil && browserOptions?.toolbarTopBackgroundColor != newOptions.toolbarTopBackgroundColor && newOptions.toolbarTopBackgroundColor != "" {
            self.toolbarTop.backgroundColor = color(fromHexString: newOptions.toolbarTopBackgroundColor)
        }
        
        if newOptionsMap["toolbarBottom"] != nil && browserOptions?.toolbarBottom != newOptions.toolbarBottom {
            self.webView_BottomFullScreenConstraint.isActive = !newOptions.toolbarBottom
            self.toolbarBottom.isHidden = !newOptions.toolbarBottom
            self.toolbarBottom_TopToWebViewBottomConstraint.isActive = newOptions.toolbarBottom
        }
        
        if newOptionsMap["toolbarBottomBackgroundColor"] != nil && browserOptions?.toolbarBottomBackgroundColor != newOptions.toolbarBottomBackgroundColor && newOptions.toolbarBottomBackgroundColor != "" {
            self.toolbarBottom.backgroundColor = color(fromHexString: newOptions.toolbarBottomBackgroundColor)
        }
        
        if newOptionsMap["toolbarBottomTranslucent"] != nil && browserOptions?.toolbarBottomTranslucent != newOptions.toolbarBottomTranslucent {
            self.toolbarBottom.isTranslucent = newOptions.toolbarBottomTranslucent
        }
        
        if newOptionsMap["closeButtonCaption"] != nil && browserOptions?.closeButtonCaption != newOptions.closeButtonCaption && newOptions.closeButtonCaption != "" {
            closeButton.setTitle(newOptions.closeButtonCaption, for: .normal)
        }
        
        if newOptionsMap["closeButtonColor"] != nil && browserOptions?.closeButtonColor != newOptions.closeButtonColor && newOptions.closeButtonColor != "" {
            closeButton.tintColor = color(fromHexString: newOptions.closeButtonColor)
        }
        
        if newOptionsMap["presentationStyle"] != nil && browserOptions?.presentationStyle != newOptions.presentationStyle {
            self.modalPresentationStyle = UIModalPresentationStyle(rawValue: newOptions.presentationStyle)!
        }
        
        if newOptionsMap["transitionStyle"] != nil && browserOptions?.transitionStyle != newOptions.transitionStyle {
            self.modalTransitionStyle = UIModalTransitionStyle(rawValue: newOptions.transitionStyle)!
        }

pichillilorenzo's avatar
pichillilorenzo committed
797
        if newOptionsMap["disallowOverScroll"] != nil && webViewOptions?.disallowOverScroll != newInAppWebViewOptions.disallowOverScroll {
pichillilorenzo's avatar
pichillilorenzo committed
798
            if self.webView.responds(to: #selector(getter: self.webView.scrollView)) {
pichillilorenzo's avatar
pichillilorenzo committed
799
                self.webView.scrollView.bounces = !newInAppWebViewOptions.disallowOverScroll
pichillilorenzo's avatar
pichillilorenzo committed
800 801 802 803
            }
            else {
                for subview: UIView in self.webView.subviews {
                    if subview is UIScrollView {
pichillilorenzo's avatar
pichillilorenzo committed
804
                        (subview as! UIScrollView).bounces = !newInAppWebViewOptions.disallowOverScroll
pichillilorenzo's avatar
pichillilorenzo committed
805 806 807 808 809
                    }
                }
            }
        }

pichillilorenzo's avatar
pichillilorenzo committed
810
        if newOptionsMap["enableViewportScale"] != nil && webViewOptions?.enableViewportScale != newInAppWebViewOptions.enableViewportScale && newInAppWebViewOptions.enableViewportScale {
pichillilorenzo's avatar
pichillilorenzo committed
811 812 813 814
            let jscript = "var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);"
            self.webView.evaluateJavaScript(jscript, completionHandler: nil)
        }
        
pichillilorenzo's avatar
pichillilorenzo committed
815
        if newOptionsMap["mediaPlaybackRequiresUserGesture"] != nil && webViewOptions?.mediaPlaybackRequiresUserGesture != newInAppWebViewOptions.mediaPlaybackRequiresUserGesture {
pichillilorenzo's avatar
pichillilorenzo committed
816
            if #available(iOS 10.0, *) {
pichillilorenzo's avatar
pichillilorenzo committed
817
                self.webView.configuration.mediaTypesRequiringUserActionForPlayback = (newInAppWebViewOptions.mediaPlaybackRequiresUserGesture) ? .all : []
pichillilorenzo's avatar
pichillilorenzo committed
818 819
            } else {
                // Fallback on earlier versions
pichillilorenzo's avatar
pichillilorenzo committed
820
                self.webView.configuration.mediaPlaybackRequiresUserAction = newInAppWebViewOptions.mediaPlaybackRequiresUserGesture
pichillilorenzo's avatar
pichillilorenzo committed
821 822 823
            }
        }

pichillilorenzo's avatar
pichillilorenzo committed
824 825
        if newOptionsMap["allowsInlineMediaPlayback"] != nil && webViewOptions?.allowsInlineMediaPlayback != newInAppWebViewOptions.allowsInlineMediaPlayback {
            self.webView.configuration.allowsInlineMediaPlayback = newInAppWebViewOptions.allowsInlineMediaPlayback
pichillilorenzo's avatar
pichillilorenzo committed
826 827 828 829 830 831
        }
        
//        if newOptionsMap["keyboardDisplayRequiresUserAction"] != nil && browserOptions?.keyboardDisplayRequiresUserAction != newOptions.keyboardDisplayRequiresUserAction {
//            self.webView.keyboardDisplayRequiresUserAction = newOptions.keyboardDisplayRequiresUserAction
//        }
        
pichillilorenzo's avatar
pichillilorenzo committed
832 833
        if newOptionsMap["suppressesIncrementalRendering"] != nil && webViewOptions?.suppressesIncrementalRendering != newInAppWebViewOptions.suppressesIncrementalRendering {
            self.webView.configuration.suppressesIncrementalRendering = newInAppWebViewOptions.suppressesIncrementalRendering
pichillilorenzo's avatar
pichillilorenzo committed
834 835
        }
        
pichillilorenzo's avatar
pichillilorenzo committed
836 837
        if newOptionsMap["allowsBackForwardNavigationGestures"] != nil && webViewOptions?.allowsBackForwardNavigationGestures != newInAppWebViewOptions.allowsBackForwardNavigationGestures {
            self.webView.allowsBackForwardNavigationGestures = newInAppWebViewOptions.allowsBackForwardNavigationGestures
pichillilorenzo's avatar
pichillilorenzo committed
838 839
        }
        
pichillilorenzo's avatar
pichillilorenzo committed
840
        if newOptionsMap["allowsLinkPreview"] != nil && webViewOptions?.allowsLinkPreview != newInAppWebViewOptions.allowsLinkPreview {
pichillilorenzo's avatar
pichillilorenzo committed
841
            if #available(iOS 9.0, *) {
pichillilorenzo's avatar
pichillilorenzo committed
842
                self.webView.allowsLinkPreview = newInAppWebViewOptions.allowsLinkPreview
pichillilorenzo's avatar
pichillilorenzo committed
843 844 845
            }
        }
        
pichillilorenzo's avatar
pichillilorenzo committed
846
        if newOptionsMap["ignoresViewportScaleLimits"] != nil && webViewOptions?.ignoresViewportScaleLimits != newInAppWebViewOptions.ignoresViewportScaleLimits {
pichillilorenzo's avatar
pichillilorenzo committed
847
            if #available(iOS 10.0, *) {
pichillilorenzo's avatar
pichillilorenzo committed
848
                self.webView.configuration.ignoresViewportScaleLimits = newInAppWebViewOptions.ignoresViewportScaleLimits
pichillilorenzo's avatar
pichillilorenzo committed
849 850 851
            }
        }
        
pichillilorenzo's avatar
pichillilorenzo committed
852 853
        if newOptionsMap["allowsInlineMediaPlayback"] != nil && webViewOptions?.allowsInlineMediaPlayback != newInAppWebViewOptions.allowsInlineMediaPlayback {
            self.webView.configuration.allowsInlineMediaPlayback = newInAppWebViewOptions.allowsInlineMediaPlayback
pichillilorenzo's avatar
pichillilorenzo committed
854 855
        }
        
pichillilorenzo's avatar
pichillilorenzo committed
856
        if newOptionsMap["allowsPictureInPictureMediaPlayback"] != nil && webViewOptions?.allowsPictureInPictureMediaPlayback != newInAppWebViewOptions.allowsPictureInPictureMediaPlayback {
pichillilorenzo's avatar
pichillilorenzo committed
857
            if #available(iOS 9.0, *) {
pichillilorenzo's avatar
pichillilorenzo committed
858
                self.webView.configuration.allowsPictureInPictureMediaPlayback = newInAppWebViewOptions.allowsPictureInPictureMediaPlayback
pichillilorenzo's avatar
pichillilorenzo committed
859 860 861
            }
        }
        
pichillilorenzo's avatar
pichillilorenzo committed
862 863
        if newOptionsMap["javaScriptCanOpenWindowsAutomatically"] != nil && webViewOptions?.javaScriptCanOpenWindowsAutomatically != newInAppWebViewOptions.javaScriptCanOpenWindowsAutomatically {
            self.webView.configuration.preferences.javaScriptCanOpenWindowsAutomatically = newInAppWebViewOptions.javaScriptCanOpenWindowsAutomatically
pichillilorenzo's avatar
pichillilorenzo committed
864 865
        }
        
pichillilorenzo's avatar
pichillilorenzo committed
866 867
        if newOptionsMap["javaScriptEnabled"] != nil && webViewOptions?.javaScriptEnabled != newInAppWebViewOptions.javaScriptEnabled {
            self.webView.configuration.preferences.javaScriptEnabled = newInAppWebViewOptions.javaScriptEnabled
pichillilorenzo's avatar
pichillilorenzo committed
868 869
        }

pichillilorenzo's avatar
pichillilorenzo committed
870
        if newOptionsMap["userAgent"] != nil && webViewOptions?.userAgent != newInAppWebViewOptions.userAgent && (newInAppWebViewOptions.userAgent != "") {
pichillilorenzo's avatar
pichillilorenzo committed
871
            if #available(iOS 9.0, *) {
pichillilorenzo's avatar
pichillilorenzo committed
872
                self.webView.customUserAgent = newInAppWebViewOptions.userAgent
pichillilorenzo's avatar
pichillilorenzo committed
873 874 875
            }
        }

pichillilorenzo's avatar
pichillilorenzo committed
876
        if newOptionsMap["clearCache"] != nil && newInAppWebViewOptions.clearCache {
pichillilorenzo's avatar
pichillilorenzo committed
877 878 879 880
            clearCache()
        }
        
        self.browserOptions = newOptions
pichillilorenzo's avatar
pichillilorenzo committed
881
        self.webViewOptions = newInAppWebViewOptions
pichillilorenzo's avatar
pichillilorenzo committed
882 883 884
    }
    
    func getOptions() -> [String: Any]? {
pichillilorenzo's avatar
pichillilorenzo committed
885 886 887 888 889 890 891 892 893 894 895 896 897 898
        if (self.browserOptions == nil || self.webViewOptions == nil) {
            return nil
        }
        var optionsMap = self.browserOptions!.getHashMap()
        optionsMap.merge(self.webViewOptions!.getHashMap(), uniquingKeysWith: { (current, _) in current })
        return optionsMap
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?,
                               change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "estimatedProgress" {
            let progress = Int(webView.estimatedProgress * 100)
            self.navigationDelegate?.onProgressChanged(uuid: self.uuid, webView: self.webView, progress: progress)
        }
pichillilorenzo's avatar
pichillilorenzo committed
899
    }
900
}