Repository Public License
1import Foundation2import NavigatorCore3import WebKit45extension WebEngine {6 // MARK: Script evaluation78 /// Runs `functionBody` as the body of an async JavaScript function in one of the browser's isolated worlds9 /// and returns its result. `arguments` become local variables. The page's own JavaScript world is not10 /// reachable through this API: the script sees the DOM, never the page's objects, and the page never sees11 /// the script's.12 @discardableResult13 public func evaluate(_ functionBody: String, arguments: [String: ScriptValue] = [:],14 in world: ScriptWorld = .agent) async throws(WebEngineError) -> ScriptValue {15 guard let view = webView else { throw .noWebView }16 do {17 let result = try await view.callAsyncJavaScript(functionBody, arguments: arguments.mapValues(\.foundationValue),18 in: nil, contentWorld: world.contentWorld)19 return ScriptValue(any: result)20 } catch {21 let nsError = error as NSError22 let detail = (nsError.userInfo["WKJavaScriptExceptionMessage"] as? String) ?? nsError.localizedDescription23 throw .scriptFailed(detail)24 }25 }2627 // MARK: User scripts of other features2829 /// Installs a user script for this tab (isolated worlds only). It survives suspension: the engine re-installs30 /// it on the recreated web view. Built-in scripts and scripts of other features are untouched.31 public func installUserScript(_ descriptor: UserScriptDescriptor) {32 featureScripts.removeAll { $0.id == descriptor.id }33 featureScripts.append(descriptor)34 scriptRegistry?.install(descriptor)35 }3637 public func removeUserScript(id: String) {38 featureScripts.removeAll { $0.id == id }39 scriptRegistry?.remove(id: id)40 }4142 public var installedUserScriptIDs: [String] { featureScripts.map(\.id) }4344 // MARK: Reader4546 /// Extracts the main article of the current page. Throws `.readerUnavailable` when the page has no article47 /// or the result fails native validation.48 public func extractReaderArticle() async throws(WebEngineError) -> ReaderArticle {49 let script = BundledScript.reader.source + "\nreturn __orixReaderExtract(options);"50 let result = try await evaluate(script, arguments: ["options": .object([:])], in: .reader)51 return try ReaderHTMLPolicy.article(from: result)52 }5354 // MARK: Lens5556 /// The current text selection, read on demand.57 public func currentSelection() async throws(WebEngineError) -> TextSelection? {58 let value = try await evaluate("return window.__orixLens ? window.__orixLens.selection() : null;", in: .lens)59 guard case .object(let payload) = value else { return nil }60 guard let selection = try? BridgeValidator.selection(payload, pageURL: committedURL), !selection.isCollapsed else { return nil }61 return selection62 }6364 /// Starts element picking: the next click on the page reports that element in `lastPickedElement` instead of65 /// activating it; Escape cancels. `isPickingElement` tracks the mode.66 public func startElementPicking() async throws(WebEngineError) {67 lastPickedElement = nil68 let started = try await evaluate("return window.__orixLens ? window.__orixLens.startPicking() : false;", in: .lens)69 guard started.boolValue == true else { throw .scriptFailed("Lens is not available on this page") }70 isPickingElement = true71 }7273 public func stopElementPicking() async {74 isPickingElement = false75 _ = try? await evaluate("return window.__orixLens ? window.__orixLens.stopPicking() : false;", in: .lens)76 }7778 // MARK: Morph (per-site CSS)7980 /// Installs a stylesheet applied to documents whose host matches one of `hosts` (exact host or any81 /// sub-domain; `"*"` matches everything). Applied to the current page at once and to later loads at document82 /// start. CSS only: `@import`, remote `url()` and markup are refused.83 public func installStylesheet(id: String, css: String, hosts: [String]) throws(WebEngineError) {84 try MorphStylesheet.validate(css)85 let patterns = hosts.map { $0.lowercased() }.filter { !$0.isEmpty }86 guard !patterns.isEmpty else { throw .invalidStylesheet("No host pattern") }87 let call = "window.__orixMorph.applyForHosts(\(Self.jsLiteral(id)), \(Self.jsLiteral(css)), \(Self.jsLiteral(patterns)));"88 installUserScript(UserScriptDescriptor(id: Self.morphScriptID(id), source: BundledScript.morph.source + "\n" + call,89 world: .morph, injectionTime: .documentStart, mainFrameOnly: false))90 if webView != nil {91 Task { _ = try? await self.evaluate(BundledScript.morph.source + "\nreturn " + call, in: .morph) }92 }93 }9495 public func removeStylesheet(id: String) {96 removeUserScript(id: Self.morphScriptID(id))97 if webView != nil {98 Task { _ = try? await self.evaluate("return window.__orixMorph ? window.__orixMorph.remove(id) : false;",99 arguments: ["id": .string(id)], in: .morph) }100 }101 }102103 public var installedStylesheetIDs: [String] {104 featureScripts.compactMap { $0.id.hasPrefix("orix.morph.") ? String($0.id.dropFirst("orix.morph.".count)) : nil }105 }106107 static func morphScriptID(_ id: String) -> String { "orix.morph." + id }108109 /// A JavaScript literal for a JSON-encodable value (JSON is a subset of JavaScript).110 static func jsLiteral<Value: Encodable>(_ value: Value) -> String {111 guard let data = try? JSONEncoder().encode(value) else { return "null" }112 return String(decoding: data, as: UTF8.self)113 }114115 // MARK: Dev console116117 /// Turns the console mirror on or off. Errors, rejections and CSP violations are captured regardless; this118 /// adds `console.*` output, which requires the one bundled script that runs in the page world. Takes effect119 /// on the next load.120 public func setConsoleMirroring(_ enabled: Bool) {121 guard enabled != settings.mirrorsConsole else { return }122 settings.mirrorsConsole = enabled123 guard let registry = scriptRegistry, let controller = webView?.configuration.userContentController else { return }124 if enabled {125 installConsoleMirror(in: registry, controller: controller)126 } else {127 registry.remove(id: Self.consoleMirrorID)128 controller.removeScriptMessageHandler(forName: WebRuntimeConstants.consoleHandlerName, contentWorld: .page)129 }130 }131132 public func clearConsole() { consoleEntries.removeAll() }133}134135/// Validation of user-authored CSS for Morph.136public enum MorphStylesheet {137 public static let maximumLength = 500_000138139 /// Refuses anything that is not plain styling: stylesheets that pull other resources (`@import`, remote140 /// `url()`), legacy script hooks, or text that tries to close the `<style>` element.141 public static func validate(_ css: String) throws(WebEngineError) {142 guard css.utf16.count <= maximumLength else { throw .invalidStylesheet("Stylesheet too large") }143 // CSS allows escapes and comments inside keywords ("@imp\\6frt", "@im/**/port"): compare against a form144 // with escapes decoded and comments removed.145 var folded = unescape(css).lowercased()146 while let start = folded.range(of: "/*") {147 let end = folded.range(of: "*/", range: start.upperBound..<folded.endIndex)?.upperBound ?? folded.endIndex148 folded.removeSubrange(start.lowerBound..<end)149 }150 if folded.contains("@import") { throw .invalidStylesheet("@import is not allowed") }151 if folded.contains("</style") || folded.contains("<script") { throw .invalidStylesheet("Markup is not allowed") }152 if folded.contains("javascript:") || folded.contains("expression(") || folded.contains("-moz-binding") || folded.contains("behavior:") {153 throw .invalidStylesheet("Script hooks are not allowed")154 }155 var search = folded.startIndex156 while let range = folded.range(of: "url(", range: search..<folded.endIndex) {157 let rest = folded[range.upperBound...].drop { $0 == " " || $0 == "\"" || $0 == "'" || $0 == "\n" || $0 == "\t" }158 guard rest.hasPrefix("data:") || rest.hasPrefix("#") else {159 throw .invalidStylesheet("Only data: and fragment URLs are allowed in url()")160 }161 search = range.upperBound162 }163 if folded.contains("image-set(") && (folded.contains("http") || folded.contains("//")) {164 throw .invalidStylesheet("Remote images are not allowed")165 }166 }167168 /// Decodes CSS escapes: a backslash followed by one to six hex digits (and one optional whitespace) is that169 /// code point; a backslash followed by anything else is that character.170 static func unescape(_ css: String) -> String {171 var result = String.UnicodeScalarView()172 var scalars = css.unicodeScalars.makeIterator()173 var pending = scalars.next()174 while let scalar = pending {175 pending = scalars.next()176 guard scalar == "\\" else { result.append(scalar); continue }177 var hex = ""178 while let digit = pending, hex.count < 6, digit.properties.isASCIIHexDigit {179 hex.unicodeScalars.append(digit)180 pending = scalars.next()181 }182 if hex.isEmpty {183 if let literal = pending { result.append(literal); pending = scalars.next() }184 } else {185 if let value = UInt32(hex, radix: 16), let decoded = Unicode.Scalar(value), value != 0 { result.append(decoded) }186 if let space = pending, space == " " || space == "\n" || space == "\t" { pending = scalars.next() }187 }188 }189 return String(result)190 }191}192