Is there a way to get current URL from currently opened browser (Chrome, Firefox, or Safari) using Swift?
Asked
Active
Viewed 2,855 times
0
-
What code have you written yourself to try and do this? Don't just ask people to do the work for you. Tell us what you've tried and what didn't work, to demonstrate that you’ve taken the time to try to help yourself, it saves us from giving obvious answers, and most of all it helps you get a more specific and relevant answer. Also see [Ask] – Ashley Mills Feb 21 '17 at 13:54
-
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
2
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
}
}
SUMIT NIHALANI
- 319
- 1
- 10