Jump to content

[How To] Get frontmost tab’s url and title of various browsers


Recommended Posts

Starting with Alfred 5, you can use Automation Tasks to achieve the same results and more.

 

I’ve been seeing a lot of workflows that need to interact with a browser via AppleScript (usually to get a page’s url), but most of them seem to settle on a single browser, which is a shame. I can understand — AppleScript is a pain, and since each browser implements these functions however they want, finding the best way to do it with each one can be difficult, so here’s the code for most of them.

 

The code for this may seem massive, but it is not. Read the comments to understand when to use what.

You can find the latest version of this as a gist.

 

-- AppleScript --

-- This example is meant as a simple starting point to show how to get the information in the simplest available way.
-- Keep in mind that when asking for a `return` after another, only the first one will be output.
-- This method is as good as its JXA counterpart.

-- Chromium variants include "Google Chrome", "Chromium", "Opera", "Vivaldi", "Brave Browser", "Microsoft Edge".
-- Specific editions are valid, including "Google Chrome Canary", "Microsoft Edge Dev".
-- "Google Chrome" Example:
tell application "Google Chrome" to return title of active tab of front window
tell application "Google Chrome" to return URL of active tab of front window
-- "Chromium" Example:
tell application "Chromium" to return title of active tab of front window
tell application "Chromium" to return URL of active tab of front window

-- Webkit variants include "Safari", "Webkit".
-- Specific editions are valid, including "Safari Technology Preview".
-- "Safari" Example:
tell application "Safari" to return name of front document
tell application "Safari" to return URL of front document
-- "Webkit" Example:
tell application "Webkit" to return name of front document
tell application "Webkit" to return URL of front document

-- This example returns both the title and URL for the frontmost tab of the active browser, separated by a newline.
-- For shorter code inclusive of all editions, only the start of the application name is checked.
-- Keep in mind that to be able to use a variable in `tell application` — via `using terms from` — we’re basically requiring that referenced browser to be available on the system.
-- That means that to use this on "Google Chrome Canary" or "Chromium", "Google Chrome" needs to be installed. Same for other browsers.
-- This method also does not exit with a non-zero exit status when the frontmost application is not a supported browser.
-- For the aforementioned reasons, this method is inferior to its JXA counterpart.

tell application "System Events" to set frontApp to name of first process whose frontmost is true

if (frontapp starts with "Google Chrome") or (frontApp starts with "Chromium") or (frontApp starts with "Opera") or (frontApp starts with "Vivaldi") or (frontApp starts with "Brave Browser") or (frontApp starts with "Microsoft Edge") then
  using terms from application "Google Chrome"
    tell application frontApp to set currentTabTitle to title of active tab of front window
    tell application frontApp to set currentTabUrl to URL of active tab of front window
  end using terms from
else if (frontApp starts with "Safari") or (frontApp starts with "Webkit") then
  using terms from application "Safari"
    tell application frontApp to set currentTabTitle to name of front document
    tell application frontApp to set currentTabUrl to URL of front document
  end using terms from
else
  return "You need a supported browser as your frontmost app"
end if

return currentTabUrl & "\n" & currentTabTitle

 

// JavaScript for Automation (JXA) //

// This example is meant as a simple starting point to show how to get the information in the simplest available way.
// Keep in mind that when asking for a value after another, only the last one one will be output.
// This method is as good as its AppleScript counterpart.

// Chromium variants include "Google Chrome", "Chromium", "Opera", "Vivaldi", "Brave Browser", "Microsoft Edge".
// Specific editions are valid, including "Google Chrome Canary", "Microsoft Edge Dev".
// "Google Chrome" Example:
Application('Google Chrome').windows[0].activeTab.name()
Application('Google Chrome').windows[0].activeTab.url()
// "Chromium" Example:
Application('Chromium').windows[0].activeTab.name()
Application('Chromium').windows[0].activeTab.url()

// Webkit variants include "Safari", "Webkit".
// Specific editions are valid, including "Safari Technology Preview".
// "Safari" Example:
Application('Safari').windows[0].currentTab.name()
Application('Safari').windows[0].currentTab.url()
// "Webkit" Example:
Application('Webkit').windows[0].currentTab.name()
Application('Webkit').windows[0].currentTab.url()

// This example returns both the title and URL for the frontmost tab of the active browser, separated by a newline.
// For shorter code inclusive of all editions, only the start of the application name is checked.
// This method is superior to its AppleScript counterpart. It does not need a "main" browser available on the system to reuse the command on similar ones and throws a proper error code on failure.

const frontmost_app_name = Application('System Events').applicationProcesses.where({ frontmost: true }).name()[0]
const frontmost_app = Application(frontmost_app_name)

const chromium_variants = ['Google Chrome', 'Chromium', 'Opera', 'Vivaldi', 'Brave Browser', 'Microsoft Edge']
const webkit_variants = ['Safari', 'Webkit']

