MacOS – AppleScript in OS X 10.10 to Resize Safari window and take Screen Shot of that window and repeat with multiple sizes

applescriptmacossafariscreen capture

I would like to build an AppleScript Application that when run will do the following:

  1. Open up Safari and navigate to a specific URL, or a line delimited file, or CSV. This is not required but would make generating multiple screenshots of different pages a lot quicker.

  2. Resize the Safari window to one of a number of sizes

  3. Take a screenshot of the Safari window with the filename being the url along with the screen size

Best Answer

I only got a partial solution, which works apart from a few small issues.

First of all, you can not store the URL in the filename (due to slashes and special characters) so you'd need to specify the Website name.

But more importantly, so far the CSV import is not implemented. Is CSV really a hard requirement, or could you get the list of URLs in a different format? If not, please update your question with exemplary lines of your CSV file. I'll work on it and update my answer as soon as possible.

on open_url(theUrl, theUrlName, x0, y0, xSize, ySize)
    tell application "Safari"
        open location theUrl
        activate

        set bounds of window 1 to {x0, y0, xSize, ySize}
        set windowID to id of window 1
        set the_state to missing value

        repeat until the_state is "complete"
            set the_state to (do JavaScript "document.readyState" in document 1)
            delay 0.3
        end repeat

        set theFolder to POSIX path of (path to desktop as string)
        set shellCommand to "/usr/sbin/screencapture -l " & windowID & " " & quoted form of (theFolder & "Screen Shot " & theUrlName & " " & xSize & "x" & ySize & ".png")
        do shell script shellCommand

    end tell
end open_url


set resolutionList to {{640, 480}, {1024, 768}}
set siteList to {{"http://www.apple.com", "Apple"}, {"http://www.google.com", "Google"}}

repeat with resolution in resolutionList
    set xSize to item 1 of resolution
    set ySize to item 2 of resolution
    repeat with theSite in siteList
        set theUrl to item 1 of theSite
        set theUrlName to item 2 of theSite
        open_url(theUrl, theUrlName, 0, 0, xSize, ySize)
    end repeat
end repeat