Get current URL from browser in macOS

Table of Contents

27 Sep 2022

I've been looking for a solution to grab the current browser's URL via keyboard shortcut, to include in my workflows !projects/clipee

Unsuccessfully so far.

resources

Solution might be with AppleScript.

func getBrowserURL(_ appName: String) -> String? {
        guard let scriptText = getScriptText(appName) else { return nil }
        var error: NSDictionary?
        guard let script = NSAppleScript(source: scriptText) else { return nil }

        guard let outputString = script.executeAndReturnError(&error).stringValue else {
            if let error = error {
                Logger.error("Get Browser URL request failed with error: \(error.description)")
            }
            return nil
        }

        // clean url output - remove protocol & unnecessary "www."
        if let url = URL(string: outputString),
            var host = url.host {
            if host.hasPrefix("www.") {
                host = String(host.dropFirst(4))
            }
            let resultURL = "\(host)\(url.path)"
            return resultURL
        }

        return nil
    }

    func getScriptText(_ appName: String) -> String? {
        switch appName {
        case "Google Chrome":
            return "tell app \"Google Chrome\" to get the url of the active tab of window 1"
        case "Safari":
            return "tell application \"Safari\" to return URL of front document"
        default:
            return nil
        }
    }

links

social