if (chromium_variants.some(app_name => frontmost_app_name.startsWith(app_name))) {
  var current_tab_title = frontmost_app.windows[0].activeTab.name()
  var current_tab_url = frontmost_app.windows[0].activeTab.url()
} else if (webkit_variants.some(app_name => frontmost_app_name.startsWith(app_name))) {
  var current_tab_title = frontmost_app.documents[0].name()
  var current_tab_url = frontmost_app.documents[0].url()
} else {
  throw new Error('You need a supported browser as your frontmost app')
}

current_tab_url + '\n' + current_tab_title

 

Other browsers
Firefox
Absent since although it’s possible to get the window’s title, it’s not possible to get its URL (it used to be, before version 3.6). It’s possible via hacky ways that consist of sending keystrokes, but those can be unreliable. This bug is being tracked in Bugzilla.

Link to comment

I’ve been seeing a lot of workflows that need to interact with a browser via AppleScript (usually to get a page’s url), but most of them seem to settle on a single browser (usually Safari), which is a shame. I can certainly understand — applescript is a pain, and since each browser implements this functions however they want, finding the best way to do it with each one can be difficult, so here’s the code for some of them.

You can find the latest version as a gist

# Browser
# applescript to get frontmost tab's url
# applescript to get frontmost tab's page title
 
# Google Chrome
tell application "Google Chrome" to return URL of active tab of front window
tell application "Google Chrome" to return title of active tab of front window
# Google Chrome Canary
tell application "Google Chrome Canary" to return URL of active tab of front window
tell application "Google Chrome Canary" to return title of active tab of front window
# Safari
tell application "Safari" to return URL of front document
tell application "Safari" to return name of front document
# Webkit
tell application "Webkit" to return URL of front document
tell application "Webkit" to return name of front document
# Opera
tell application "Opera" to return URL of front document
tell application "Opera" to return name of front document
# Camino
tell application "Camino" to return URL of current tab of front browser window
tell application "Camino" to return name of current tab of front browser window 

This will output the relevant information. If you want it to be set as a variable, change return to set theVariable to.

You’ll notice Firefox is absent. That’s because with it, even though it’s possible to get the window’s title, it’s not possible to get it’s URL. There are some hacky ways that consist of sending keystrokes, but those can be very unreliable, so I prefer to leave them out (resources on the web are full of hacky ways for every browser, and I want this to only show the “correct”, reliable ones).

 

I thought that Firefox didn't support AppleScript. Apparently I was wrong. Nice work though, thanks for sharing.

Link to comment
  • 2 months later...

Updated the list.

 

Removed support for Camino. As a reference, it was

# Camino
tell application "Camino" to return URL of current tab of front browser window
tell application "Camino" to return name of current tab of front browser window 
Link to comment
  • 2 weeks later...

A simple code to get the url of whatever browser the user is in.

Note firefox code is hacky at its best.

tell application "System Events"
	set myApp to name of first application process whose frontmost is true
	if myApp is "Google Chrome" then
		tell application "Google Chrome" to return URL of active tab of front window
	else if myApp is "Opera" then
		tell application "Opera" to return URL of front document
	else if myApp is "Safari" then
		tell application "Safari" to return URL of front document
	else if myApp is "Firefox" then
		tell application "System Events"
			keystroke "l" using command down
			keystroke "c" using command down
		end tell
		delay 0.5
		return the clipboard
	else
		return
	end if
end tell
Link to comment

A simple code to get the url of whatever browser the user is in.

Note firefox code is hacky at its best.

 

You’ll see on the first post that’s the reason I decided to not include Firefox in the list — it’s not a reliable method. This is supposed to be a list that includes the shortest, easiest to compreend, most effective ways of getting that information, which is why Firefox is absent — like you said, it needs a hack. Camino was removed because it was discontinued.

 

I do something similar to that script on my PinAdd workflow (if the user picks “depends” as the browser), but I use bash to call the relevant information. The goal of this post is not to use applescript, but much to the contrary, to show how to use it to the absolute minimum just to get the relevant information you need to, from each browser, so you can call it from your language of choice.

Link to comment

 

You’ll see on the first post that’s the reason I decided to not include Firefox in the list — it’s not a reliable method. This is supposed to be a list that includes the shortest, easiest to compreend, most effective ways of getting that information, which is why Firefox is absent — like you said, it needs a hack. Camino was removed because it was discontinued.

 

I do something similar to that script on my PinAdd workflow (if the user picks “depends” as the browser), but I use bash to call the relevant information. The goal of this post is not to use applescript, but much to the contrary, to show how to use it to the absolute minimum just to get the relevant information you need to, from each browser, so you can call it from your language of choice.

 

I agree with you. It's not really a solution. But I had to figure out how to do that.

To save others time I shared that script. If someone wants to use it can use it.

 

Thanks again :)

