AppleScript to save current Safari window in webarchive format

applescriptsafari

Without using GUI scripting, how can I use AppleScript to tell Safari to save the current browser page to a file in webarchive format? The following produces an error "The document “...” could not be exported as “foo.webarchive” (where "…" is the title of the current web page, whatever it may be):

set the_filepath to "/tmp/foo.webarchive"
tell application "Safari"
    activate
    save document 1 in the_filepath
end tell

I've tried variations on this, such as different file name extensions (e.g., .html) to see if anything works, but an error always arises. I've tried different ways of specifying the file name, but that also produces errors (of a different kind). I've tried using save ... as ".webarchive" instead of the simple save above, but that produces a different error about "document 1 doesn't understand the save message".

The AppleScript dictionary for Safari 11 has this description:

save v : Save a document.
  save specifier : The document(s) or window(s) to save.
    [in file] : The file in which to save the document.
    [as saveable file format] : The file format to use.

This implies that it should be possible to save the current web page in a specific format understood by Safari (such as, hopefully, webarchive), and that I simply haven't figured out the right syntax.

Best Answer

I have created a bundled script that saves the current tab to the desktop as a webarchive. Credit to newzealandpaul for his webarchiver shell command that powers this script. You can tweak the code to fit your specific needs, but this should do what that code in your question is trying to do.

Here is the bundled script: SaveWebarchive

This works with the webarchiver command bundled;

set fileName to "foo"

tell application "Safari" to set targetURL to (URL of document 1) as string
set commandPath to POSIX path of (path to resource "webarchiver.command")
do shell script "" & commandPath & " -url " & targetURL & " -output ~/Desktop/" & fileName & ".webarchive"

Note that the downloaded script may have the Script Editor interface showing the Log over the entire window.