Skip to content

armgit / cra

Public Imported from GitHub
0

The open-source Arc replacement for macOS. Spaces, pinned tabs, split view, Little Windows and Arc's shortcuts on Chromium, with your Arc sidebar imported in one go.

Another app's link in a new tab or window opens the app, not a blank tab (#207)

Victord1ad2af9adb8
diff --git a/Packages/CraCore/Sources/CraCore/AppLinks.swift b/Packages/CraCore/Sources/CraCore/AppLinks.swift
new file mode 100644
index 0000000..a7bbc65
--- /dev/null
+++ b/Packages/CraCore/Sources/CraCore/AppLinks.swift
@@ -0,0 +1,46 @@
+import Foundation
+
+/// Addresses a page hands to another app instead of loading (spotify:, zoommtg:, itms-apps:):
+/// Chrome's external protocols. In Arc a link, target=_blank link or window.open to one opens no
+/// tab: "Open Spotify?" comes up over the page and macOS opens the app (GitHub #207).
+public enum AppLinks {
+ public enum Kind: Equatable, Sendable {
+ /// The engine loads it (http, about:blank, a page's own web+ handler, Chromium's pages).
+ case page
+ /// Another app's: "Open <app>?" first (Chrome's external protocol dialog).
+ case asksFirst
+ /// Another app's, opened without asking: Chrome's allowed schemes (mailto:).
+ case opens
+ /// Never handed to macOS: Chrome's denied schemes (afp: mounts a share) and cra:, Cra's
+ /// own scripting scheme, which would reach the installed Cra.
+ case refused
+ }
+
+ /// Schemes the engines handle themselves, allowed or not: Chromium opens View Page Source
+ /// as a view-source: tab, runs a javascript: popup's script and refuses a web page's file: one.
+ static let pageSchemes: Set<String> = [
+ "http", "https", "about", "blob", "data", "filesystem", "ws", "wss", "file", "javascript",
+ "view-source", "chrome", "chrome-extension", "chrome-untrusted", "chrome-search", "devtools",
+ ]
+ /// The rest of Chrome's kDeniedSchemes (external_protocol_handler.cc), plus cra:.
+ static let refusedSchemes: Set<String> = [
+ "afp", "disk", "disks", "hcp", "ie.http", "login", "mk", "ms-help", "nntp", "res", "shell",
+ "vbscript", "vnd.ms.radio", "cra",
+ ]
+ /// Chrome's kAllowedSchemes.
+ static let openedSchemes: Set<String> = ["mailto", "news", "snews"]
+
+ /// What `url` is for a link or window.open that wants a new tab, or a WebKit page's own
+ /// navigation to a scheme WebKit doesn't load.
+ public static func kind(of url: String) -> Kind {
+ guard let colon = url.firstIndex(of: ":") else { return .page }
+ let scheme = url[..<colon].lowercased()
+ // RFC 3986: a letter, then letters, digits, + - . (anything else is not a scheme).
+ guard let first = scheme.first, first.isASCII, first.isLetter,
+ scheme.allSatisfy({ $0.isASCII && ($0.isLetter || $0.isNumber || "+-.".contains($0)) }) else { return .page }
+ // navigator.registerProtocolHandler's own schemes go to the page that registered them.
+ if scheme.hasPrefix("web+") || pageSchemes.contains(scheme) { return .page }
+ if refusedSchemes.contains(scheme) { return .refused }
+ return openedSchemes.contains(scheme) ? .opens : .asksFirst
+ }
+}
diff --git a/Packages/CraCore/Tests/CraCoreTests/AppLinksTests.swift b/Packages/CraCore/Tests/CraCoreTests/AppLinksTests.swift
new file mode 100644
index 0000000..887879a
--- /dev/null
+++ b/Packages/CraCore/Tests/CraCoreTests/AppLinksTests.swift
@@ -0,0 +1,39 @@
+import CraCore
+import Testing
+
+struct AppLinksTests {
+ @Test(arguments: [
+ // Spotify's "Open in Desktop app" (GitHub #207) and other apps' links.
+ ("spotify:album:06CjF89lLSSiVWXujVVtQs", AppLinks.Kind.asksFirst),
+ ("SPOTIFY:playlist:1", .asksFirst),
+ ("zoommtg://zoom.us/join?confno=1", .asksFirst),
+ ("itms-apps://apps.apple.com/app/id1", .asksFirst),
+ ("x-apple.systempreferences:com.apple.preference", .asksFirst),
+ ("mailto:[email protected]", .opens),
+ ("news:comp.lang", .opens),
+ // Pages.
+ ("https://open.spotify.com/album/1", .page),
+ ("http://localhost:3000", .page),
+ ("about:blank", .page),
+ ("", .page),
+ ("blob:https://example.com/1", .page),
+ ("data:text/html,hi", .page),
+ ("chrome-extension://abc/popup.html", .page),
+ ("devtools://devtools/bundled/inspector.html", .page),
+ ("web+cra:thing", .page),
+ ("/relative/path", .page),
+ ("1password:x", .page),
+ // Never to an app.
+ ("cra://action/closeTab", .refused),
+ ("CRA:action", .refused),
+ ("afp://server/share", .refused),
+ ("ms-help://x", .refused),
+ // The engines' own, allowed or not: never an app's.
+ ("file:///etc/passwd", .page),
+ ("javascript:alert(1)", .page),
+ ("view-source:https://example.com", .page),
+ ])
+ func kind(url: String, kind: AppLinks.Kind) {
+ #expect(AppLinks.kind(of: url) == kind)
+ }
+}
diff --git a/Sources/Cra/App/AppDelegate.swift b/Sources/Cra/App/AppDelegate.swift
index 49c8c16..71b54f3 100644
--- a/Sources/Cra/App/AppDelegate.swift
+++ b/Sources/Cra/App/AppDelegate.swift
@@ -106,6 +106,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
let hasNewExtension = !Set(installed).isSubset(of: welcomed)
try? JSONEncoder().encode(installed.sorted()).write(to: welcomedFile, options: .atomic)
DownloadDestinations.install(store: store)
+ AppLinkPrompt.install()
CraCEFRuntime.setStrayPageHandler { [weak self] url, profile in
Task { @MainActor in
guard let self else { return }
diff --git a/Sources/Cra/Services/AppLinkPrompt.swift b/Sources/Cra/Services/AppLinkPrompt.swift
new file mode 100644
index 0000000..f81c95a
--- /dev/null
+++ b/Sources/Cra/Services/AppLinkPrompt.swift
@@ -0,0 +1,57 @@
+import AppKit
+import CraCEF
+
+/// Chrome's external protocol dialog for a page in either engine: a link, target=_blank link or
+/// window.open to another app's address (AppLinks) opens no tab. "Open Spotify?" comes up over
+/// the page that asked, and macOS opens the app, as in Arc (GitHub #207: Spotify's "Open in
+/// Desktop app" left a blank spotify: tab). A Chromium page's same-tab links keep Chrome's own
+/// dialog (CraCEF's OnProtocolExecution).
+@MainActor
+enum AppLinkPrompt {
+ /// Chromium's new tabs and windows (CraCEF's OnBeforePopup) come here first.
+ static func install() {
+ CraCEFRuntime.setAppLinkHandler { browser, url, userGesture in
+ MainActor.assumeIsolated { handle(url, from: browser, userGesture: userGesture) }
+ }
+ }
+
+ /// Whether `url` is another app's. Then it is dealt with here (asked about, opened or
+ /// refused) and must not load or open a tab. Without a click (`userGesture`) nothing opens.
+ @discardableResult
+ static func handle(_ url: String, from browser: CraBrowser, userGesture: Bool) -> Bool {
+ let kind = AppLinks.kind(of: url)
+ if kind == .page { return false }
+ let page = browser.isIncognito ? "(incognito)" : CraLog.host(browser.currentURL)
+ let scheme = url.prefix { $0 != ":" }.lowercased() + ":"
+ guard kind != .refused, userGesture, let target = URL(string: url) else {
+ CraLog.note("page \(page) can't open \(scheme) \(kind == .refused ? "(refused)" : "(no click)")")
+ return true
+ }
+ // No app for it: nothing happens, as in Chrome.
+ guard let app = NSWorkspace.shared.urlForApplication(toOpen: target) else {
+ CraLog.note("page \(page) wants \(scheme), no app opens it")
+ return true
+ }
+ let name = FileManager.default.displayName(atPath: app.path).replacingOccurrences(of: ".app", with: "")
+ if kind == .opens {
+ CraLog.note("page \(page) opens \(name) for \(scheme)")
+ NSWorkspace.shared.open(target)
+ return true
+ }
+ // One question at a time: a page asking again while it is up gets nothing.
+ guard let window = browser.containerView.window, window.attachedSheet == nil else {
+ CraLog.note("page \(page) asks for \(name) again, already asking")
+ return true
+ }
+ CraLog.note("page \(page) asks to open \(name) for \(scheme)")
+ let alert = NSAlert()
+ alert.messageText = "Open \(name)?"
+ alert.informativeText = "\(URL(string: browser.currentURL)?.host ?? "This site") wants to open this application."
+ alert.addButton(withTitle: "Open \(name)")
+ alert.addButton(withTitle: "Cancel")
+ alert.beginSheetModal(for: window) { response in
+ if response == .alertFirstButtonReturn { NSWorkspace.shared.open(target) }
+ }
+ return true
+ }
+}
diff --git a/Sources/Cra/Services/WebKit/WebKitBrowser.swift b/Sources/Cra/Services/WebKit/WebKitBrowser.swift
index 035584b..647c173 100644
--- a/Sources/Cra/Services/WebKit/WebKitBrowser.swift
+++ b/Sources/Cra/Services/WebKit/WebKitBrowser.swift
@@ -29,6 +29,8 @@ final class WebKitBrowser: CraBrowser, WKNavigationDelegate, WKUIDelegate, WKDow
private var closed = false
private var pageClosedItself = false
private var committed = false
+ /// The page's own navigation to another app's address asked already (decidePolicyFor).
+ private var askedForAppOnThisPage = false
private var lastStatus = 0
private var lastLoadingState: [Bool] = []
private var observations: [NSKeyValueObservation] = []
@@ -311,12 +313,17 @@ final class WebKitBrowser: CraBrowser, WKNavigationDelegate, WKUIDelegate, WKDow
if action.shouldPerformDownload { return decisionHandler(.download, preferences) }
guard let url = action.request.url else { return decisionHandler(.allow, preferences) }
let scheme = url.scheme?.lowercased() ?? ""
- // mailto:, zoommtg:, itms-apps: go to their app, only from a click.
// A web page never opens local files (Chromium's rule; Cra's own file:// pages are Chromium's).
if scheme == "file" { return decisionHandler(.cancel, preferences) }
if !["http", "https", "about", "blob", "data"].contains(scheme) {
- // mailto:, zoommtg:, itms-apps: go to their app from a click, after Chrome's "Open <app>?".
- if action.navigationType == .linkActivated { confirmOpeningApp(for: url) }
+ // zoommtg:, spotify:, itms-apps: go to their app after Chrome's "Open <app>?". A click
+ // asks each time; the page's own redirect (Spotify's "open in the app" when a link
+ // to it opens) asks once per page it loads, from the main frame, as Chrome's flood
+ // guard lets it.
+ let click = action.navigationType == .linkActivated
+ let redirect = !click && action.targetFrame?.isMainFrame == true && !askedForAppOnThisPage
+ if redirect { askedForAppOnThisPage = true }
+ AppLinkPrompt.handle(url.absoluteString, from: self, userGesture: click || redirect)
return decisionHandler(.cancel, preferences)
}
guard action.navigationType == .linkActivated else { return decisionHandler(.allow, preferences) }
@@ -339,21 +346,6 @@ final class WebKitBrowser: CraBrowser, WKNavigationDelegate, WKUIDelegate, WKDow
decisionHandler(.allow, preferences)
}
- /// Chrome's external protocol dialog: the app the link wants, named, before macOS opens it.
- @MainActor
- private func confirmOpeningApp(for url: URL) {
- guard let app = NSWorkspace.shared.urlForApplication(toOpen: url), let window = container.window else { return }
- let name = FileManager.default.displayName(atPath: app.path).replacingOccurrences(of: ".app", with: "")
- let alert = NSAlert()
- alert.messageText = "Open \(name)?"
- alert.informativeText = "\(webView?.url?.host ?? "This site") wants to open this application."
- alert.addButton(withTitle: "Open \(name)")
- alert.addButton(withTitle: "Cancel")
- alert.beginSheetModal(for: window) { response in
- if response == .alertFirstButtonReturn { NSWorkspace.shared.open(url) }
- }
- }
-
func webView(_ webView: WKWebView, decidePolicyFor response: WKNavigationResponse,
decisionHandler: @escaping @MainActor (WKNavigationResponsePolicy) -> Void) {
let http = response.response as? HTTPURLResponse
@@ -368,6 +360,7 @@ final class WebKitBrowser: CraBrowser, WKNavigationDelegate, WKUIDelegate, WKDow
}
func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
+ askedForAppOnThisPage = false
setCommitted(true)
}
@@ -419,6 +412,9 @@ final class WebKitBrowser: CraBrowser, WKNavigationDelegate, WKUIDelegate, WKDow
func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for action: WKNavigationAction,
windowFeatures: WKWindowFeatures) -> WKWebView? {
let url = action.request.url?.absoluteString ?? ""
+ // Another app's address (Spotify's "Open in Desktop app" #207): no tab, "Open <app>?" over
+ // this page. WebKit asks here only for a click (javaScriptCanOpenWindowsAutomatically is off).
+ if AppLinkPrompt.handle(url, from: self, userGesture: true) { return nil }
// A target=_blank link: a new tab without an opener, like Chrome's noopener default.
if action.navigationType == .linkActivated {
let mods = action.modifierFlags
diff --git a/Sources/CraCEF/CraCEF.mm b/Sources/CraCEF/CraCEF.mm
index e2529a9..dd2082b 100644
--- a/Sources/CraCEF/CraCEF.mm
+++ b/Sources/CraCEF/CraCEF.mm
@@ -71,6 +71,7 @@ static NSHashTable<CraBrowser*>* g_allBrowsers = nil;
/// Closed tabs whose page stays alive until its downloads end (see -[CraBrowser close]).
static NSMutableSet<CraBrowser*>* g_parkedBrowsers = nil;
static void (^g_strayPageHandler)(NSString*, NSString*) = nil;
+static BOOL (^g_appLinkHandler)(CraBrowser*, NSString*, BOOL) = nil;
// Downloads whose save panel was cancelled (#190): cancelled on their next update, never shown.
static std::set<uint32_t> g_cancelledDownloads;
static void (^g_downloadDestinationHandler)(NSString*, NSString*, void (^)(NSString*)) = nil;
@@ -1306,6 +1307,8 @@ public:
CraPageSettings(settings);
return false;
}
+ // Another app's address (spotify:) opens no tab: Cra asks "Open <app>?" over this page.
+ if (g_appLinkHandler && g_appLinkHandler(o, NSStringFromCef(target_url), user_gesture)) return true;
// A target=_blank link the user clicked (Shift-clicked: a new window) may open in a
// Peek; window.open with features (a sign-in popup) is CEF_WOD_NEW_POPUP and stays one.
if (user_gesture && (target_disposition == CEF_WOD_NEW_FOREGROUND_TAB || target_disposition == CEF_WOD_NEW_WINDOW)
@@ -2743,6 +2746,7 @@ static void MarkProfileExitedCleanly(NSString* profileDir) {
+ (BOOL)anotherInstanceWasNotified { return g_alreadyRunning; }
+ (void)setRelaunchHandler:(void (^)(NSArray<NSString*>*))handler { g_relaunchHandler = [handler copy]; }
+ (void)setStrayPageHandler:(void (^)(NSString*, NSString*))handler { g_strayPageHandler = [handler copy]; }
++ (void)setAppLinkHandler:(BOOL (^)(CraBrowser*, NSString*, BOOL))handler { g_appLinkHandler = [handler copy]; }
+ (void)setDownloadDestinationHandler:(void (^)(NSString*, NSString*, void (^)(NSString*)))handler { g_downloadDestinationHandler = [handler copy]; }
+ (void)setProcessEventHandler:(void (^)(NSString*, NSString*, NSString*))handler { g_processEventHandler = [handler copy]; }
+ (BOOL)isExtensionWindow:(NSWindow*)window { return window && [g_extensionWindows containsObject:window]; }
diff --git a/Sources/CraCEF/include/CraCEF.h b/Sources/CraCEF/include/CraCEF.h
index bca69aa..b9c0c08 100644
--- a/Sources/CraCEF/include/CraCEF.h
+++ b/Sources/CraCEF/include/CraCEF.h
@@ -312,6 +312,11 @@ typedef NS_ENUM(NSInteger, CraDownloadState) {
/// ("Default", "Profile <id>"; nil off the record); Chrome's own window for it is closed.
/// Popup-type windows (windows.create({type: "popup"})) stay Chrome's windows.
+ (void)setStrayPageHandler:(void (^)(NSString *url, NSString * _Nullable profile))handler;
+/// A new tab or window a page asks for (target=_blank, window.open) at another app's address
+/// (spotify:): the handler gets the page's browser, the address and whether a click asked, and
+/// returns YES when it took it (Cra's "Open <app>?"); then no tab opens (GitHub #207). On the
+/// main thread, before Peek and the delegate's popupHostForURL.
++ (void)setAppLinkHandler:(BOOL (^)(CraBrowser *browser, NSString *url, BOOL userGesture))handler;
/// Where a page's download is saved (GitHub #190): the handler gets the browser's profile folder
/// (nil for Default and off the record) and the file name Chromium suggests, and calls `completion`
/// on the main thread with the full path to save to, or nil to cancel the download (a save panel
diff --git a/Tests/Scenarios/external-app-links.scenario b/Tests/Scenarios/external-app-links.scenario
new file mode 100644
index 0000000..5b13d40
--- /dev/null
+++ b/Tests/Scenarios/external-app-links.scenario
@@ -0,0 +1,40 @@
+# A link or window.open to another app's scheme (spotify:, zoommtg:) opens no tab: the page that
+# asked shows "Open <app>?" and macOS opens the app, as in Arc (GitHub #207, Spotify's "Open in
+# Desktop app"). macappstore: has an app on every Mac and is asked about (Chrome opens mailto:
+# without asking); the prompt is never answered. ${WEBKIT} pages run in WebKit
+# (ProtectedMediaSites), ${PAGE} in Chromium.
+budget rss=900 stalls50=40
+pace 0.5
+
+# WebKit: window.open from a click (the cdp script counts as one) asks over the page, no tab.
+cra://open?url=${WEBKIT}/page.html?n=webkit
+expect-log loaded localhost \(HTTP 200\)
+cra://debug?cdp=Runtime.evaluate&params={"expression":"String(window.open('macappstore://apps.apple.com/app/id1?n=open'))"}
+expect-log Cra cdp Runtime.evaluate .*"value":"null"
+expect-log page localhost asks to open .* for macappstore:
+# A target=_blank link while that question is up: one at a time.
+cra://debug?cdp=Runtime.evaluate&params={"expression":"(a=>(a.href='macappstore://apps.apple.com/app/id1?n=blank',a.target='_blank',document.body.append(a),a.click(),'clicked'))(document.createElement('a'))"}
+expect-log Cra cdp Runtime.evaluate .*"value":"clicked"
+expect-log page localhost asks for .* again, already asking
+# The page's own redirect asks once per page it loads; a second gets nothing.
+cra://debug?pageJS=location.href='macappstore://apps.apple.com/app/id1?n=redirect1'
+wait 1
+cra://debug?pageJS=location.href='macappstore://apps.apple.com/app/id1?n=redirect2'
+expect-log page localhost can't open macappstore: \(no click\)
+# Cra's own scheme never goes to an app (it would reach the installed Cra).
+cra://debug?cdp=Runtime.evaluate&params={"expression":"String(window.open('cra://action/closeTab'))"}
+expect-log page localhost can't open cra: \(refused\)
+
+# Chromium, in a Little Window (the main window's question is still up): the same.
+cra://open?url=${PAGE}?n=little&little=1
+wait 3
+cra://debug?cdp=Runtime.evaluate&target=little&params={"expression":"String(window.open('macappstore://apps.apple.com/app/id1?n=copen'))","userGesture":true}
+expect-log Cra cdp Runtime.evaluate .*"value":"null"
+expect-log page 127\.0\.0\.1 asks to open .* for macappstore:
+cra://debug?cdp=Runtime.evaluate&target=little&params={"expression":"(a=>(a.href='macappstore://apps.apple.com/app/id1?n=cblank',a.target='_blank',document.body.append(a),a.click(),'clicked'))(document.createElement('a'))","userGesture":true}
+expect-log Cra cdp Runtime.evaluate .*"value":"clicked"
+expect-log page 127\.0\.0\.1 asks for .* again, already asking
+wait 1
+cra://debug?checkStore=1
+reject-log opens a page for macappstore:
+reject-log shown: \(no page\)