Link to comment
  • 2 months later...
  • 2 months later...

Found this post searching Google. I've been trying to mess around with a script to use as a app on my dock that when clicked will save the returned URL as a file on my desktop with the proper ".webloc" extension. In reading the Applescript dictionary for Google Chrome I see there is support for "id", "title" and "URL" to save as a bookmark but, is there any way to just save it to the desktop or a specific folder? Forgive me if this is thread jacking in any way. Just thought it would be helpful attached here at the bottom if anyone else was searching for it too.

 

 

Link to comment

Found this post searching Google. I've been trying to mess around with a script to use as a app on my dock that when clicked will save the returned URL as a file on my desktop with the proper ".webloc" extension. In reading the Applescript dictionary for Google Chrome I see there is support for "id", "title" and "URL" to save as a bookmark but, is there any way to just save it to the desktop or a specific folder? Forgive me if this is thread jacking in any way. Just thought it would be helpful attached here at the bottom if anyone else was searching for it too.

 

I doubt there would be a way to just save it off as a webloc built in to the AppleScript dictionary for it but may I ask what the end goal is for this? why do you want to save them as webloc? Are you wanting to be able to search through saved items or something? Also, it's been a little while since I've done it but, webloc files are just xml so you could grab the data you want, create a little xml string (in applescript or however you're doing it) and write that to a file. Wouldn't think it would be too difficult.

Link to comment

TBH the end goal is for me satisfy my need to make Applescript do something weird and learn as I go. I'm a visual learner so reading syntax from man pages is about as confusing as algebra.......and I REALLY don't get algebra. :-P

So I scour the internet at night searching for the most random of code snippets to tear down and learn from. As far as my previous post I guess the initial goal is to just have the ability to surf the net and when I'm on a page I want to read later I can simply click my icon in the dock and it will create a file on the desktop (.webloc) that shortcuts to that URL. Perhaps I can save it to my Dropbox path and have it available to all of my other Mac's or just for archival purposes. I'm an avid user of Chrome out side of work and Firefox at work, both browsers offering a bookmark syncing service but this would be my of doing it, again mainly just to learn some new Applescript as I go.

 

What I put together this morning..

tell application "Google Chrome"
	get URL of active tab of first window as text
end tell

tell application "Finder"
	set goHome to (path to home folder as text)
	set nextLvl to goHome & "Dropbox:Weblocs" as alias
	set fullPath to quoted form of POSIX path of nextLvl
	set fileName to POSIX path of (nextLvl & fileName & ".webloc")
end tell

It's missing pieces, like the definition of "fileName" but I'm getting things together. Assuming I can turn the URL into plain text and append .webloc on the end, saving it as a file in my Dropbox. Make sense?

Link to comment
  • 4 months later...

The problem won’t be related to the code itself, then, but to something you’re doing and/or some configuration you have. How are you trying to execute the code?

 

If I try to compile the following code from above in AppleScript Editor it won't compile:

 

tell application "Google Chrome" to return URL of active tab of front window

 

 

It highlights the 'active tab' part and the error message says:

 

Syntax Error

A property can't go after this identifier

 

 

Here's a script that I used to use that used to work OK for, but now won't compile, giving the same error message:

 

tell application "Google Chrome" to set TransferURL to URL of active tab of first window
tell application "Safari" to open location TransferURL
tell application "Safari" to activate
Link to comment

It’s extremely likely the problem lies on your end. Just tried that code and it worked as expected, and I can’t seem to find anyone else with your problem, searching for it.

I suggest you ask about your issue on stackoverflow, askdifferent, or the chrome forums (if the problem does lie somewhere with chrome, which is unclear). That way you’ll have the attention of way more eyes and minds. The problem is not related to Alfred, so there’s no reason to ask about it only here.

Link to comment

It’s extremely likely the problem lies on your end. Just tried that code and it worked as expected, and I can’t seem to find anyone else with your problem, searching for it.

I suggest you ask about your issue on stackoverflow, askdifferent, or the chrome forums (if the problem does lie somewhere with chrome, which is unclear). That way you’ll have the attention of way more eyes and minds. The problem is not related to Alfred, so there’s no reason to ask about it only here.

 

Ah, so I was right originally. It is strange  :P

 

Thanks for the links, I'll look into at one of those.

Link to comment

Haha, right :P

 

Actually, I've just tried it on my 10.9.2 machine and it works fine. I'm on a 10.9.3 beta on this Mac, so it looks like that's the cause of the problem. I'll install the final build of 10.9.3 and hope that it's OK on there.

Link to comment
  • 1 year later...

I just tried

 

tell application "System Events" to set frontApp to name of first process whose frontmost is true

if (frontApp = "Safari") or (frontApp = "Webkit") then
  using terms from application "Safari"
    tell application frontApp to close current tab of front window
  end using terms from
end if
And it worked without a problem.
Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...