-- thanks https://macosxautomation.com/applescript/sbrt/sbrt-09.html!
on write_to_file(this_data, target_file, append_data)
try
set the target_file to the target_file as string
set the open_target_file to open for access file target_file with write permission
if append_data is false then set eof of the open_target_file to 0
write this_data to the open_target_file starting at eof
close access the open_target_file
return true
on error
try
close access file target_file
end try
return false
end try
end write_to_file
tell application "Finder"
if exists (((path to home folder) as string) & "Safari Tab Dumps") then
set dump_folder to (((path to home folder) as string) & "Safari Tab Dumps")
else
set dump_folder to make new folder at home ¬
with properties {name:"Safari Tab Dumps"}
end if
end tell
tell application "Safari"
-- use a more readable date inside the Markdown file.
set d to short date string of (current date)
set t to time string of (current date)
set fullDate to d & space & t
(* Since we can't use ":" in macOS filenames...
This will use ISO 8601 “basic” format strings (YYYYMMDDTHHMMSSZ) in the file name. *)
set y to the year of (current date)
set m to the month of (current date)
set d to the day of (current date)
set h to the hours of (current date)
set m to the minutes of (current date)
set s to the seconds of (current date)
set timestamp to y & m & d & "T" & h & m & s as string
set windowCount to the number of windows
set genMarkdown to ""
repeat with currentWindow from 1 to windowCount
set tabCount to number of every tab in the window currentWindow
repeat with currentTab from 1 to tabCount
set tabName to the name of tab currentTab of window currentWindow
set tabURL to the URL of tab currentTab of window currentWindow
set genMarkdown to genMarkdown & "[" & tabName & "]" & "(" & tabURL & ")" & linefeed as string
end repeat
end repeat
-- generate an HTML template with tabName and tabURL
set markdownData to ¬
"# " & tabCount & " tabs dumped on " & fullDate & "
" & genMarkdown
end tell
tell application "Finder"
set current_file to make new file at dump_folder with properties {name:timestamp & ".markdown"}
my write_to_file(markdownData, current_file, false)
end tell
-- finally clean up
tell application "Safari"
quit -- was close windows
delay 2
activate
end tell