You need to save the script as a script bundle in ~/Library/Script Libraries/, and call it something like Make webarchive.scptd. If you're using AppleScript Editor, you then need to click the Bundle Contents button at the top of the window, click the AppleScript/Objective C Library checkbox, and save again. If you're using Script Debugger, you need version 5.0.7, and you make the initial file by choosing New Script from Template and clicking the button there. So...
use framework "Foundation"
use framework "WebKit"
property theSender : missing value
property thePath : missing value
property theSearchString : missing value
on archivePage:thePageURL toPath:aPath ifItContains:searchString sender:sender
set my theSender to sender -- store main script so we can call back
set my thePath to aPath -- store path for use later
set my theSearchString to searchString -- store for use later
-- 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 call delegate methods on me
theView's setFrameLoadDelegate:me
-- load the page
theView's setMainFrameURL:thePageURL
end archivePage:toPath:ifItContains:sender:
-- called when our WebView loads a frame
on WebView:aWebView didFinishLoadForFrame:webFrame
-- the main frame is our interest
if webFrame = aWebView's mainFrame() then
-- get the text of the page
set theText to (webFrame's DOMDocument()'s documentElement()'s outerText())
-- search it
if (theText's rangeOfString:theSearchString)'s |length|() > 0 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
-- tell our script it's all done
theSender's jobDone:"The webarchive was saved"
else
theSender's jobDone:"Seach string not found"
end if
end if
end WebView:didFinishLoadForFrame:
-- called when there's a problem
on WebView:WebView didFailLoadWithError:theError forFrame:webFrame
-- got an error, bail
WebView's stopLoading:me
theSender's jobDone:"The webarchive was not saved"
end WebView:didFailLoadWithError:forFrame:
To use the library, you need a script like this:
use theLib : script "Make webarchive"
use scripting additions
set thePath to (POSIX path of (path to desktop)) & "Test.webarchive"
-- called when the job's done
on jobDone:theMessage
display notification theMessage sound name "Ping"
end jobDone:
And when you save it as an applet, you need to make it stay-open. You can't run the script above directly from AppleScript Editor because it runs scripts in the background -- you get: