-
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathWebView.swift
More file actions
2142 lines (1906 loc) · 82 KB
/
Copy pathWebView.swift
File metadata and controls
2142 lines (1906 loc) · 82 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
// Copyright 2024–2026 Skip
// SPDX-License-Identifier: MPL-2.0
#if !SKIP_BRIDGE
import Foundation
import SwiftUI
import OSLog
import Combine
#if !SKIP
import WebKit
public typealias PlatformWebView = WKWebView
#else
public typealias PlatformWebView = android.webkit.WebView
//import android.webkit.WebView // not imported because it conflicts with SkipWeb.WebView
import androidx.compose.runtime.Composable
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.ui.viewinterop.AndroidView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat.startActivity
import android.webkit.WebViewClient
import android.webkit.JavascriptInterface
import android.webkit.WebResourceRequest
import android.webkit.WebResourceResponse
import android.view.ViewGroup
import androidx.webkit.WebSettingsCompat
import androidx.webkit.WebViewAssetLoader
import androidx.webkit.WebViewClientCompat
import androidx.webkit.WebViewCompat
import androidx.webkit.WebViewFeature
#endif
/// Metadata for a browser navigation that the platform runtime wants to treat as a download.
public struct WebDownloadRequest: Equatable, Hashable, Sendable {
public let url: URL?
public let suggestedFilename: String?
public let mimeType: String?
public let contentDisposition: String?
public let contentLength: Int64?
public init(
url: URL?,
suggestedFilename: String? = nil,
mimeType: String? = nil,
contentDisposition: String? = nil,
contentLength: Int64? = nil
) {
self.url = url
self.suggestedFilename = suggestedFilename
self.mimeType = mimeType
self.contentDisposition = contentDisposition
if let contentLength, contentLength >= 0 {
self.contentLength = contentLength
} else {
self.contentLength = nil
}
}
/// Returns whether a response should be treated as a download instead of a page.
public static func shouldTreatResponseAsDownload(
canShowMIMEType: Bool,
contentDisposition: String?,
mimeType: String? = nil,
url: URL? = nil
) -> Bool {
if let dispositionType = normalizedContentDispositionType(contentDisposition) {
if dispositionType == "attachment" {
return true
}
}
let isInlineDisposition = normalizedContentDispositionType(contentDisposition) == "inline"
if normalizedMIMEType(mimeType) == "application/octet-stream" {
if hasKnownPlayableMediaSignal(url) {
return false
}
return !isInlineDisposition || !canShowMIMEType
}
if hasKnownPlayableMediaSignal(url) {
return false
}
if isInlineDisposition, canShowMIMEType {
return false
}
return !canShowMIMEType
}
private static func normalizedContentDispositionType(_ contentDisposition: String?) -> String? {
contentDisposition?
.split(separator: ";", maxSplits: 1)
.first?
.trimmingCharacters(in: .whitespacesAndNewlines)
.lowercased()
}
private static func normalizedMIMEType(_ mimeType: String?) -> String? {
mimeType?
.split(separator: ";", maxSplits: 1)
.first?
.trimmingCharacters(in: .whitespacesAndNewlines)
.lowercased()
}
private static func hasKnownPlayableMediaSignal(_ url: URL?) -> Bool {
guard let pathExtension = url?.pathExtension.lowercased(),
!pathExtension.isEmpty else {
return false
}
switch pathExtension {
case "3gp", "aac", "flac", "m3u8", "m4a", "m4v", "mkv", "mov", "mp3", "mp4", "mpeg", "mpg", "mpd", "oga", "ogg", "opus", "ts", "wav", "webm":
return true
default:
return false
}
}
}
#if SKIP || os(iOS)
/// An embedded WebKit view. It is configured using a `WebEngineConfiguration`
/// and driven with a `WebViewNavigator` which can be associated
/// with user interface controls like back/forward buttons and a URL bar.
///
/// For single-page flows, a navigator is usually enough to keep one browser runtime warm.
/// For multi-tab browsers, use `persistentWebViewID` so each tab can own and later rebind
/// its own cached `WebEngine`.
public struct WebView : View {
fileprivate let config: WebEngineConfiguration
let navigator: WebViewNavigator
@Binding var state: WebViewState
var scriptCaller: WebViewScriptCaller? = nil
let htmlInState: Bool = false
let schemeHandlers: [(URLSchemeHandler, String)] = []
let onNavigationCommitted: (() -> Void)?
let onNavigationFinished: (() -> Void)?
let onNavigationFailed: (() -> Void)?
let onDownloadRequested: ((WebDownloadRequest) -> Void)?
let scrollDelegate: (any SkipWebScrollDelegate)?
let shouldOverrideUrlLoading: ((_ url: URL) -> Bool)?
let persistentWebViewID: String?
private static var engineCache: [String: WebEngine] = [:]
//let onWarm: (() async -> Void)?
//@State fileprivate var isWarm = false
/// Creates an embedded web view backed by a `WebEngine`.
///
/// Think of it as the view wrapper around one browser runtime. If you are building
/// a multi-tab browser, `persistentWebViewID` is the mechanism that lets each tab
/// keep its own live engine while the SwiftUI view mounts and unmounts around it.
///
/// Use a stable per-tab identifier, such as a tab UUID string, when each tab should
/// resume its own history and in-page state after being rebound. Omit
/// `persistentWebViewID` when the web view does not need cross-mount identity.
public init(
configuration: WebEngineConfiguration = WebEngineConfiguration(),
navigator: WebViewNavigator = WebViewNavigator(),
url initialURL: URL? = nil,
html initialHTML: String? = nil,
state: Binding<WebViewState> = .constant(WebViewState()),
scrollDelegate: (any SkipWebScrollDelegate)? = nil,
onNavigationCommitted: (() -> Void)? = nil,
onNavigationFinished: (() -> Void)? = nil,
onNavigationFailed: (() -> Void)? = nil,
onDownloadRequested: ((WebDownloadRequest) -> Void)? = nil,
shouldOverrideUrlLoading: ((_ url: URL) -> Bool)? = nil,
persistentWebViewID: String? = nil
) {
self.config = configuration
self.navigator = navigator
if let initialURL = initialURL {
navigator.initialURL = initialURL
}
if let initialHTML = initialHTML {
navigator.initialHTML = initialHTML
}
self._state = state
self.scrollDelegate = scrollDelegate
self.onNavigationCommitted = onNavigationCommitted
self.onNavigationFinished = onNavigationFinished
self.onNavigationFailed = onNavigationFailed
self.onDownloadRequested = onDownloadRequested
self.shouldOverrideUrlLoading = shouldOverrideUrlLoading
self.persistentWebViewID = persistentWebViewID
}
/// Removes one cached persistent web view so the next mount recreates its engine.
///
/// Think of it as explicitly dropping one parked browser engine from the shared cache.
/// Multi-tab hosts should call this when a tab closes or when a background tab should
/// no longer keep a live engine in memory.
@MainActor
public static func removePersistentWebView(id: String) {
guard let engine = engineCache.removeValue(forKey: id) else {
return
}
teardownPersistentWebEngine(engine)
}
/// Removes multiple cached persistent web views so the next mount recreates their engines.
///
/// Think of it as a bulk purge for parked browser engines that should no longer stay warm.
/// This is useful when a browser feature trims its warm tab pool after memory pressure
/// or session changes.
@MainActor
public static func removePersistentWebViews(ids: [String]) {
for id in ids {
removePersistentWebView(id: id)
}
}
@MainActor
static func cachedPersistentWebEngine(id: String) -> WebEngine? {
engineCache[id]
}
@MainActor
static func resolvePersistentWebEngine(
id: String?,
make: () -> WebEngine
) -> (engine: WebEngine, reused: Bool) {
if let id, let cachedEngine = engineCache[id] {
return (cachedEngine, true)
}
let engine = make()
if let id {
engineCache[id] = engine
}
return (engine, false)
}
@MainActor
private static func teardownPersistentWebEngine(_ engine: WebEngine) {
engine.stopLoading()
#if !SKIP
engine.webView.navigationDelegate = nil
engine.webView.uiDelegate = nil
engine.webView.scrollView.delegate = nil
engine.webView.removeFromSuperview()
#else
engine.webView.stopLoading()
engine.webView.loadUrl("about:blank")
engine.webView.clearHistory()
engine.webView.removeAllViews()
engine.webView.destroy()
#endif
}
}
/// The current state of a web page, including the loading status and the current URL
@available(macOS 14.0, iOS 17.0, *)
@Observable public final class WebViewState: @unchecked Sendable {
public internal(set) var isLoading: Bool = false
public internal(set) var isProvisionallyNavigating: Bool = false
/// Preferred URL accessor for parity with `WKWebView.url`.
/// Using a typed `URL` avoids string parsing at call sites.
public internal(set) var url: URL?
/// Deprecated string URL accessor kept for source compatibility.
/// Prefer `url` to mirror `WKWebView` ergonomics.
@available(*, deprecated, renamed: "url")
public internal(set) var pageURL: String? {
get {
url?.absoluteString
}
set {
if let newValue {
url = URL(string: newValue)
} else {
url = nil
}
}
}
public internal(set) var estimatedProgress: Double?
public internal(set) var pageTitle: String?
public internal(set) var pageHTML: String?
public internal(set) var error: Error?
// SKIP @nobridge
public internal(set) var themeColor: Color?
// SKIP @nobridge
public internal(set) var backgroundColor: Color?
public internal(set) var canGoBack: Bool = false
public internal(set) var canGoForward: Bool = false
public internal(set) var backList: [WebHistoryItem] = []
public internal(set) var forwardList: [WebHistoryItem] = []
public internal(set) var scrollingDown: Bool = false
public init() {
}
@MainActor func updatePageState(webView: PlatformWebView) {
self.url = webView.currentURL
self.isLoading = webView.isLoading
self.estimatedProgress = webView.estimatedProgress
self.pageTitle = webView.title
self.canGoBack = webView.canGoBack
self.canGoForward = webView.canGoForward
self.backList = webView.backList
self.forwardList = webView.forwardList
}
}
/// A controller that can drive a `WebEngine` from a user interface.
public final class WebViewNavigator: @unchecked Sendable {
/// The URL the navigator's `webEngine.didSet` will reload onto a
/// freshly-attached engine when it has no existing back/forward
/// history. Hosts that need their content to survive engine
/// recreation — for example a `TabView` with `PageTabViewStyle`
/// that dismantles off-screen `WKWebView`s and reinstantiates them
/// on return — should keep this in sync with the user's current
/// navigation, not just set it at construction time.
public var initialURL: URL?
public var initialHTML: String?
#if SKIP
@MainActor var androidScrollTracker: AndroidScrollTracker?
#endif
@MainActor public var webEngine: WebEngine? {
didSet {
logger.info("assigned webEngine: \(self.webEngine?.description ?? "NULL")")
// Allow re-use of an already-warm WebView engine (for example when
// navigating away and back to the same WebView screen).
guard oldValue !== self.webEngine else { return }
guard let webEngine = self.webEngine else { return }
let hasExistingContent = webEngine.webView.currentURL != nil
|| !webEngine.webView.backList.isEmpty
|| !webEngine.webView.forwardList.isEmpty
guard !hasExistingContent else { return }
if let initialURL = initialURL {
logger.log("loading initialURL: \(initialURL)")
load(url: initialURL)
} else if let initialHTML = initialHTML {
load(html: initialHTML)
}
}
}
public init(initialURL: URL? = nil, initialHTML: String? = nil) {
self.initialURL = initialURL
self.initialHTML = initialHTML
}
@MainActor public func load(html: String, baseURL: URL? = nil, mimeType: String = "text/html") {
// TODO: handle newTab
webEngine?.loadHTML(html, baseURL: baseURL, mimeType: mimeType)
}
@MainActor public func load(url: URL) {
Task { @MainActor in
do {
try await loadOrThrow(url: url)
} catch {
logger.error("load URL failed: \(url.absoluteString), error: \(String(describing: error))")
}
}
}
/// Loads a URL and throws any profile setup/navigation preflight errors.
@MainActor public func loadOrThrow(url: URL) async throws {
// TODO: handle newTab
let urlString = url.absoluteString
logger.info("load URL=\(urlString) webView: \(self.webEngine?.description ?? "NONE")")
guard let webEngine else { return }
try await webEngine.load(url: url)
}
@MainActor public func reload() {
logger.info("reload webView: \(self.webEngine?.description ?? "NONE")")
webEngine?.reload()
}
@MainActor public func stopLoading() {
logger.info("stopLoading webView: \(self.webEngine?.description ?? "NONE")")
webEngine?.stopLoading()
}
@MainActor public func go(_ item: WebHistoryItem) {
logger.info("go: \(item.item) webView: \(self.webEngine?.description ?? "NONE")")
webEngine?.go(to: item)
}
@MainActor public func goBack() {
logger.info("goBack webView: \(self.webEngine?.description ?? "NONE")")
webEngine?.goBack()
}
@MainActor public func goForward() {
logger.info("goForward webView: \(self.webEngine?.description ?? "NONE")")
webEngine?.goForward()
}
@MainActor public func evaluateJavaScript(_ js: String) async throws -> String? {
logger.info("evaluateJavaScript: \(js)")
return try await webEngine?.evaluate(js: js)
}
@MainActor public func takeSnapshot(configuration: SkipWebSnapshotConfiguration? = nil) async throws -> SkipWebSnapshot {
guard let webEngine else {
throw WebSnapshotError.emptySnapshot
}
return try await webEngine.takeSnapshot(configuration: configuration)
}
@MainActor public func cookies(for url: URL) async -> [WebCookie] {
guard let webEngine else {
return []
}
return await webEngine.cookies(for: url)
}
@MainActor public func cookieHeader(for url: URL) async -> String? {
guard let webEngine else {
return nil
}
return await webEngine.cookieHeader(for: url)
}
@MainActor public func setCookie(_ cookie: WebCookie, requestURL: URL? = nil) async throws {
guard let webEngine else {
return
}
try await webEngine.setCookie(cookie, requestURL: requestURL)
}
@MainActor public func applySetCookieHeaders(_ headers: [String], for responseURL: URL) async throws {
guard let webEngine else {
return
}
try await webEngine.applySetCookieHeaders(headers, for: responseURL)
}
@MainActor public func clearCookies() async {
guard let webEngine else {
return
}
await webEngine.clearCookies()
}
@MainActor public func removeData(ofTypes types: Set<WebSiteDataType>, modifiedSince: Date) async throws {
guard let webEngine else {
return
}
try await webEngine.removeData(ofTypes: types, modifiedSince: modifiedSince)
}
}
// MARK: SkipUI interop with legacy UIKit/AndroidView system
#if SKIP
protocol ViewRepresentable {
}
#elseif canImport(UIKit)
typealias ViewRepresentable = UIViewRepresentable
#elseif canImport(AppKit)
typealias ViewRepresentable = NSViewRepresentable
#else
#error("Unsupported platform")
#endif
#if SKIP
public struct MessageHandlerRouter {
let webEngine: WebEngine
// SKIP INSERT: @android.webkit.JavascriptInterface
public func postMessage(_ name: String, bodyJSON: String, sourceURL: String, isMainFrame: Bool) {
guard webEngine.configuration.allRegisteredMessageHandlerNames.contains(name) else {
logger.error("no scriptMessageHandler for \(name)")
return
}
let message = WebViewScriptMessage(
name: name,
bodyJSON: bodyJSON,
sourceURL: sourceURL.isEmpty ? nil : sourceURL,
isMainFrame: isMainFrame
)
Task { @MainActor [webEngine, message] in
webEngine.configuration.scriptMessageDelegate?.webEngine(webEngine, didReceiveScriptMessage: message)
}
if let messageHandler = webEngine.configuration.legacyMessageHandlers[name] {
let frameURL = URL(string: sourceURL.isEmpty ? "about:blank" : sourceURL) ?? URL(string: "about:blank")!
let frameInfo = FrameInfo(isMainFrame: isMainFrame, request: URLRequest(url: frameURL), securityOrigin: SecurityOrigin(), webView: webEngine.webView)
let body = try JSONSerialization.jsonObject(with: bodyJSON.data(using: .utf8)!, options: [])
let legacyMessage = WebViewMessage(frameInfo: frameInfo, uuid: UUID(), name: name, body: body)
Task {
await messageHandler(legacyMessage)
}
}
}
}
struct WebViewClient : android.webkit.WebViewClient {
let state: WebViewState
let onNavigationCommitted: (() -> Void)?
let onNavigationFinished: (() -> Void)?
let onNavigationFailed: (() -> Void)?
let shouldOverrideUrlLoadingHandler: ((_ url: URL) -> Bool)?
override func onPageFinished(view: PlatformWebView, url: String) {
state.updatePageState(webView: view)
if let onNavigationFinished {
onNavigationFinished()
}
}
override func onPageStarted(view: PlatformWebView, url: String, favicon: android.graphics.Bitmap?) {
state.updatePageState(webView: view)
if let onNavigationCommitted {
onNavigationCommitted()
}
}
override func onReceivedError(view: PlatformWebView, request: android.webkit.WebResourceRequest, error: android.webkit.WebResourceError) {
state.updatePageState(webView: view)
if let onNavigationFailed {
onNavigationFailed()
}
}
override func shouldOverrideUrlLoading(view: PlatformWebView, request: android.webkit.WebResourceRequest) -> Bool {
guard let url = URL(string: request.url.toString()) else {
return false
}
let result = shouldOverrideUrlLoadingHandler?(url) ?? false
if result {
logger.log("Override URL loading for \(url)")
}
return result
}
}
struct WebViewDownloadListener : android.webkit.DownloadListener {
let state: WebViewState
let onDownloadRequested: ((WebDownloadRequest) -> Void)?
static func suggestedFilename(url: String, contentDisposition: String, mimeType: String) -> String? {
let filename = android.webkit.URLUtil.guessFileName(url, contentDisposition, mimeType)
if filename.isEmpty {
return nil
}
return filename
}
override func onDownloadStart(
url: String,
userAgent: String,
contentDisposition: String,
mimetype: String,
contentLength: Int64
) {
state.isLoading = false
state.isProvisionallyNavigating = false
state.estimatedProgress = 0
state.error = nil
onDownloadRequested?(
WebDownloadRequest(
url: URL(string: url),
suggestedFilename: Self.suggestedFilename(
url: url,
contentDisposition: contentDisposition,
mimeType: mimetype
),
mimeType: mimetype.isEmpty ? nil : mimetype,
contentDisposition: contentDisposition.isEmpty ? nil : contentDisposition,
contentLength: contentLength
)
)
}
}
final class SkipWebChromeClient : android.webkit.WebChromeClient {
let webView: WebView
let webEngine: WebEngine
private var childEnginesByWebViewHash: [Int32: WebEngine] = [:]
init(webView: WebView, webEngine: WebEngine) {
self.webView = webView
self.webEngine = webEngine
}
private func inheritParentConfiguration(for childEngine: WebEngine) -> Bool {
let parentConfig = webEngine.configuration
if let profileError = childEngine.inheritAndroidProfile(from: parentConfig) {
logger.error("onCreateWindow: failed to inherit parent WebProfile \(String(describing: parentConfig.profile)): \(String(describing: profileError))")
return false
}
let settings = childEngine.webView.settings
settings.setJavaScriptEnabled(parentConfig.javaScriptEnabled)
settings.setJavaScriptCanOpenWindowsAutomatically(parentConfig.javaScriptCanOpenWindowsAutomatically)
settings.setSupportMultipleWindows(parentConfig.uiDelegate != nil)
settings.setSafeBrowsingEnabled(false)
settings.setAllowContentAccess(true)
settings.setAllowFileAccess(true)
settings.setDomStorageEnabled(true)
if parentConfig.customUserAgent != nil {
settings.setUserAgentString(parentConfig.customUserAgent)
}
childEngine.webView.setBackgroundColor(0x000000)
childEngine.webView.addJavascriptInterface(MessageHandlerRouter(webEngine: childEngine), "skipWebAndroidMessageHandler")
childEngine.installAndroidScriptMessageFacadeIfNeeded()
childEngine.installAndroidDocumentStartUserScriptsIfNeeded()
childEngine.webView.setDownloadListener(WebViewDownloadListener(
state: self.webView.state,
onDownloadRequested: self.webView.onDownloadRequested
))
childEngine.setAndroidEmbeddedNavigationClient(WebViewClient(
state: self.webView.state,
onNavigationCommitted: self.webView.onNavigationCommitted,
onNavigationFinished: self.webView.onNavigationFinished,
onNavigationFailed: self.webView.onNavigationFailed,
shouldOverrideUrlLoadingHandler: self.webView.shouldOverrideUrlLoading
))
childEngine.webView.webChromeClient = self
return true
}
override func onCreateWindow(view: PlatformWebView, isDialog: Bool, isUserGesture: Bool, resultMsg: android.os.Message) -> Bool {
let createWindowHandler = webEngine.configuration.androidCreateWindowHandler
let uiDelegate = webEngine.configuration.uiDelegate
guard createWindowHandler != nil || uiDelegate != nil else {
return false
}
let sourceURL = URL(string: view.getUrl() ?? "")
let request = WebWindowRequest(
sourceURL: sourceURL,
targetURL: nil,
isUserGesture: isUserGesture,
isDialog: isDialog,
isMainFrame: nil
)
let params = AndroidCreateWindowParams(
isDialog: isDialog,
isUserGesture: isUserGesture,
resultMessage: resultMsg
)
let childEngine: WebEngine?
if let createWindowHandler {
childEngine = createWindowHandler(webView, request, params)
} else {
childEngine = uiDelegate?.webView(
webView,
createWebViewWith: request,
platformContext: params
)
}
guard let childEngine else {
return false
}
guard inheritParentConfiguration(for: childEngine) else {
return false
}
guard let transport = resultMsg.obj as? android.webkit.WebView.WebViewTransport else {
logger.error("onCreateWindow: invalid WebViewTransport message payload")
return false
}
transport.setWebView(childEngine.webView)
resultMsg.sendToTarget()
childEnginesByWebViewHash[childEngine.webView.hashCode()] = childEngine
return true
}
override func onCloseWindow(window: PlatformWebView) {
defer {
super.onCloseWindow(window)
}
guard let childEngine = childEnginesByWebViewHash.removeValue(forKey: window.hashCode()) else {
return
}
if let closeWindowHandler = webEngine.configuration.androidCloseWindowHandler {
closeWindowHandler(self.webView, childEngine)
} else {
webEngine.configuration.uiDelegate?.webViewDidClose(self.webView, child: childEngine)
}
}
}
#endif
@available(macOS 14.0, iOS 17.0, *)
extension WebView : ViewRepresentable {
public typealias Coordinator = WebViewCoordinator
public func makeCoordinator() -> Coordinator {
WebViewCoordinator(webView: self, navigator: navigator, scriptCaller: scriptCaller, config: config)
}
@MainActor private func setupWebView(_ webEngine: WebEngine, coordinator: WebViewCoordinator? = nil) -> WebEngine {
// configure JavaScript
#if SKIP
let settings = webEngine.webView.settings
settings.setJavaScriptEnabled(config.javaScriptEnabled)
settings.setJavaScriptCanOpenWindowsAutomatically(config.javaScriptCanOpenWindowsAutomatically)
settings.setSupportMultipleWindows(
config.uiDelegate != nil || config.androidCreateWindowHandler != nil
)
settings.setSafeBrowsingEnabled(false)
settings.setAllowContentAccess(true)
settings.setAllowFileAccess(true)
settings.setDomStorageEnabled(true)
if (config.customUserAgent != nil ) {
settings.setUserAgentString(config.customUserAgent)
}
webEngine.webView.setBackgroundColor(0x000000) // prevents screen flashing: https://issuetracker.google.com/issues/314821744
webEngine.webView.addJavascriptInterface(MessageHandlerRouter(webEngine: webEngine), "skipWebAndroidMessageHandler")
webEngine.installAndroidScriptMessageFacadeIfNeeded()
webEngine.installAndroidDocumentStartUserScriptsIfNeeded()
webEngine.webView.setDownloadListener(WebViewDownloadListener(
state: state,
onDownloadRequested: onDownloadRequested
))
webEngine.setAndroidEmbeddedNavigationClient(WebViewClient(
state: state,
onNavigationCommitted: onNavigationCommitted,
onNavigationFinished: onNavigationFinished,
onNavigationFailed: onNavigationFailed,
shouldOverrideUrlLoadingHandler: shouldOverrideUrlLoading
))
if config.uiDelegate != nil || config.androidCreateWindowHandler != nil {
webEngine.webView.webChromeClient = SkipWebChromeClient(webView: self, webEngine: webEngine)
} else {
webEngine.webView.webChromeClient = android.webkit.WebChromeClient()
}
coordinator?.configureAndroidScrollTracking(webView: webEngine.webView)
// Cross-platform link context menu on Android: when the
// user long-presses a link or image-link, build the same
// `WebContextMenuAction` list the iOS WKUIDelegate uses and
// render it as a centered `AlertDialog`. Without
// `linkContextMenuActions` configured, fall through to
// Android's default text-selection action mode.
//
// `PopupMenu` was rejected here: it anchors to the WebView
// and bottom-lefts itself in the viewport, which feels
// disconnected from the link the user pressed. `AlertDialog`
// centers on screen and shows the URL as the dialog title so
// the user can confirm what they're acting on.
let configRef = self.config
webEngine.webView.setOnLongClickListener { view in
let nativeWebView = view as android.webkit.WebView
let hitTest = nativeWebView.hitTestResult
let type = hitTest.type
if type == android.webkit.WebView.HitTestResult.SRC_ANCHOR_TYPE
|| type == android.webkit.WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE {
if let urlString = hitTest.extra, let url = URL(string: urlString),
let actionsProvider = configRef.linkContextMenuActions {
let actions = actionsProvider(url)
if !actions.isEmpty {
let titles: kotlin.Array<CharSequence> = kotlin.Array(actions.count) { i in
actions[i].title as CharSequence
}
let builder = android.app.AlertDialog.Builder(view.context)
builder.setTitle(url.absoluteString)
builder.setItems(titles) { _, which in
if which >= 0 && which < actions.count {
actions[which].handler(url)
}
}
builder.create().show()
return true
}
}
}
return false
}
//settings.setAlgorithmicDarkeningAllowed(boolean allow)
//settings.setAllowContentAccess(boolean allow)
//settings.setAllowFileAccess(boolean allow)
//settings.setAllowFileAccessFromFileURLs(boolean flag) // deprecated
//settings.setAllowUniversalAccessFromFileURLs(boolean flag) // deprecated
//settings.setBlockNetworkImage(boolean flag)
//settings.setBlockNetworkLoads(boolean flag)
//settings.setBuiltInZoomControls(boolean enabled)
//settings.setCacheMode(int mode)
//settings.setCursiveFontFamily(String font)
//settings.setDatabaseEnabled(boolean flag)
//settings.setDatabasePath(String databasePath) // deprecated
//settings.setDefaultFixedFontSize(int size)
//settings.setDefaultFontSize(int size)
//settings.setDefaultTextEncodingName(String encoding)
//settings.setDefaultZoom(WebSettings.ZoomDensity zoom) // deprecated
//settings.setDisabledActionModeMenuItems(int menuItems)
//settings.setDisplayZoomControls(boolean enabled)
//settings.setEnableSmoothTransition(boolean enable) // deprecated
//settings.setFantasyFontFamily(String font)
//settings.setFixedFontFamily(String font)
//settings.setForceDark(int forceDark) // deprecated
//settings.setGeolocationDatabasePath(String databasePath) // deprecated
//settings.setGeolocationEnabled(boolean flag)
//settings.setJavaScriptCanOpenWindowsAutomatically(boolean flag)
//settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm l)
//settings.setLightTouchEnabled(boolean enabled) // deprecated
//settings.setLoadWithOverviewMode(boolean overview)
//settings.setLoadsImagesAutomatically(boolean flag)
//settings.setMediaPlaybackRequiresUserGesture(boolean require)
//settings.setMinimumFontSize(int size)
//settings.setMinimumLogicalFontSize(int size)
//settings.setMixedContentMode(int mode)
//settings.setNeedInitialFocus(boolean flag)
//settings.setOffscreenPreRaster(boolean enabled)
//settings.setPluginState(WebSettings.PluginState state) // deprecated
//settings.setRenderPriority(WebSettings.RenderPriority priority) // deprecated
//settings.setSansSerifFontFamily(String font)
//settings.setSaveFormData(boolean save) // deprecated
//settings.setSavePassword(boolean save) // deprecated
//settings.setSerifFontFamily(String font)
//settings.setStandardFontFamily(String font)
//settings.setSupportMultipleWindows(boolean support)
//settings.setSupportZoom(boolean support)
//settings.setTextSize(WebSettings.TextSize t)
//settings.setTextZoom(int textZoom)
//settings.setUseWideViewPort(boolean use)
//settings.setUserAgentString(String ua)
#else
let configuration = webEngine.webView.configuration
configuration.allowsAirPlayForMediaPlayback = true
configuration.suppressesIncrementalRendering = false
//configuration.mediaTypesRequiringUserActionForPlayback =
//configuration.userContentController =
//configuration.allowsInlinePredictions =
//configuration.applicationNameForUserAgent =
//configuration.limitsNavigationsToAppBoundDomains =
//configuration.upgradeKnownHostsToHTTPS =
let preferences = configuration.defaultWebpagePreferences!
preferences.allowsContentJavaScript = config.javaScriptEnabled
configuration.preferences.javaScriptCanOpenWindowsAutomatically = config.javaScriptCanOpenWindowsAutomatically
preferences.preferredContentMode = .recommended
// preferences.isLockdownModeEnabled = false // The 'com.apple.developer.web-browser' restricted entitlement is required to disable lockdown mode
webEngine.refreshMessageHandlers()
webEngine.updateUserScripts()
if (config.customUserAgent != "" ) {
webEngine.webView.customUserAgent = config.customUserAgent
}
#endif
if navigator.webEngine !== webEngine {
// Rebind only when needed so we do not re-trigger initial content loading.
navigator.webEngine = webEngine
}
return webEngine
}
public func update(webView: PlatformWebView, coordinator: WebViewCoordinator? = nil) {
coordinator?.update(from: self)
#if !SKIP
if let coordinator, webView.navigationDelegate == nil {
webView.navigationDelegate = coordinator
}
webView.uiDelegate = coordinator
webView.scrollView.delegate = coordinator
webView.scrollView.isScrollEnabled = config.isScrollEnabled
#endif
//logger.info("WebView.update: \(webView)")
}
#if SKIP
// Without `remember` recompositions recreate WebViewCoordinator, which resets scroll-tracking state and can swap scrollViewProxy identity mid-session
@Composable
private func rememberedCoordinator() -> WebViewCoordinator {
// SKIP INSERT: return androidx.compose.runtime.remember { makeCoordinator() }
return makeCoordinator()
}
public var body: some View {
ComposeView { ctx in
let coordinator = rememberedCoordinator()
AndroidView(factory: { ctx in
config.context = ctx
let resolvedWebEngine: WebEngine
if let persistentWebViewID {
resolvedWebEngine = Self.resolvePersistentWebEngine(id: persistentWebViewID) {
WebEngine(configuration: config)
}.engine
} else {
// Preserve navigator-owned reuse for single WebViews without a tab cache ID.
resolvedWebEngine = navigator.webEngine ?? WebEngine(configuration: config)
}
let webEngine = setupWebView(resolvedWebEngine, coordinator: coordinator)
navigator.webEngine = webEngine
let view = webEngine.webView
if let parent = view.parent as? ViewGroup {
parent.removeView(view)
}
// AndroidView does not reliably push the parent's fill constraints into the
// embedded WebView on the first layout pass, so we request fill sizing from both
// Compose and the native view to avoid a zero-height viewport.
view.layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
view.minimumHeight = 1
return view
}, modifier: ctx.modifier.fillMaxSize(), update: { webView in
webView.layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
coordinator.update(from: self)
coordinator.configureAndroidScrollTracking(webView: webView)
self.update(webView: webView, coordinator: coordinator)
})
}
}
#else
@MainActor private func makeWebEngine(id: String?, config: WebEngineConfiguration, coordinator: WebViewCoordinator) -> WebEngine {
let resolvedEngine = Self.resolvePersistentWebEngine(id: id) {
let engine = WebEngine(configuration: config)
logger.info("created WebEngine \(id ?? "noid"): \(engine)")
return engine
}
let web = resolvedEngine.engine
if resolvedEngine.reused {
for messageHandlerName in coordinator.messageHandlerNames {
web.webView.configuration.userContentController.removeScriptMessageHandler(forName: messageHandlerName)
}
}
_ = setupWebView(web, coordinator: coordinator)
#if !os(macOS) // API unavailable on macOS
web.webView.isOpaque = false
web.webView.backgroundColor = .clear
//web?.backgroundColor = .white
#endif
return web
}
@MainActor private func create(from context: Context) -> WebEngine {
let webEngine = makeWebEngine(id: persistentWebViewID, config: config, coordinator: context.coordinator)
context.coordinator.navigator.webEngine = webEngine
let webView = webEngine.webView
Task { @MainActor in
if let error = await webEngine.awaitContentBlockerSetup().first {
context.coordinator.state.error = error
}
}
webView.allowsLinkPreview = true
webView.navigationDelegate = context.coordinator
webView.scrollView.delegate = context.coordinator
webView.uiDelegate = context.coordinator
webView.allowsBackForwardNavigationGestures = config.allowsBackForwardNavigationGestures
#if os(iOS)
webView.scrollView.contentInsetAdjustmentBehavior = .always
//webView.scrollView.contentInsetAdjustmentBehavior = .scrollableAxes
webView.scrollView.isScrollEnabled = config.isScrollEnabled
webView.pageZoom = config.pageZoom
webView.isOpaque = config.isOpaque
webView.isInspectable = true
webView.isFindInteractionEnabled = true
webView.allowsBackForwardNavigationGestures = true
webView.allowsLinkPreview = true
if config.allowsPullToRefresh == true {
// add a pull-to-refresh control to the page
webView.scrollView.refreshControl = UIRefreshControl()
webView.scrollView.refreshControl?.addTarget(context.coordinator, action: #selector(Coordinator.handleRefreshControl), for: .valueChanged)
}
webView.publisher(for: \.title)
.receive(on: DispatchQueue.main)
.sink { title in
if let title = title, !title.isEmpty {
context.coordinator.state.pageTitle = title
}
}
.store(in: &context.coordinator.subscriptions)