forked from pichillilorenzo/flutter_inappwebview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInAppWebView.swift
More file actions
executable file
·3071 lines (2737 loc) · 151 KB
/
Copy pathInAppWebView.swift
File metadata and controls
executable file
·3071 lines (2737 loc) · 151 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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
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
79
80
81
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
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
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
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
684
685
686
687
688
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
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
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
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// InAppWebView.swift
// flutter_inappwebview
//
// Created by Lorenzo on 21/10/18.
//
import Flutter
import Foundation
import WebKit
public class InAppWebView: WKWebView, UIScrollViewDelegate, WKUIDelegate,
WKNavigationDelegate, WKScriptMessageHandler, UIGestureRecognizerDelegate,
WKDownloadDelegate,
PullToRefreshDelegate,
Disposable {
static let METHOD_CHANNEL_NAME_PREFIX = "com.pichillilorenzo/flutter_inappwebview_"
var id: Any? // viewId
var plugin: SwiftFlutterPlugin?
var windowId: Int64?
var windowCreated = false
var windowBeforeCreatedCallbacks: [() -> ()] = []
var inAppBrowserDelegate: InAppBrowserDelegate?
var channelDelegate: WebViewChannelDelegate?
var settings: InAppWebViewSettings?
var pullToRefreshControl: PullToRefreshControl?
var findInteractionController: FindInteractionController?
var webMessageChannels: [String: WebMessageChannel] = [:]
var webMessageListeners: [WebMessageListener] = []
var currentOriginalUrl: URL?
var inFullscreen = false
var preventGestureDelay = false
private static var sslCertificatesMap: [String: SslCertificate] = [:] // [URL host name : SslCertificate]
private static var credentialsProposed: [URLCredential] = []
var lastScrollX: CGFloat = 0
var lastScrollY: CGFloat = 0
// Used to manage pauseTimers() and resumeTimers()
var isPausedTimers = false
var isPausedTimersCompletionHandler: (() -> Void)?
var contextMenu: [String: Any]?
var initialUserScripts: [UserScript] = []
// https://github.com/mozilla-mobile/firefox-ios/blob/50531a7e9e4d459fb11d4fcb7d4322e08103501f/Client/Frontend/Browser/ContextMenuHelper.swift
fileprivate var nativeHighlightLongPressRecognizer: UILongPressGestureRecognizer?
fileprivate var nativeLoupeGesture: UILongPressGestureRecognizer?
var longPressRecognizer: UILongPressGestureRecognizer!
var recognizerForDisablingContextMenuOnLinks: UILongPressGestureRecognizer!
var lastLongPressTouchPoint: CGPoint?
var panGestureRecognizer: UIPanGestureRecognizer!
var lastTouchPoint: CGPoint?
var lastTouchPointTimestamp = Int64(Date().timeIntervalSince1970 * 1000)
var contextMenuIsShowing = false
// flag used for the workaround to trigger onCreateContextMenu event as the same on Android
var onCreateContextMenuEventTriggeredWhenMenuDisabled = false
var customIMPs: [IMP] = []
var callAsyncJavaScriptBelowIOS14Results: [String:((Any?) -> Void)] = [:]
var oldZoomScale = Float(1.0)
fileprivate var interceptOnlyAsyncAjaxRequestsPluginScript: PluginScript?
init(id: Any?, plugin: SwiftFlutterPlugin?, frame: CGRect, configuration: WKWebViewConfiguration,
contextMenu: [String: Any]?, userScripts: [UserScript] = []) {
super.init(frame: frame, configuration: configuration)
self.id = id
self.plugin = plugin
if let id = id, let registrar = plugin?.registrar {
let channel = FlutterMethodChannel(name: InAppWebView.METHOD_CHANNEL_NAME_PREFIX + String(describing: id),
binaryMessenger: registrar.messenger())
self.channelDelegate = WebViewChannelDelegate(webView: self, channel: channel)
}
self.contextMenu = contextMenu
self.initialUserScripts = userScripts
uiDelegate = self
navigationDelegate = self
scrollView.delegate = self
longPressRecognizer = UILongPressGestureRecognizer()
longPressRecognizer.delegate = self
longPressRecognizer.addTarget(self, action: #selector(longPressGestureDetected))
recognizerForDisablingContextMenuOnLinks = UILongPressGestureRecognizer()
recognizerForDisablingContextMenuOnLinks.delegate = self
recognizerForDisablingContextMenuOnLinks.addTarget(self, action: #selector(longPressGestureDetected))
recognizerForDisablingContextMenuOnLinks?.minimumPressDuration = 0.45
panGestureRecognizer = UIPanGestureRecognizer()
panGestureRecognizer.delegate = self
panGestureRecognizer.addTarget(self, action: #selector(endDraggingDetected))
}
override public var frame: CGRect {
get {
return super.frame
}
set {
super.frame = newValue
self.scrollView.contentInset = .zero
if #available(iOS 11, *) {
// Above iOS 11, adjust contentInset to compensate the adjustedContentInset so the sum will
// always be 0.
if (scrollView.adjustedContentInset != UIEdgeInsets.zero) {
let insetToAdjust = self.scrollView.adjustedContentInset
scrollView.contentInset = UIEdgeInsets(top: -insetToAdjust.top, left: -insetToAdjust.left,
bottom: -insetToAdjust.bottom, right: -insetToAdjust.right)
}
}
}
}
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
}
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
// BVC KVO events for all changes on the webview will call this.
// It is called frequently during a page load (particularly on progress changes and URL changes).
// As of iOS 12, WKContentView gesture setup is async, but it has been called by the time
// the webview is ready to load an URL. After this has happened, we can override the gesture.
func replaceGestureHandlerIfNeeded() {
DispatchQueue.main.async {
if self.gestureRecognizerWithDescriptionFragment("InAppWebView") == nil {
self.replaceWebViewLongPress()
}
}
}
private func replaceWebViewLongPress() {
// WebKit installs gesture handlers async. If `replaceWebViewLongPress` is called after a wkwebview in most cases a small delay is sufficient
// See also https://bugs.webkit.org/show_bug.cgi?id=193366
nativeHighlightLongPressRecognizer = gestureRecognizerWithDescriptionFragment("action=_highlightLongPressRecognized:")
nativeLoupeGesture = gestureRecognizerWithDescriptionFragment("action=loupeGesture:")
if let nativeLongPressRecognizer = gestureRecognizerWithDescriptionFragment("action=_longPressRecognized:") {
nativeLongPressRecognizer.removeTarget(nil, action: nil)
nativeLongPressRecognizer.addTarget(self, action: #selector(self.longPressGestureDetected))
}
}
private func gestureRecognizerWithDescriptionFragment(_ descriptionFragment: String) -> UILongPressGestureRecognizer? {
let result = self.scrollView.subviews.compactMap({ $0.gestureRecognizers }).joined().first(where: {
return (($0 as? UILongPressGestureRecognizer) != nil) && $0.description.contains(descriptionFragment)
})
return result as? UILongPressGestureRecognizer
}
@objc func longPressGestureDetected(_ sender: UIGestureRecognizer) {
if sender.state == .cancelled {
return
}
guard sender.state == .began else {
return
}
if sender == recognizerForDisablingContextMenuOnLinks,
let settings = settings, !settings.disableLongPressContextMenuOnLinks {
return
}
if sender == longPressRecognizer {
// To prevent the tapped link from proceeding with navigation, "cancel" the native WKWebView
// `_highlightLongPressRecognizer`. This preserves the original behavior as seen here:
// https://github.com/WebKit/webkit/blob/d591647baf54b4b300ca5501c21a68455429e182/Source/WebKit/UIProcess/ios/WKContentViewInteraction.mm#L1600-L1614
if let nativeHighlightLongPressRecognizer = nativeHighlightLongPressRecognizer,
nativeHighlightLongPressRecognizer.isEnabled {
nativeHighlightLongPressRecognizer.isEnabled = false
nativeHighlightLongPressRecognizer.isEnabled = true
}
}
//Finding actual touch location in webView
var touchLocation = sender.location(in: self)
touchLocation.x -= scrollView.contentInset.left
touchLocation.y -= scrollView.contentInset.top
touchLocation.x /= scrollView.zoomScale
touchLocation.y /= scrollView.zoomScale
lastLongPressTouchPoint = touchLocation
evaluateJavaScript("window.\(JAVASCRIPT_BRIDGE_NAME)._findElementsAtPoint(\(touchLocation.x),\(touchLocation.y))", completionHandler: {(value, error) in
if error != nil {
print("Long press gesture recognizer error: \(error?.localizedDescription ?? "")")
} else if let value = value as? [String: Any?] {
let hitTestResult = HitTestResult.fromMap(map: value)!
self.nativeLoupeGesture = self.gestureRecognizerWithDescriptionFragment("action=loupeGesture:")
if sender == self.recognizerForDisablingContextMenuOnLinks,
hitTestResult.type.rawValue > HitTestResultType.unknownType.rawValue,
hitTestResult.type.rawValue < HitTestResultType.editTextType.rawValue {
self.nativeLoupeGesture?.isEnabled = false
self.nativeLoupeGesture?.isEnabled = true
} else {
self.channelDelegate?.onLongPressHitTestResult(hitTestResult: hitTestResult)
}
} else if sender == self.longPressRecognizer {
self.channelDelegate?.onLongPressHitTestResult(hitTestResult: HitTestResult(type: .unknownType, extra: nil))
}
})
}
public override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
lastTouchPoint = point
lastTouchPointTimestamp = Int64(Date().timeIntervalSince1970 * 1000)
SharedLastTouchPointTimestamp[self] = lastTouchPointTimestamp
// re-build context menu items for the current webview
UIMenuController.shared.menuItems = []
if let menu = self.contextMenu {
if let menuItems = menu["menuItems"] as? [[String : Any]] {
for menuItem in menuItems {
let id = menuItem["id"]!
let title = menuItem["title"] as! String
let targetMethodName = "onContextMenuActionItemClicked-" + String(self.hash) + "-" +
(id is Int64 ? String(id as! Int64) : id as! String)
if !self.responds(to: Selector(targetMethodName)) {
let customAction: () -> Void = {
self.channelDelegate?.onContextMenuActionItemClicked(id: id, title: title)
if #available(iOS 16.0, *) {
if #unavailable(iOS 16.4) {
self.onHideContextMenu()
}
}
}
let castedCustomAction: AnyObject = unsafeBitCast(customAction as @convention(block) () -> Void, to: AnyObject.self)
let swizzledImplementation = imp_implementationWithBlock(castedCustomAction)
class_addMethod(InAppWebView.self, Selector(targetMethodName), swizzledImplementation, nil)
self.customIMPs.append(swizzledImplementation)
}
let item = UIMenuItem(title: title, action: Selector(targetMethodName))
UIMenuController.shared.menuItems!.append(item)
}
}
}
// https://github.com/pichillilorenzo/flutter_inappwebview/pull/1665
if preventGestureDelay, let gestures = superview?.superview?.gestureRecognizers {
for gesture in gestures {
if NSStringFromClass(type(of: gesture)) == "DelayingGestureRecognizer" {
gesture.isEnabled = false
}
}
}
return super.hitTest(point, with: event)
}
@available(iOS 13.0, *)
public override func buildMenu(with builder: UIMenuBuilder) {
if #available(iOS 16.0, *) {
if let menu = contextMenu {
let contextMenuSettings = ContextMenuSettings()
if let contextMenuSettingsMap = menu["settings"] as? [String: Any?] {
let _ = contextMenuSettings.parse(settings: contextMenuSettingsMap)
if contextMenuSettings.hideDefaultSystemContextMenuItems {
builder.remove(menu: .lookup)
}
}
}
if #unavailable(iOS 16.4), settings?.disableContextMenu == false {
contextMenuIsShowing = false
DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
self.onCreateContextMenu()
}
}
}
super.buildMenu(with: builder)
}
@available(iOS 16.4, *)
public func webView(_ webView: WKWebView, willPresentEditMenuWithAnimator animator: UIEditMenuInteractionAnimating) {
onCreateContextMenu()
}
@available(iOS 16.4, *)
public func webView(_ webView: WKWebView, willDismissEditMenuWithAnimator animator: UIEditMenuInteractionAnimating) {
onHideContextMenu()
}
public override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
var needCheck = sender is UIMenuController
if #available(iOS 13.0, *) {
needCheck = sender is UIMenuElement || sender is UIMenuController
}
if needCheck {
if settings?.disableContextMenu == true {
if !onCreateContextMenuEventTriggeredWhenMenuDisabled {
// workaround to trigger onCreateContextMenu event as the same on Android
onCreateContextMenu()
onCreateContextMenuEventTriggeredWhenMenuDisabled = true
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
self.onCreateContextMenuEventTriggeredWhenMenuDisabled = false
}
}
return false
}
if let menu = contextMenu {
let contextMenuSettings = ContextMenuSettings()
if let contextMenuSettingsMap = menu["settings"] as? [String: Any?] {
let _ = contextMenuSettings.parse(settings: contextMenuSettingsMap)
if !action.description.starts(with: "onContextMenuActionItemClicked-") && contextMenuSettings.hideDefaultSystemContextMenuItems {
return false
}
}
}
if contextMenuIsShowing, !action.description.starts(with: "onContextMenuActionItemClicked-") {
let id = action.description.compactMap({ $0.asciiValue?.description }).joined()
channelDelegate?.onContextMenuActionItemClicked(id: id, title: action.description)
if #available(iOS 16.0, *) {
if #unavailable(iOS 16.4) {
onHideContextMenu()
}
}
}
}
return super.canPerformAction(action, withSender: sender)
}
// For some reasons, using the scrollViewDidEndDragging event, in some rare cases, could block
// the scroll gesture
@objc func endDraggingDetected() {
// detect end dragging
if panGestureRecognizer.state == .ended {
// fix for pull-to-refresh jittering when the touch drag event is held
if let pullToRefreshControl = pullToRefreshControl,
pullToRefreshControl.shouldCallOnRefresh {
pullToRefreshControl.onRefresh()
}
}
}
public func prepare() {
scrollView.addGestureRecognizer(self.longPressRecognizer)
scrollView.addGestureRecognizer(self.recognizerForDisablingContextMenuOnLinks)
scrollView.addGestureRecognizer(self.panGestureRecognizer)
scrollView.addObserver(self, forKeyPath: #keyPath(UIScrollView.contentOffset), options: [.new, .old], context: nil)
scrollView.addObserver(self, forKeyPath: #keyPath(UIScrollView.zoomScale), options: [.new, .old], context: nil)
scrollView.addObserver(self, forKeyPath: #keyPath(UIScrollView.contentSize), options: [.new, .old], context: nil)
addObserver(self,
forKeyPath: #keyPath(WKWebView.estimatedProgress),
options: .new,
context: nil)
addObserver(self,
forKeyPath: #keyPath(WKWebView.url),
options: [.new, .old],
context: nil)
addObserver(self,
forKeyPath: #keyPath(WKWebView.title),
options: [.new, .old],
context: nil)
if #available(iOS 15.0, *) {
addObserver(self,
forKeyPath: #keyPath(WKWebView.cameraCaptureState),
options: [.new, .old],
context: nil)
addObserver(self,
forKeyPath: #keyPath(WKWebView.microphoneCaptureState),
options: [.new, .old],
context: nil)
}
if #unavailable(iOS 16.0) {
NotificationCenter.default.addObserver(
self,
selector: #selector(onCreateContextMenu),
name: UIMenuController.willShowMenuNotification,
object: nil)
NotificationCenter.default.addObserver(
self,
selector: #selector(onHideContextMenu),
name: UIMenuController.didHideMenuNotification,
object: nil)
}
// TODO: Still not working on iOS 16.0!
// if #available(iOS 16.0, *) {
// addObserver(self,
// forKeyPath: #keyPath(WKWebView.fullscreenState),
// options: .new,
// context: nil)
// } else {
// listen for videos playing in fullscreen
NotificationCenter.default.addObserver(self,
selector: #selector(onEnterFullscreen(_:)),
name: UIWindow.didBecomeVisibleNotification,
object: window)
// listen for videos stopping to play in fullscreen
NotificationCenter.default.addObserver(self,
selector: #selector(onExitFullscreen(_:)),
name: UIWindow.didBecomeHiddenNotification,
object: window)
// }
if let settings = settings {
if settings.transparentBackground {
isOpaque = false
backgroundColor = UIColor.clear
scrollView.backgroundColor = UIColor.clear
}
// prevent webView from bouncing
if settings.disallowOverScroll {
if responds(to: #selector(getter: scrollView)) {
scrollView.bounces = false
}
else {
for subview: UIView in subviews {
if subview is UIScrollView {
(subview as! UIScrollView).bounces = false
}
}
}
}
if #available(iOS 11.0, *) {
accessibilityIgnoresInvertColors = settings.accessibilityIgnoresInvertColors
scrollView.contentInsetAdjustmentBehavior =
UIScrollView.ContentInsetAdjustmentBehavior.init(rawValue: settings.contentInsetAdjustmentBehavior)!
}
allowsBackForwardNavigationGestures = settings.allowsBackForwardNavigationGestures
if #available(iOS 9.0, *) {
allowsLinkPreview = settings.allowsLinkPreview
if !settings.userAgent.isEmpty {
customUserAgent = settings.userAgent
}
}
if #available(iOS 13.0, *) {
scrollView.automaticallyAdjustsScrollIndicatorInsets = settings.automaticallyAdjustsScrollIndicatorInsets
}
scrollView.showsVerticalScrollIndicator = !settings.disableVerticalScroll
scrollView.showsHorizontalScrollIndicator = !settings.disableHorizontalScroll
scrollView.showsVerticalScrollIndicator = settings.verticalScrollBarEnabled
scrollView.showsHorizontalScrollIndicator = settings.horizontalScrollBarEnabled
scrollView.isScrollEnabled = !(settings.disableVerticalScroll && settings.disableHorizontalScroll)
scrollView.isDirectionalLockEnabled = settings.isDirectionalLockEnabled
scrollView.decelerationRate = Util.getDecelerationRate(type: settings.decelerationRate)
scrollView.alwaysBounceVertical = settings.alwaysBounceVertical
scrollView.alwaysBounceHorizontal = settings.alwaysBounceHorizontal
scrollView.scrollsToTop = settings.scrollsToTop
scrollView.isPagingEnabled = settings.isPagingEnabled
scrollView.maximumZoomScale = CGFloat(settings.maximumZoomScale)
scrollView.minimumZoomScale = CGFloat(settings.minimumZoomScale)
if #available(iOS 14.0, *) {
mediaType = settings.mediaType
pageZoom = CGFloat(settings.pageZoom)
}
if #available(iOS 15.0, *) {
if let underPageBackgroundColor = settings.underPageBackgroundColor, !underPageBackgroundColor.isEmpty {
self.underPageBackgroundColor = UIColor(hexString: underPageBackgroundColor)
}
}
if #available(iOS 15.5, *) {
if let minViewportInset = settings.minimumViewportInset, let maxViewportInset = settings.maximumViewportInset {
setMinimumViewportInset(minViewportInset, maximumViewportInset: maxViewportInset)
}
}
if #available(iOS 16.0, *) {
isFindInteractionEnabled = settings.isFindInteractionEnabled
}
if #available(iOS 16.4, *) {
isInspectable = settings.isInspectable
}
if settings.clearCache {
clearCache()
}
}
prepareAndAddUserScripts()
if windowId != nil {
// The new created window webview has the same WKWebViewConfiguration variable reference.
// So, we cannot set another WKWebViewConfiguration for it unfortunately!
// This is a limitation of the official WebKit API.
return
}
configuration.preferences = WKPreferences()
if let settings = settings {
if #available(iOS 9.0, *) {
configuration.allowsAirPlayForMediaPlayback = settings.allowsAirPlayForMediaPlayback
configuration.allowsPictureInPictureMediaPlayback = settings.allowsPictureInPictureMediaPlayback
}
configuration.preferences.javaScriptCanOpenWindowsAutomatically = settings.javaScriptCanOpenWindowsAutomatically
configuration.preferences.minimumFontSize = CGFloat(settings.minimumFontSize)
if #available(iOS 13.0, *) {
configuration.preferences.isFraudulentWebsiteWarningEnabled = settings.isFraudulentWebsiteWarningEnabled
configuration.defaultWebpagePreferences.preferredContentMode = WKWebpagePreferences.ContentMode(rawValue: settings.preferredContentMode)!
}
configuration.preferences.javaScriptEnabled = settings.javaScriptEnabled
if #available(iOS 14.0, *) {
configuration.defaultWebpagePreferences.allowsContentJavaScript = settings.javaScriptEnabled
}
if #available(iOS 15.0, *) {
configuration.preferences.isTextInteractionEnabled = settings.isTextInteractionEnabled
}
if #available(iOS 15.4, *) {
configuration.preferences.isSiteSpecificQuirksModeEnabled = settings.isSiteSpecificQuirksModeEnabled
configuration.preferences.isElementFullscreenEnabled = settings.isElementFullscreenEnabled
}
if #available(iOS 16.4, *) {
configuration.preferences.shouldPrintBackgrounds = settings.shouldPrintBackgrounds
}
}
}
public func prepareAndAddUserScripts() -> Void {
if windowId != nil {
// The new created window webview has the same WKWebViewConfiguration variable reference.
// So, we cannot set another WKWebViewConfiguration for it unfortunately!
// This is a limitation of the official WebKit API.
return
}
configuration.userContentController = WKUserContentController()
configuration.userContentController.initialize()
if let applePayAPIEnabled = settings?.applePayAPIEnabled, applePayAPIEnabled {
return
}
configuration.userContentController.addPluginScript(PROMISE_POLYFILL_JS_PLUGIN_SCRIPT)
configuration.userContentController.addPluginScript(JAVASCRIPT_BRIDGE_JS_PLUGIN_SCRIPT)
configuration.userContentController.addPluginScript(CONSOLE_LOG_JS_PLUGIN_SCRIPT)
configuration.userContentController.addPluginScript(PRINT_JS_PLUGIN_SCRIPT)
configuration.userContentController.addPluginScript(ON_WINDOW_BLUR_EVENT_JS_PLUGIN_SCRIPT)
configuration.userContentController.addPluginScript(ON_WINDOW_FOCUS_EVENT_JS_PLUGIN_SCRIPT)
configuration.userContentController.addPluginScript(FIND_ELEMENTS_AT_POINT_JS_PLUGIN_SCRIPT)
configuration.userContentController.addPluginScript(LAST_TOUCHED_ANCHOR_OR_IMAGE_JS_PLUGIN_SCRIPT)
configuration.userContentController.addPluginScript(FIND_TEXT_HIGHLIGHT_JS_PLUGIN_SCRIPT)
configuration.userContentController.addPluginScript(ORIGINAL_VIEWPORT_METATAG_CONTENT_JS_PLUGIN_SCRIPT)
if let settings = settings {
interceptOnlyAsyncAjaxRequestsPluginScript = createInterceptOnlyAsyncAjaxRequestsPluginScript(onlyAsync: settings.interceptOnlyAsyncAjaxRequests)
if settings.useShouldInterceptAjaxRequest {
if let interceptOnlyAsyncAjaxRequestsPluginScript = interceptOnlyAsyncAjaxRequestsPluginScript {
configuration.userContentController.addPluginScript(interceptOnlyAsyncAjaxRequestsPluginScript)
}
configuration.userContentController.addPluginScript(INTERCEPT_AJAX_REQUEST_JS_PLUGIN_SCRIPT)
}
if settings.useShouldInterceptFetchRequest {
configuration.userContentController.addPluginScript(INTERCEPT_FETCH_REQUEST_JS_PLUGIN_SCRIPT)
}
if settings.useOnLoadResource {
configuration.userContentController.addPluginScript(ON_LOAD_RESOURCE_JS_PLUGIN_SCRIPT)
}
if !settings.supportZoom {
configuration.userContentController.addPluginScript(NOT_SUPPORT_ZOOM_JS_PLUGIN_SCRIPT)
} else if settings.enableViewportScale {
configuration.userContentController.addPluginScript(ENABLE_VIEWPORT_SCALE_JS_PLUGIN_SCRIPT)
}
}
configuration.userContentController.removeScriptMessageHandler(forName: "onCallAsyncJavaScriptResultBelowIOS14Received")
configuration.userContentController.add(self, name: "onCallAsyncJavaScriptResultBelowIOS14Received")
configuration.userContentController.removeScriptMessageHandler(forName: "onWebMessagePortMessageReceived")
configuration.userContentController.add(self, name: "onWebMessagePortMessageReceived")
configuration.userContentController.removeScriptMessageHandler(forName: "onWebMessageListenerPostMessageReceived")
configuration.userContentController.add(self, name: "onWebMessageListenerPostMessageReceived")
configuration.userContentController.addUserOnlyScripts(initialUserScripts)
configuration.userContentController.sync(scriptMessageHandler: self)
}
public static func preWKWebViewConfiguration(settings: InAppWebViewSettings?) -> WKWebViewConfiguration {
let configuration = WKWebViewConfiguration()
configuration.processPool = WKProcessPoolManager.sharedProcessPool
if let settings = settings {
configuration.allowsInlineMediaPlayback = settings.allowsInlineMediaPlayback
configuration.suppressesIncrementalRendering = settings.suppressesIncrementalRendering
configuration.selectionGranularity = WKSelectionGranularity.init(rawValue: settings.selectionGranularity)!
if settings.allowUniversalAccessFromFileURLs {
configuration.setValue(settings.allowUniversalAccessFromFileURLs, forKey: "allowUniversalAccessFromFileURLs")
}
if settings.allowFileAccessFromFileURLs {
configuration.preferences.setValue(settings.allowFileAccessFromFileURLs, forKey: "allowFileAccessFromFileURLs")
}
if #available(iOS 9.0, *) {
if settings.incognito {
configuration.websiteDataStore = WKWebsiteDataStore.nonPersistent()
} else if settings.cacheEnabled {
configuration.websiteDataStore = WKWebsiteDataStore.default()
}
if !settings.applicationNameForUserAgent.isEmpty {
if let applicationNameForUserAgent = configuration.applicationNameForUserAgent {
configuration.applicationNameForUserAgent = applicationNameForUserAgent + " " + settings.applicationNameForUserAgent
}
}
}
if #available(iOS 10.0, *) {
configuration.ignoresViewportScaleLimits = settings.ignoresViewportScaleLimits
var dataDetectorTypes = WKDataDetectorTypes.init(rawValue: 0)
for type in settings.dataDetectorTypes {
let dataDetectorType = Util.getDataDetectorType(type: type)
dataDetectorTypes = WKDataDetectorTypes(rawValue: dataDetectorTypes.rawValue | dataDetectorType.rawValue)
}
configuration.dataDetectorTypes = dataDetectorTypes
configuration.mediaTypesRequiringUserActionForPlayback = settings.mediaPlaybackRequiresUserGesture ? .all : []
} else {
// Fallback on earlier versions
configuration.mediaPlaybackRequiresUserAction = settings.mediaPlaybackRequiresUserGesture
}
if #available(iOS 11.0, *) {
for scheme in settings.resourceCustomSchemes {
configuration.setURLSchemeHandler(CustomSchemeHandler(), forURLScheme: scheme)
}
if settings.sharedCookiesEnabled {
// More info to sending cookies with WKWebView
// https://stackoverflow.com/questions/26573137/can-i-set-the-cookies-to-be-used-by-a-wkwebview/26577303#26577303
// Set Cookies in iOS 11 and above, initialize websiteDataStore before setting cookies
// See also https://forums.developer.apple.com/thread/97194
// check if websiteDataStore has not been initialized before
if(!settings.incognito && !settings.cacheEnabled) {
configuration.websiteDataStore = WKWebsiteDataStore.nonPersistent()
}
for cookie in HTTPCookieStorage.shared.cookies ?? [] {
configuration.websiteDataStore.httpCookieStore.setCookie(cookie, completionHandler: nil)
}
}
}
if #available(iOS 14.0, *) {
configuration.limitsNavigationsToAppBoundDomains = settings.limitsNavigationsToAppBoundDomains
}
if #available(iOS 15.0, *) {
configuration.upgradeKnownHostsToHTTPS = settings.upgradeKnownHostsToHTTPS
}
}
return configuration
}
@objc func onCreateContextMenu() {
let mapSorted = SharedLastTouchPointTimestamp.sorted { $0.value > $1.value }
if (mapSorted.first?.key != self) {
return
}
contextMenuIsShowing = true
let hitTestResult = HitTestResult(type: .unknownType, extra: nil)
if let lastLongPressTouhLocation = lastLongPressTouchPoint {
if configuration.preferences.javaScriptEnabled {
self.evaluateJavaScript("window.\(JAVASCRIPT_BRIDGE_NAME)._findElementsAtPoint(\(lastLongPressTouhLocation.x),\(lastLongPressTouhLocation.y))", completionHandler: {(value, error) in
if error != nil {
print("Long press gesture recognizer error: \(error?.localizedDescription ?? "")")
} else if let value = value as? [String: Any?] {
self.channelDelegate?.onCreateContextMenu(hitTestResult: HitTestResult.fromMap(map: value) ?? hitTestResult)
} else {
self.channelDelegate?.onCreateContextMenu(hitTestResult: hitTestResult)
}
})
} else {
channelDelegate?.onCreateContextMenu(hitTestResult: hitTestResult)
}
} else {
channelDelegate?.onCreateContextMenu(hitTestResult: hitTestResult)
}
}
@objc func onHideContextMenu() {
if contextMenuIsShowing == false {
return
}
contextMenuIsShowing = false
channelDelegate?.onHideContextMenu()
}
override public func observeValue(forKeyPath keyPath: String?, of object: Any?,
change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == #keyPath(WKWebView.estimatedProgress) {
initializeWindowIdJS()
let progress = Int(estimatedProgress * 100)
channelDelegate?.onProgressChanged(progress: progress)
inAppBrowserDelegate?.didChangeProgress(progress: estimatedProgress)
} else if keyPath == #keyPath(WKWebView.url) && change?[.newKey] is URL {
initializeWindowIdJS()
let newUrl = change?[NSKeyValueChangeKey.newKey] as? URL
channelDelegate?.onUpdateVisitedHistory(url: newUrl?.absoluteString, isReload: nil)
inAppBrowserDelegate?.didUpdateVisitedHistory(url: newUrl)
} else if keyPath == #keyPath(WKWebView.title) && change?[.newKey] is String {
let newTitle = change?[.newKey] as? String
channelDelegate?.onTitleChanged(title: newTitle)
inAppBrowserDelegate?.didChangeTitle(title: newTitle)
} else if keyPath == #keyPath(UIScrollView.contentOffset) {
let newContentOffset = change?[.newKey] as? CGPoint
let oldContentOffset = change?[.oldKey] as? CGPoint
let startedByUser = scrollView.isDragging || scrollView.isDecelerating
if newContentOffset != oldContentOffset {
DispatchQueue.main.async {
self.onScrollChanged(startedByUser: startedByUser, oldContentOffset: oldContentOffset)
}
}
} else if keyPath == #keyPath(UIScrollView.contentSize) {
if let newContentSize = change?[.newKey] as? CGSize,
let oldContentSize = change?[.oldKey] as? CGSize,
newContentSize != oldContentSize {
DispatchQueue.main.async {
self.onContentSizeChanged(oldContentSize: oldContentSize)
}
}
}
else if #available(iOS 15.0, *) {
if keyPath == #keyPath(WKWebView.cameraCaptureState) || keyPath == #keyPath(WKWebView.microphoneCaptureState) {
var oldState: WKMediaCaptureState? = nil
if let oldValue = change?[.oldKey] as? Int {
oldState = WKMediaCaptureState.init(rawValue: oldValue)
}
var newState: WKMediaCaptureState? = nil
if let newValue = change?[.newKey] as? Int {
newState = WKMediaCaptureState.init(rawValue: newValue)
}
if oldState != newState {
if keyPath == #keyPath(WKWebView.cameraCaptureState) {
channelDelegate?.onCameraCaptureStateChanged(oldState: oldState, newState: newState)
} else {
channelDelegate?.onMicrophoneCaptureStateChanged(oldState: oldState, newState: newState)
}
}
}
} else if #available(iOS 16.0, *) {
// TODO: Still not working on iOS 16.0!
// if keyPath == #keyPath(WKWebView.fullscreenState) {
// if fullscreenState == .enteringFullscreen {
// channelDelegate?.onEnterFullscreen()
// } else if fullscreenState == .exitingFullscreen {
// channelDelegate?.onExitFullscreen()
// }
// }
}
replaceGestureHandlerIfNeeded()
}
public func initializeWindowIdJS() {
if let windowId = windowId {
if #available(iOS 14.0, *) {
let contentWorlds = configuration.userContentController.getContentWorlds(with: windowId)
for contentWorld in contentWorlds {
let source = WINDOW_ID_INITIALIZE_JS_SOURCE.replacingOccurrences(of: PluginScriptsUtil.VAR_PLACEHOLDER_VALUE, with: String(windowId))
evaluateJavascript(source: source, contentWorld: contentWorld)
}
} else {
let source = WINDOW_ID_INITIALIZE_JS_SOURCE.replacingOccurrences(of: PluginScriptsUtil.VAR_PLACEHOLDER_VALUE, with: String(windowId))
evaluateJavascript(source: source)
}
}
}
public func goBackOrForward(steps: Int) {
if canGoBackOrForward(steps: steps) {
if (steps > 0) {
let index = steps - 1
go(to: self.backForwardList.forwardList[index])
}
else if (steps < 0){
let backListLength = self.backForwardList.backList.count
let index = backListLength + steps
go(to: self.backForwardList.backList[index])
}
}
}
public func canGoBackOrForward(steps: Int) -> Bool {
let currentIndex = self.backForwardList.backList.count
return (steps >= 0)
? steps <= self.backForwardList.forwardList.count
: currentIndex + steps >= 0
}
@available(iOS 11.0, *)
public func takeScreenshot (with: [String: Any?]?, completionHandler: @escaping (_ screenshot: Data?) -> Void) {
var snapshotConfiguration: WKSnapshotConfiguration? = nil
if let with = with {
snapshotConfiguration = WKSnapshotConfiguration()
if let rect = with["rect"] as? [String: Double] {
snapshotConfiguration!.rect = CGRect.fromMap(map: rect)
}
if let snapshotWidth = with["snapshotWidth"] as? Double {
snapshotConfiguration!.snapshotWidth = NSNumber(value: snapshotWidth)
}
if #available(iOS 13.0, *), let afterScreenUpdates = with["afterScreenUpdates"] as? Bool {
snapshotConfiguration!.afterScreenUpdates = afterScreenUpdates
}
}
takeSnapshot(with: snapshotConfiguration, completionHandler: {(image, error) -> Void in
var imageData: Data? = nil
if let screenshot = image {
if let with = with {
switch with["compressFormat"] as! String {
case "JPEG":
let quality = Float(with["quality"] as! Int) / 100
imageData = screenshot.jpegData(compressionQuality: CGFloat(quality))
break
case "PNG":
imageData = screenshot.pngData()
break
default:
imageData = screenshot.pngData()
}
}
else {
imageData = screenshot.pngData()
}
}
completionHandler(imageData)
})
}
@available(iOS 14.0, *)
public func createPdf (configuration: [String: Any?]?, completionHandler: @escaping (_ pdf: Data?) -> Void) {
let pdfConfiguration: WKPDFConfiguration = .init()
if let configuration = configuration {
if let rect = configuration["rect"] as? [String: Double] {
pdfConfiguration.rect = CGRect.fromMap(map: rect)
}
}
createPDF(configuration: pdfConfiguration) { (result) in
switch (result) {
case .success(let data):
completionHandler(data)
return
case .failure(let error):
print(error.localizedDescription)
completionHandler(nil)
return
}
}
}
@available(iOS 14.0, *)
public func createWebArchiveData (dataCompletionHandler: @escaping (_ webArchiveData: Data?) -> Void) {
createWebArchiveData(completionHandler: { (result) in
switch (result) {
case .success(let data):
dataCompletionHandler(data)
return
case .failure(let error):
print(error.localizedDescription)
dataCompletionHandler(nil)
return
}
})
}
@available(iOS 14.0, *)
public func saveWebArchive (filePath: String, autoname: Bool, completionHandler: @escaping (_ path: String?) -> Void) {
createWebArchiveData(dataCompletionHandler: { (webArchiveData) in
if let webArchiveData = webArchiveData {
var localUrl = URL(fileURLWithPath: filePath)
if autoname {
if let url = self.url {
// tries to mimic Android saveWebArchive method
let invalidCharacters = CharacterSet(charactersIn: "\\/:*?\"<>|")
.union(.newlines)
.union(.illegalCharacters)
.union(.controlCharacters)
let currentPageUrlFileName = url.path
.components(separatedBy: invalidCharacters)
.joined(separator: "")
let fullPath = filePath + "/" + currentPageUrlFileName + ".webarchive"
localUrl = URL(fileURLWithPath: fullPath)
} else {
completionHandler(nil)
return
}
}
do {
try webArchiveData.write(to: localUrl)
completionHandler(localUrl.path)
} catch {
// Catch any errors
print(error.localizedDescription)
completionHandler(nil)
}
} else {
completionHandler(nil)
}
})
}
public func loadUrl(urlRequest: URLRequest, allowingReadAccessTo: URL?) {
let url = urlRequest.url!
if #available(iOS 9.0, *), let allowingReadAccessTo = allowingReadAccessTo, url.scheme == "file", allowingReadAccessTo.scheme == "file" {
loadFileURL(url, allowingReadAccessTo: allowingReadAccessTo)
} else {
load(urlRequest)
}
}
public func postUrl(url: URL, postData: Data) {
var request = URLRequest(url: url)
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
request.httpBody = postData
load(request)
}
public func loadData(data: String, mimeType: String, encoding: String, baseUrl: URL, allowingReadAccessTo: URL?) {
if #available(iOS 9.0, *), let allowingReadAccessTo = allowingReadAccessTo, baseUrl.scheme == "file", allowingReadAccessTo.scheme == "file" {
loadFileURL(baseUrl, allowingReadAccessTo: allowingReadAccessTo)
}
if #available(iOS 9.0, *) {
load(data.data(using: .utf8)!, mimeType: mimeType, characterEncodingName: encoding, baseURL: baseUrl)
} else {
loadHTMLString(data, baseURL: baseUrl)
}
}
public func loadFile(assetFilePath: String) throws {
if let plugin = plugin {
let assetURL = try Util.getUrlAsset(plugin: plugin, assetFilePath: assetFilePath)
let urlRequest = URLRequest(url: assetURL)
loadUrl(urlRequest: urlRequest, allowingReadAccessTo: nil)
}
}
func setSettings(newSettings: InAppWebViewSettings, newSettingsMap: [String: Any]) {
// MUST be the first! In this way, all the settings that uses evaluateJavaScript can be applied/blocked!
if #available(iOS 13.0, *) {
if newSettingsMap["applePayAPIEnabled"] != nil && settings?.applePayAPIEnabled != newSettings.applePayAPIEnabled {
if let settings = settings {
settings.applePayAPIEnabled = newSettings.applePayAPIEnabled
}
if !newSettings.applePayAPIEnabled {
// re-add WKUserScripts for the next page load
prepareAndAddUserScripts()
} else {
configuration.userContentController.removeAllUserScripts()
}
}
}
if newSettingsMap["transparentBackground"] != nil && settings?.transparentBackground != newSettings.transparentBackground {
if newSettings.transparentBackground {
isOpaque = false
backgroundColor = UIColor.clear
scrollView.backgroundColor = UIColor.clear
} else {
isOpaque = true
backgroundColor = nil
scrollView.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 1)
}
}
if newSettingsMap["disallowOverScroll"] != nil && settings?.disallowOverScroll != newSettings.disallowOverScroll {
if responds(to: #selector(getter: scrollView)) {
scrollView.bounces = !newSettings.disallowOverScroll
}
else {
for subview: UIView in subviews {
if subview is UIScrollView {
(subview as! UIScrollView).bounces = !newSettings.disallowOverScroll