the results are nice, (but look the same as if you would open a webarchive in TextEdit)
I don’t use Safari but would love to save/keep some sites for offline reading, using my preferred Browser, Chrome. Saving HTML with all the resources folder creates just clutter!
So, to get a perfect webarchive I have to use Safari or is it possible to script this process without involving Safari in this workflow?
You can do it without any browser. Here’s the code, but there are a couple of catches (see below):
use AppleScript version "2.4" -- Yosemite (10.10) or later
use scripting additions
use framework "Foundation"
use framework "AppKit"
use framework "WebKit"
property thePath : missing value
set thePath to (POSIX path of (path to desktop)) & "Test.webarchive"
my archivePage:"http://www.macosxautomation.com/applescript/apps/" toPath:thePath
on archivePage:thePageURL toPath:aPath
set my thePath to aPath -- store path for use later
my performSelectorOnMainThread:"setUpWebViewForPage:" withObject:thePageURL waitUntilDone:false
end archivePage:toPath:
on setUpWebViewForPage:thePageURL
-- needs to be done on the main thread
-- make a WebView
set theView to current application's WebView's alloc()'s initWithFrame:{origin:{x:0, y:0}, |size|:{width:100, height:100}}
-- tell it to call delegate methods on me
theView's setFrameLoadDelegate:me
-- load the page
theView's setMainFrameURL:thePageURL
end setUpWebViewForPage:
-- called when the WebView loads a frame
on WebView:aWebView didFinishLoadForFrame:webFrame
-- the main frame is our interest
if webFrame = aWebView's mainFrame() then
-- get the data and write it to file
set theArchiveData to webFrame's dataSource()'s webArchive()'s |data|()
theArchiveData's writeToFile:thePath atomically:true
display dialog "The webarchive was saved" buttons {"OK"} default button 1
end if
end WebView:didFinishLoadForFrame:
on WebView:WebView didFailLoadWithError:theError forFrame:webFrame
-- got an error, bail
WebView's stopLoading:me
display dialog "The webarchive was not saved" buttons {"OK"} default button 1
end WebView:didFailLoadWithError:forFrame:
It needs to be run either from Script Editor, or as a stay-open applet (in which case you can add code to quit after the dialogs). The stay-open issue means it won’t run in Script Debugger as yet.