MacOS – clear Safari cache from script

macossafari

Here is a Python script that clears cookies from Safari (OS X):

from Foundation import *
store = NSHTTPCookieStorage.sharedHTTPCookieStorage()
L = store.cookies()
print len(L)
for c in L:
    store.deleteCookie_(c)
print len(store.cookies())

Is there a similar API to clear Safari's Cache and LocalStorage?

Best Answer

For the cache, you would be looking at NSURLCache and the method(s) removeAllCachedResponses and removeCachedResponseForRequest

For the LocalStorage, there does not appear to be an API for talking directly to Safari LocalStorage except through JS.

I did find this AppleScript however which basically circumvents the API and deletes the SQLite databases directly, obviously replace USERNAME with your username.

tell application "Finder"

select every item of folder "LocalStorage" of folder "Safari" of folder "Library" of folder "USERNAME" of folder "Users" of startup disk
move selection to the trash
end tell

Finally, there's a project on SourceForge called SafariCleaner which does all that you are trying to do in a set of AppleScripts.