Skip to content
This repository was archived by the owner on Feb 24, 2025. It is now read-only.

Commit 9d078c6

Browse files
authored
move async WKWebView.evaluateJavaScript to BSK (#2902)
Task/Issue URL: https://app.asana.com/0/1201037661562251/1207644259876245/f BSK PR: duckduckgo/BrowserServicesKit#861
1 parent f7057ac commit 9d078c6

File tree

12 files changed

+42
-61
lines changed

12 files changed

+42
-61
lines changed

DuckDuckGo.xcodeproj/project.pbxproj

+1-1
Original file line numberDiff line numberDiff line change
@@ -13042,7 +13042,7 @@
1304213042
repositoryURL = "https://github.com/duckduckgo/BrowserServicesKit";
1304313043
requirement = {
1304413044
kind = exactVersion;
13045-
version = 160.0.0;
13045+
version = 160.1.0;
1304613046
};
1304713047
};
1304813048
9FF521422BAA8FF300B9819B /* XCRemoteSwiftPackageReference "lottie-spm" */ = {

DuckDuckGo.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved

+2-2
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,8 @@
3232
"kind" : "remoteSourceControl",
3333
"location" : "https://github.com/duckduckgo/BrowserServicesKit",
3434
"state" : {
35-
"revision" : "70ea98c091350a5dde9d6e5d6b05f064e5a36ec0",
36-
"version" : "160.0.0"
35+
"revision" : "a9c9b63020ca36848193205be2d1f91fba412b5a",
36+
"version" : "160.1.0"
3737
}
3838
},
3939
{

DuckDuckGo/Common/Extensions/WKWebViewExtension.swift

-13
Original file line numberDiff line numberDiff line change
@@ -262,19 +262,6 @@ extension WKWebView {
262262
}
263263
}
264264

265-
@MainActor
266-
func evaluateJavaScript<T>(_ script: String) async throws -> T? {
267-
try await withUnsafeThrowingContinuation { c in
268-
evaluateJavaScript(script) { result, error in
269-
if let error {
270-
c.resume(with: .failure(error))
271-
} else {
272-
c.resume(with: .success(result as? T))
273-
}
274-
}
275-
}
276-
}
277-
278265
func close() {
279266
self.evaluateJavaScript("window.close()")
280267
}

IntegrationTests/AutoconsentIntegrationTests.swift

+3-3
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,7 @@ class AutoconsentIntegrationTests: XCTestCase {
117117
errorDescription!
118118
}
119119
}
120-
let html = try await tab.webView.evaluateJavaScript("document.documentElement.outerHTML") as? String
120+
let html = try await tab.webView.evaluateJavaScript("document.documentElement.outerHTML") as String?
121121

122122
if let html {
123123
throw ErrorWithHTML(originalError: error, html: html)
@@ -126,7 +126,7 @@ class AutoconsentIntegrationTests: XCTestCase {
126126
}
127127
}
128128

129-
let isBannerHidden = try await tab.webView.evaluateJavaScript("window.getComputedStyle(banner).display === 'none'") as? Bool
129+
let isBannerHidden = try await tab.webView.evaluateJavaScript("window.getComputedStyle(banner).display === 'none'") as Bool?
130130
XCTAssertTrue(isBannerHidden == true)
131131
}
132132

@@ -168,7 +168,7 @@ class AutoconsentIntegrationTests: XCTestCase {
168168
let cookieConsentManaged = try await cookieConsentManagedPromise.value
169169
XCTAssertTrue(cookieConsentManaged == true)
170170

171-
let isBannerHidden = try await tab.webView.evaluateJavaScript("window.getComputedStyle(banner).display === 'none'") as? Bool
171+
let isBannerHidden = try await tab.webView.evaluateJavaScript("window.getComputedStyle(banner).display === 'none'") as Bool?
172172
XCTAssertTrue(isBannerHidden == true)
173173
}
174174

IntegrationTests/Downloads/DownloadsIntegrationTests.swift

+2-2
Original file line numberDiff line numberDiff line change
@@ -478,7 +478,7 @@ class DownloadsIntegrationTests: XCTestCase {
478478
return true;
479479
})();
480480
"""
481-
try! await tab.webView.evaluateJavaScript(js)
481+
try! await tab.webView.evaluateJavaScript(js) as Void?
482482

483483
let fileUrl = try await downloadTaskFuture.get().output
484484
.timeout(5, scheduler: DispatchQueue.main) { .init(TimeoutError() as NSError) }.first().promise().get()
@@ -512,7 +512,7 @@ class DownloadsIntegrationTests: XCTestCase {
512512
return true;
513513
})();
514514
"""
515-
try! await tab.webView.evaluateJavaScript(js)
515+
try! await tab.webView.evaluateJavaScript(js) as Void?
516516

517517
let fileUrl = try await downloadTaskFuture.get().output
518518
.timeout(1, scheduler: DispatchQueue.main) { .init(TimeoutError() as NSError) }.first().promise().get()

IntegrationTests/HTTPSUpgrade/HTTPSUpgradeIntegrationTests.swift

+4-4
Original file line numberDiff line numberDiff line change
@@ -89,15 +89,15 @@ class HTTPSUpgradeIntegrationTests: XCTestCase {
8989
.promise()
9090

9191
// run test
92-
_=try await tab.webView.evaluateJavaScript("(function() { document.getElementById('start').click(); return true })()")
92+
try await tab.webView.evaluateJavaScript("(function() { document.getElementById('start').click(); })()") as Void?
9393

9494
// await for popup to open and close
9595
_=try await comingBackToFirstTabPromise.value
9696

9797
let downloadTaskFuture = FileDownloadManager.shared.downloadsPublisher.timeout(5).first().promise()
9898

9999
// download results
100-
_=try await tab.webView.evaluateJavaScript("(function() { document.getElementById('download').click(); return true })()")
100+
try await tab.webView.evaluateJavaScript("(function() { document.getElementById('download').click(); })()") as Void?
101101

102102
let fileUrl = try await downloadTaskFuture.value.output
103103
.timeout(1, scheduler: DispatchQueue.main) { .init(TimeoutError() as NSError) }.first().promise().get()
@@ -167,15 +167,15 @@ class HTTPSUpgradeIntegrationTests: XCTestCase {
167167
.promise()
168168

169169
// run test
170-
_=try await tab.webView.evaluateJavaScript("(function() { document.getElementById('start').click(); return true })()")
170+
try await tab.webView.evaluateJavaScript("(function() { document.getElementById('start').click(); })()") as Void?
171171

172172
// await for popup to open and close
173173
_=try await comingBackToFirstTabPromise.value
174174

175175
let downloadTaskFuture = FileDownloadManager.shared.downloadsPublisher.timeout(5).first().promise()
176176

177177
// download results
178-
_=try await tab.webView.evaluateJavaScript("(function() { document.getElementById('download').click(); return true })()")
178+
try await tab.webView.evaluateJavaScript("(function() { document.getElementById('download').click(); })()") as Void?
179179

180180
let fileUrl = try await downloadTaskFuture.value.output
181181
.timeout(1, scheduler: DispatchQueue.main) { .init(TimeoutError() as NSError) }.first().promise().get()

IntegrationTests/History/HistoryIntegrationTests.swift

+2-2
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,7 @@ class HistoryIntegrationTests: XCTestCase {
103103
.first()
104104
.promise()
105105

106-
_=try await tab.webView.evaluateJavaScript("(function() { document.title = 'Title 2'; return true })()")
106+
try await tab.webView.evaluateJavaScript("(function() { document.title = 'Title 2'; })()") as Void?
107107
_=try await titleChangedPromise2.value
108108

109109
XCTAssertEqual(HistoryCoordinator.shared.history?.count, 1)
@@ -143,7 +143,7 @@ class HistoryIntegrationTests: XCTestCase {
143143
.first()
144144
.promise()
145145

146-
_=try await tab.webView.evaluateJavaScript("(function() { document.getElementById('link').click(); return true })()")
146+
try await tab.webView.evaluateJavaScript("(function() { document.getElementById('link').click(); })()") as Void?
147147
_=try await titleChangedPromise.value
148148

149149
XCTAssertEqual(HistoryCoordinator.shared.history?.count, 2)

IntegrationTests/NavigationProtection/NavigationProtectionIntegrationTests.swift

+8-8
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ class NavigationProtectionIntegrationTests: XCTestCase {
7070
let url = URL(string: "https://privacy-test-pages.site/privacy-protections/amp/")!
7171
_=try await tab.setUrl(url, source: .link)?.result.get()
7272

73-
let itemsCount = try await tab.webView.evaluateJavaScript("document.getElementsByTagName('li').length") as? Int ?? 0
73+
let itemsCount = try await tab.webView.evaluateJavaScript("document.getElementsByTagName('li').length") as Int? ?? 0
7474
XCTAssertTrue(itemsCount > 0, "no items")
7575

7676
// go through links on the page
@@ -82,8 +82,8 @@ class NavigationProtectionIntegrationTests: XCTestCase {
8282
}
8383

8484
// extract "Expected" URL
85-
guard let name = try await tab.webView.evaluateJavaScript("document.getElementsByTagName('li')[\(i)].getElementsByTagName('a')[0].innerText") as? String,
86-
let expected = try await tab.webView.evaluateJavaScript("document.getElementsByTagName('li')[\(i)].getElementsByClassName('expected')[0].innerText") as? String,
85+
guard let name: String = try await tab.webView.evaluateJavaScript("document.getElementsByTagName('li')[\(i)].getElementsByTagName('a')[0].innerText"),
86+
let expected: String = try await tab.webView.evaluateJavaScript("document.getElementsByTagName('li')[\(i)].getElementsByClassName('expected')[0].innerText"),
8787
let expectedUrl = URL(string: expected.lowercased().dropping(prefix: "expected: "))
8888
else {
8989
XCTFail("Could not parse element at \(i)")
@@ -121,7 +121,7 @@ class NavigationProtectionIntegrationTests: XCTestCase {
121121
}.timeout(10, "#\(i + 1) \(name)").first().promise()
122122

123123
// click
124-
_=try await tab.webView.evaluateJavaScript("(function() { document.getElementsByTagName('li')[\(i)].getElementsByTagName('a')[0].click(); return true })()")
124+
try await tab.webView.evaluateJavaScript("(function() { document.getElementsByTagName('li')[\(i)].getElementsByTagName('a')[0].click(); })()") as Void?
125125
// get the NavigationAction url
126126
let resultUrl = try await navigationWillStartPromise.value
127127

@@ -154,7 +154,7 @@ class NavigationProtectionIntegrationTests: XCTestCase {
154154
_=try await tab.setUrl(url, source: .link)?.result.get()
155155

156156
// run test
157-
_=try await tab.webView.evaluateJavaScript("(function() { document.getElementById('start').click(); return true })()")
157+
try await tab.webView.evaluateJavaScript("(function() { document.getElementById('start').click(); })()") as Void?
158158

159159
_=try await Future<Void, Never> { promise in
160160
onDidFinish = { _ in
@@ -171,7 +171,7 @@ class NavigationProtectionIntegrationTests: XCTestCase {
171171
let downloadTaskPromise = FileDownloadManager.shared.downloadsPublisher.timeout(5).first().promise()
172172
for i in 0...4 {
173173
do {
174-
_=try await tab.webView.evaluateJavaScript("(function() { document.getElementById('download').click(); return true })()")
174+
try await tab.webView.evaluateJavaScript("(function() { document.getElementById('download').click(); })()") as Void?
175175
try await Task.sleep(nanoseconds: 300.asNanos)
176176
break
177177
} catch {
@@ -229,7 +229,7 @@ class NavigationProtectionIntegrationTests: XCTestCase {
229229
.promise()
230230

231231
// run test
232-
_=try await tab.webView.evaluateJavaScript("(function() { document.getElementById('start').click(); return true })()")
232+
try await tab.webView.evaluateJavaScript("(function() { document.getElementById('start').click(); })()") as Void?
233233

234234
// await for popup to open and close
235235
_=try await comingBackToFirstTabPromise.value
@@ -256,7 +256,7 @@ class NavigationProtectionIntegrationTests: XCTestCase {
256256
let persistor = DownloadsPreferencesUserDefaultsPersistor()
257257
persistor.selectedDownloadLocation = FileManager.default.temporaryDirectory.absoluteString
258258
let downloadTaskFuture = FileDownloadManager.shared.downloadsPublisher.timeout(5).first().promise()
259-
_=try await tab.webView.evaluateJavaScript("(function() { document.getElementById('download').click(); return true })()")
259+
try await tab.webView.evaluateJavaScript("(function() { document.getElementById('download').click(); })()") as Void?
260260

261261
let fileUrl = try await downloadTaskFuture.value.output
262262
.timeout(1, scheduler: DispatchQueue.main) { .init(TimeoutError() as NSError) }.first().promise().get()

LocalPackages/DataBrokerProtection/Package.swift

+1-1
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ let package = Package(
2929
targets: ["DataBrokerProtection"])
3030
],
3131
dependencies: [
32-
.package(url: "https://github.com/duckduckgo/BrowserServicesKit", exact: "160.0.0"),
32+
.package(url: "https://github.com/duckduckgo/BrowserServicesKit", exact: "160.1.0"),
3333
.package(path: "../SwiftUIExtensions"),
3434
.package(path: "../XPCHelper"),
3535
],

LocalPackages/DataBrokerProtection/Sources/DataBrokerProtection/CCF/WebViewHandler.swift

+17-23
Original file line numberDiff line numberDiff line change
@@ -127,40 +127,34 @@ final class DataBrokerProtectionWebViewHandler: NSObject, WebViewHandler {
127127
}
128128

129129
func evaluateJavaScript(_ javaScript: String) async throws {
130-
_ = webView?.evaluateJavaScript(javaScript, in: nil, in: WKContentWorld.page)
130+
try await webView?.evaluateJavaScript(javaScript) as Void?
131131
}
132132

133133
func takeSnaphost(path: String, fileName: String) async throws {
134-
let script = "document.body.scrollHeight"
134+
guard let height: CGFloat = try await webView?.evaluateJavaScript("document.body.scrollHeight") else { return }
135135

136-
let result = try await webView?.evaluateJavaScript(script)
137-
138-
if let height = result as? CGFloat {
139-
webView?.frame = CGRect(origin: .zero, size: CGSize(width: 1024, height: height))
140-
let configuration = WKSnapshotConfiguration()
141-
configuration.rect = CGRect(x: 0, y: 0, width: webView?.frame.size.width ?? 0.0, height: height)
142-
if let image = try await webView?.takeSnapshot(configuration: configuration) {
143-
saveToDisk(image: image, path: path, fileName: fileName)
144-
}
136+
webView?.frame = CGRect(origin: .zero, size: CGSize(width: 1024, height: height))
137+
let configuration = WKSnapshotConfiguration()
138+
configuration.rect = CGRect(x: 0, y: 0, width: webView?.frame.size.width ?? 0.0, height: height)
139+
if let image = try await webView?.takeSnapshot(configuration: configuration) {
140+
saveToDisk(image: image, path: path, fileName: fileName)
145141
}
146142
}
147143

148144
func saveHTML(path: String, fileName: String) async throws {
149-
let result = try await webView?.evaluateJavaScript("document.documentElement.outerHTML")
145+
guard let htmlString: String = try await webView?.evaluateJavaScript("document.documentElement.outerHTML") else { return }
150146
let fileManager = FileManager.default
151147

152-
if let htmlString = result as? String {
153-
do {
154-
if !fileManager.fileExists(atPath: path) {
155-
try fileManager.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil)
156-
}
157-
158-
let fileURL = URL(fileURLWithPath: "\(path)/\(fileName)")
159-
try htmlString.write(to: fileURL, atomically: true, encoding: .utf8)
160-
print("HTML content saved to file: \(fileURL)")
161-
} catch {
162-
print("Error writing HTML content to file: \(error)")
148+
do {
149+
if !fileManager.fileExists(atPath: path) {
150+
try fileManager.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil)
163151
}
152+
153+
let fileURL = URL(fileURLWithPath: "\(path)/\(fileName)")
154+
try htmlString.write(to: fileURL, atomically: true, encoding: .utf8)
155+
print("HTML content saved to file: \(fileURL)")
156+
} catch {
157+
os_log(.error, "Error writing HTML content to file: \(error)")
164158
}
165159
}
166160

LocalPackages/NetworkProtectionMac/Package.swift

+1-1
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ let package = Package(
3232
.library(name: "VPNAppLauncher", targets: ["VPNAppLauncher"]),
3333
],
3434
dependencies: [
35-
.package(url: "https://github.com/duckduckgo/BrowserServicesKit", exact: "160.0.0"),
35+
.package(url: "https://github.com/duckduckgo/BrowserServicesKit", exact: "160.1.0"),
3636
.package(url: "https://github.com/airbnb/lottie-spm", exact: "4.4.1"),
3737
.package(path: "../AppLauncher"),
3838
.package(path: "../UDSHelper"),

LocalPackages/SubscriptionUI/Package.swift

+1-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ let package = Package(
1212
targets: ["SubscriptionUI"]),
1313
],
1414
dependencies: [
15-
.package(url: "https://github.com/duckduckgo/BrowserServicesKit", exact: "160.0.0"),
15+
.package(url: "https://github.com/duckduckgo/BrowserServicesKit", exact: "160.1.0"),
1616
.package(path: "../SwiftUIExtensions")
1717
],
1818
targets: [

0 commit comments

Comments
 (0)