20140909

Using AppleScript to block access to distracting websites at night

The goal: block access to timewaster websites at night so that they don't keep you up late.  My Superego program can kill your whole browser at night, but sometimes that's too severe and you just want certain sites to be blocked.

I chose AppleScript as the tool for the job.  I hadn't written AppleScript before, it was almost fun.


set t to (time of (current date))  
if (t < (6 * 60 * 60)) or (t > (22.25 * 60 * 60)) then   -- when it's after 10:15pm or before 6am
tell application "Google Chrome"
repeat with w in windows
repeat with t in tabs of w
repeat with badurl in {"reddit", "ycombinator", "twitch"}
if URL of t contains badurl then
close t
exit repeat
end if
end repeat
end repeat
end repeat
end tell
tell application "Safari"
repeat with w in windows
repeat with t in tabs of w
repeat with badurl in {"reddit", "ycombinator", "twitch"}
if URL of t contains badurl then
close t
exit repeat
end if
end repeat
end repeat
end repeat
end tell
tell application "System Events"
set processList to get the name of every process whose background only is false
if processList contains "Firefox" then
-- display dialog "Firefox is running"
tell application "Firefox"
activate
tell application "System Events"
keystroke "l" using {command down}
keystroke "c" using {command down}
set currenturl to the clipboard
repeat with badurl in {"reddit", "ycombinator", "twitch"}
if currenturl contains badurl then
keystroke "w" using {command down}
end if
end repeat
end tell
end tell
end if
end tell
end if


(The Firefox code is different from the Safari/Chrome code because Firefox doesn't support the same AppleScript interaction.)

Then, I run this script by cron once per minute, using the osascript command.

No comments:

Post a Comment