'Automate clear browsing data Safari

Is there any way to automate clearing cache, cookies and history in Safari? I can run Swift, Python, JavaScript and AppleScript.

This is the AppleScript I have right now, but it is slow, interruptible and basically activates user interface buttons. What I want is something that works in the background and still gets the job done.

--Clear history (also clears cache and cookies)
tell application "System Events" to keystroke "t" using {command down}
tell application "System Events"
    click menu item "Clear History…" of menu 1 of menu bar item "History" of menu bar 1 of process "Safari"
    try
        click button "Clear History" of sheet 1 of window 1 of process "Safari"
    end try
end tell
tell application "System Events" to keystroke "w" using {command down}


Solution 1:[1]

I found the files where the browsing data is saved. These scripts delete the files with the same effect as clearing Safari history manually. Also clears cache and cookies for all applications in /User/Library.

AppleScript

--  Get path of files to delete and folders to empty
set base to "Macintosh HD:Users:User:Library:"
set docs to {"Safari:History.db", "Safari:History.db-lock", "Safari:History.db-shm", "Safari:History.db-wal", "Safari:CloudTabs.db", "Safari:CloudTabs.db-shm", "Safari:CloudTabs.db-wal", "Safari:PerSitePreferences.db", "Safari:PerSitePreferences.db-shm", "Safari:PerSitePreferences.db-wal", "Safari:Downloads.plist", "Safari:RecentlyClosedTabs.plist", "Safari:SearchDescriptions.plist"}
set docs1 to {"Safari:LocalStorage", "Safari:Favicon Cache", "Safari:Touch Icons Cache", "Caches:com.apple.Safari", "Caches", "Cookies"}
--  Delete history files
tell application "Finder"
    repeat with i from 1 to length of docs
        set doc to item i of docs
        set doc to base & doc
        try
            delete file doc
        end try
    end repeat
end tell

--  Empty cache folders
tell application "Finder"
    repeat with i from 1 to length of docs1
        set doc to item i of docs1
        set doc to base & doc
        try
            delete (every item of folder doc)
        end try
    end repeat
end tell

Python 3.10

import os
import shutil

# Declare file & folder directories
library = "/Users/User/Library"
files = [
    "/Safari/History.db",
    "/Safari/History.db-lock",
    "/Safari/History.db-shm",
    "/Safari/History.db-wal",
    "/Safari/CloudTabs.db",
    "/Safari/CloudTabs.db-shm",
    "/Safari/CloudTabs.db-wal",
    "/Safari/PerSitePreferences.db",
    "/Safari/PerSitePreferences.db-shm",
    "/Safari/PerSitePreferences.db-wal",
    "/Safari/Downloads.plist",
    "/Safari/RecentlyClosedTabs.plist",
    "/Safari/SearchDescriptions.plist",
    "/Containers/com.apple.Safari/Data/Library/Safari/SafariTabs.db",
    "/Containers/com.apple.Safari/Data/Library/Safari/SafariTabs.db-shm",
    "/Containers/com.apple.Safari/Data/Library/Safari/SafariTabs.db-wal"
]
folders = [
    "/Safari/Databases",
    "/Safari/LocalStorage",
    "/Safari/Favicon Cache",
    "/Safari/Template Icons",
    "/Safari/Touch Icons Cache",
    "/Containers/com.apple.Safari/Data/Library/Caches",
    "/Containers/com.apple.Safari/Data/Library/Saved Application State"
]
sensitive = [
    "/Caches",
    "/Cookies",
]

# Delete Safari history files
for file in files:
    if os.path.exists(library + file):
        os.remove(library + file)
for folder in folders:
    if os.path.exists(library + folder):
        shutil.rmtree(library + folder)

# Delete caches and cookies
for folder in sensitive:
    for file in os.listdir(library + folder):
        os.system("rm -r " + library + folder + "/" + file)

Python 3.10 multiprocessing

import os
import shutil
import multiprocessing

