Submit Hint Search The Forums LinksStatsPollsHeadlinesRSS
14,000 hints and counting!

Useful script examples for Safari Web Browsers
I was working with AppleScript for Safari, and decided to make a script that demonstrated some of the handy things you could do. Hope they prove as useful to others as they were for me.

Here is the examples script. Feel free to pull parts out and place them in your own scripts as needed. There is code for manipulating tabs, setting bookmarks, and emailing web pages.
tell application "Safari"
  set currentTab to current tab of front window --if you have multiple windows, controlling/choosing them works much the same way as tabs
  set currentName to currentTab's name
  log currentName
  set currentURL to currentTab's URL
  log currentURL
  (*set currentText to currentTab's text
  log currentText*)
  (*set currentSource to currentTab's source
  log currentSource*)
  --these are commented out because they return, of course, very long strings
  set currentVisi to currentTab's visible
  log currentVisi
  set URL of currentTab to "" --replcaces current URL. other properties are read-only.
  set twoName to (tab 2 of front window)'s name
  log twoName
  set lastName to (last tab of front window)'s name
  log lastName
  set currentTabNum to index of current tab of front window
  log currentTabNum --the selected tab can't be the first or last
  set nextTab to (tab (currentTabNum + 1) of front window)
  set nextName to nextTab's name
  log nextName
  set prevTab to (tab (currentTabNum - 1) of front window)
  set prevName to prevTab's name
  log prevName
  set tabsList to front window's tabs as list --gets all open tabs
  set tabsInfo to {} as list
  repeat with currTab in tabsList
    set currName to currTab's name
    set currURL to currTab's URL
    set currNum to currTab's index
    set tabsInfo to tabsInfo {} as list
  end repeat
  log tabsInfo
  log _name of item 2 of tabsInfo
  --this creates a list of records about the tabs you have open.
  close current tab of front window
  if exists tab 3 of front window then beep
  make new tab at (end of front window)
  make new tab at (tab 4 of front window) --this has to be a tab number that doesn't already exist
  open (((path to desktop as string) & "file.txt") as string) --obviously, this has to be a real file. can be alias or string
  email contents of (current tab of front window) --only works with some mail clients
  show bookmarks
  set URL of (make new tab at end of front window) to "topsites://" --you can nest things like using parentheses.
end tell

[crarko adds: I haven't tested this one beyond compiling the script. To dig further into scripting Safari use the AppleScript Editor to open up Safari's Dictionary. The Type Definitions and the Safari Suite are areas to look for Safari-specific data and operations that are scriptable.]
  • Currently 2.25 / 5
  You rated: 2 / 5 (24 votes cast)

Useful script examples for Safari | 2 comments | Create New Account
Click here to return to the 'Useful script examples for Safari' hint
The following comments are owned by whoever posted them. This site is not responsible for what they say.
Correction and Additions
Authored by: Krioni on Aug 06, '10 07:17:43PM
I think you're missing something in the section about getting info about the tabs in the front window. The line:
set tabsInfo to tabsInfo {} as list
doesn't compile properly, and certainly doesn't work, unless you have some strange AppleScript plugin installed. To get information about the open tabs of the front window, you can use the following:

tell application "Safari"
	set tabsList to front window's tabs as list --gets all open tabs
	set tabsInfo to {}
	repeat with currTab in tabsList
		set currName to currTab's name
		set currURL to currTab's URL
		set currNum to currTab's index
		copy {tabName:currName, tabURL:currURL, tabNumber:currNum} to end of tabsInfo
	end repeat
	return tabsInfo	
end tell
Note also that this returns the result, rather than just logging it in the event listing.

Another very useful AppleScript command for Safari is 'do Javascript' - it lets you run Javascript code in Safari for a specific document, allowing you to do many things the Safari doesn't make directly available via AppleScript. For example, you can get the selected text (as noted in some other hints on this site) using the Javascript code: "document.getSelection();"

You can also run Javascript code that gets all the links from a page by looping over the array documents.links. Or, get all the image URLs by looping over document.images.

I think you get the idea. Almost anything you can do via Javascript is possible. You can fill out and submit web forms, modify CSS properties of DIVs to hide them, change colors, and much more.

I had example code, but something strange is making any attempt to copy my code from the Preview and paste into AppleScript Editor result in failure, even though the code is identical to what ran successfully prior to posting. I ran out of time to figure out what is going on - has anyone else ran into the situation where perfectly good code pasted into a comment here, then previewed, then copied, pasted back into Applescript Editor, compiled without fail - fails to run properly? Then, if I make an equivalent-result change to the Javascript code in the string in AppleScript (like adding a single space after the semi-colon in the block of JavaScript code), it runs properly. Then, if I repeat the posting-preview copy attempt, THAT code fails in AppleScript Editor, and removing the "extra space" now allows it to run successfully. It seems that Safari ignores code that ran successfully before. Is there perhaps some strange issue with encoding going on here? Perhaps line returns copying strangely from Safari?

Example: The following ran correctly in AS Editor:

set jsCode to "document.getSelection();"
tell application "Safari"
	set selectedText to (do JavaScript jsCode in current tab of window 1)
	return selectedText
end tell
Then, I previewed it in square-bracket code tags here on I copied the resulting code, pasted into AS Editor, and got an error that "selectedText is not defined" - in other words, the JS code failed to run. So, I added a space AFTER the semi-colon inside the double-quotes for jsCode so that line looked like this:
set jsCode to "document.getSelection(); "
Now it ran properly. So, I took THAT, pasted into square-bracket code tags here, previewed, copied the preview, pasted into AS Editor, and now THAT failed. Removing the extraneous space made it function again.

Basically, it seems like something strange and invisible is added to the string defining the jsCode variable, but modifying the string in AS Editor and recompiling somehow strips back out that problem. Has anyone run across this before? It's making me crazy - I was trying to post some useful code here, stuff that I use all the time, but something made it impossible to copy the result, even though everything looks perfect.


[ Reply to This | # ]
Correction and Additions
Authored by: tedw on Aug 06, '10 08:43:52PM

with respect to copying code from web pages: You have to be a bit careful. Web pages render special characters for a lot of whitespace, and simply copying them straight into an editor that supports rich text (such as the applescript editor) will sometimes produce unexpected results. It shouldn't happen within a code block, but... If you have trouble, copy the code first into a plain text editor (like TextWrangler) and that should normalize all the whitespace.

[ Reply to This | # ]