ttrs
ttrs

Reputation: 127

Get current URL from browser in macOS

Is there a way to get current URL from currently opened browser (Chrome, Firefox, or Safari) using Swift?

Upvotes: 0

Views: 4190

Answers (3)

Donat Kabashi
Donat Kabashi

Reputation: 546

If you are developing a Mac app, make sure the following two actions are performed for the above scripts to work.

  1. You add the following entitlements in your .entitlements file:

enter image description here

  1. You add the following property in your info.plist file:

enter image description here

Upvotes: 0

SUMIT NIHALANI
SUMIT NIHALANI

Reputation: 417

Swift solution using 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
    }
}

Upvotes: 5

DrummerB
DrummerB

Reputation: 40201

You could use some Apple Script like this:

set myURL to "No browser active"
set nameOfActiveApp to (path to frontmost application as text)
if "Safari" is in nameOfActiveApp then
    tell application "Safari"
        set myURL to the URL of the current tab of the front window
    end tell
else if "Chrome" is in nameOfActiveApp then
    tell application "Google Chrome"
        set myURL to the URL of the active tab of the front window
    end tell
end if

display dialog (myURL)

Upvotes: 4

Related Questions