swift 在macOS中从浏览器获取当前URL

xpszyzbs  于 2023-05-27  发布在  Swift
关注(0)|答案(2)|浏览(204)

有没有一种方法可以使用Swift从当前打开的浏览器(Chrome,Firefox或Safari)中获取当前URL?

5anewei6

5anewei61#

你可以像这样使用Apple Script

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)
xriantvc

xriantvc2#

使用AppleScript的Swift方案

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
    }
}

相关问题