#MARK: - Declare file & folder directories
library = "/Users/User/Library"
files = (
    "/Safari/History.db",
    "/Safari/History.db-lock",
    "/Safari/History.db-shm",
    "/Safari/History.db-wal",
    "/Safari/CloudTabs.db",
    "/Safari/CloudTabs.db-shm",
    "/Safari/CloudTabs.db-wal",
    "/Safari/PerSitePreferences.db"
    "/Safari/PerSitePreferences.db-shm",
    "/Safari/PerSitePreferences.db-wal",
    "/Safari/Downloads.plist",
    "/Safari/RecentlyClosedTabs.plist",
    "/Safari/SearchDescriptions.plist",
    "/Containers/com.apple.Safari/Data/Library/Safari/SafariTabs.db",
    "/Containers/com.apple.Safari/Data/Library/Safari/SafariTabs.db-shm",
    "/Containers/com.apple.Safari/Data/Library/Safari/SafariTabs.db-wal"
)
folders = (
    ("/Safari/Databases",
    "/Safari/LocalStorage",
    "/Safari/Favicon Cache",
     "/Safari/Template Icons"),
    ("/Safari/Touch Icons Cache",
    "/Containers/com.apple.Safari/Data/tmp",
     "/Containers/com.apple.Safari/Data/CloudKit",
     "/Containers/com.apple.Safari/Data/Library/Caches"),
    ("/Containers/com.apple.Safari/Data/Library/Logs",
    "/Containers/com.apple.Safari/Data/Library/HTTPStorages",
    "/Containers/com.apple.Safari/Data/Library/WebKit/MediaKeys",
    "/Containers/com.apple.Safari/Data/Library/WebKit/WebsiteData",
    "/Containers/com.apple.Safari/Data/Library/Saved Application State")
)
sensitive_folders = (
    "/Caches",
    "/Cookies"
)

#MARK - Delete Safari history files as well as caches and cookies
#  Optimized for 3 GHz 6-Core Intel Core i5 CPU

def delete_files():
    #  Delete Safari history files
    for file in files:
        if os.path.exists(library + file): os.remove(library + file)
def delete_folders(segment):
    #  Delete folders in segment and all files inside folders
    for folder in folders[segment]:
        if os.path.exists(library + folder): shutil.rmtree(library + folder)
def delete_sensitive_folders():
    #  Delete caches and cookies folders and contents located in /User/Library folder
    for folder in sensitive_folders:
        if os.path.exists(library + folder): shutil.rmtree(library + folder)

if __name__ == "__main__":
    #  Create and start process to delete Safari history files
    file_delete_process = multiprocessing.Process(target = delete_files)
    file_delete_process.start()

    #  Create and start process to delete caches and cookies
    sensitive_folders_delete_process = multiprocessing.Process(target = delete_sensitive_folders)
    sensitive_folders_delete_process.start()

    #  Create and start processes to delete folders
    for i in range(0, 3):
        folder_delete_process = multiprocessing.Process(target = delete_folders, args = (i,))
        folder_delete_process.start()

C++ 20

#include <string>
#include <iostream>
#include <filesystem>

using namespace std;
namespace fs = filesystem;

int main() {
    const string library = "/Users/User/Library";
    const string files[16] = {
        "/Safari/History.db",
        "/Safari/History.db-lock",
        "/Safari/History.db-shm",
        "/Safari/History.db-wal",
        "/Safari/CloudTabs.db",
        "/Safari/CloudTabs.db-shm",
        "/Safari/CloudTabs.db-wal",
        "/Safari/PerSitePreferences.db",
        "/Safari/PerSitePreferences.db-shm",
        "/Safari/PerSitePreferences.db-wal",
        "/Safari/Downloads.plist",
        "/Safari/RecentlyClosedTabs.plist",
        "/Safari/SearchDescriptions.plist",
        "/Containers/com.apple.Safari/Data/Library/Safari/SafariTabs.db",
        "/Containers/com.apple.Safari/Data/Library/Safari/SafariTabs.db-shm",
        "/Containers/com.apple.Safari/Data/Library/Safari/SafariTabs.db-wal"
    };
    const string folders[13] = {
        "/Safari/Databases",
        "/Safari/LocalStorage",
        "/Safari/Favicon Cache",
        "/Safari/Template Icons",
        "/Safari/Touch Icons Cache",
        "/Containers/com.apple.Safari/Data/tmp",
        "/Containers/com.apple.Safari/Data/CloudKit",
        "/Containers/com.apple.Safari/Data/Library/Caches",
        "/Containers/com.apple.Safari/Data/Library/Logs",
        "/Containers/com.apple.Safari/Data/Library/HTTPStorages",
        "/Containers/com.apple.Safari/Data/Library/WebKit/MediaKeys",
        "/Containers/com.apple.Safari/Data/Library/WebKit/WebsiteData",
        "/Containers/com.apple.Safari/Data/Library/Saved Application State"
    };
    const string sensitiveFolders[2] = {
        "/Caches",
        "/Cookies"
    };
    
    for(const string &i: files) { fs::remove_all(library + i);};
    for(const string &i: folders) { fs::remove_all(library + i);};
    for(const string &i: sensitiveFolders) { fs::remove_all(library + i);};
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1