Is there a way to get current URL from currently opened browser (Chrome, Firefox, or Safari) using Swift?
Asked
Active
Viewed 3,636 times
0
-
It might be possible to do it with AppleScript. – El Tomato Feb 21 '17 at 14:06
-
I found [this](http://stackoverflow.com/a/6111592) approach, that uses AppleScript. But I couldn't convert it to Swift properly, yet. Especially this line `NSString *result = [[NSString alloc] initWithCharacters:(unichar*)[data bytes] length:[data length] / sizeof(unichar)];` – ttrs Feb 21 '17 at 14:38
2 Answers
4
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)
-
1Would it be correct to assume that if I'm checking for Firefox that I would add and else if statement for "Firefox"? – Alex Wang Mar 21 '18 at 03:33
-
This is really useful for me I Would like to click on Google Chrome-> View-> Developer-> Allow JavaScript from AppleEvent check using Apple Script Can you please help me to do the same – Swapnil1156035 Oct 05 '18 at 13:25
-
No Firefox doesn't support this simple way of getting the URL of the tab – Lucas van Dongen Apr 25 '20 at 12:51
-
Stopped working on Chrome 103.0.5060.53, execution error: Google Chrome got an error: Can’t get window 1. (-1728) – Teddy C Jul 01 '22 at 07:13
4
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
}
}

Matt Sephton
- 3,711
- 4
- 35
- 46

SUMIT NIHALANI
- 387
- 1
- 10