Getting the source of a Safari tab by name

Hi everyone,

I’m working on a script where I need to grab the source from a specific Safari tab. Getting the source from the current tab is easy:

tell application “Safari”
set sourceHTML to source of document 1
end tell

What’s the best method to retrieve the source of a tab that isn’t necessarily the currently visible one? I can get the names of every open tab easily and even narrow it down using “begins with”:

tell application “Safari”
set myTabs to the name of every tab of every window whose name begins with (“foo”)
end tell

How would I use the names in myTabs from the example above to get the source for those tabs which aren’t necessarily currently visible?

Thanks.

-Tim

The answer is right there in your code. Notice how you had to reference the tabs… you had to ask for the tabs that were part of a window. And if you look at Safari’s dictionary for tab, it will tell you that a tab is contained by a window. Therefore to target a specific tab you have to target a window first, and then a tab. So something like this would work.

tell application "Safari"
	set myTabs to the name of every tab of every window whose name begins with ("foo")
	
	tell tab "bar" of window "foo"
		set theSource to source
	end tell
end tell
return theSource

You wouldn’t necessarily need to get the tab names to get the sources:

tell application "Safari"
	set mySources to source of every tab of every window whose name begins with "Mac"
end tell

It’s ambiguous in English, but the filter here works on the names of the tabs, not on those of the windows, unless you use parenthesis to indicate otherwise. The result in this case is a list of lists, each list in the list representing an open window and any items in the lists the sources of any matching tabs.

Brilliant guys. Thanks. I’m still not used to the verbosity of AppleScript.

-Tim