Tossel
Tossel

Reputation: 31

Run command line script on load of a web page

I want something like a bash script that sits and listens and then runs a script when I load a specific web page in my browser. I was wondering if something like this is possible, and if so, how do I go about it?

I'm thinking this should be possible somehow. I'm on Mac and in my /etc/hosts file I can specify that specific websites should be blocked, e.g. "www.facebook.com".

So in short. Is (and how) it possible to run a bash script when my computers browser navigates to a webpage, for example "www.facebook.com"?

Upvotes: 0

Views: 875

Answers (2)

Mark Setchell
Mark Setchell

Reputation: 207798

Updated Answer

If you want to do some matching of the name of the site to a pre-defined site, and then say something, your script would look like this:

#!/bin/bash
while :; do
   site=$(osascript -e 'tell application "Safari" to return URL of front document')
   if [[ $site =~ stackoverflow ]]; then
      say "Stack overflow! A quality site"
   fi
   sleep 1
done

Original Answer

You aren't very specific about what browser you are using, what the page is or what you want to do, but this script sits and watches Safari and asks it what page you are looking at and prints it in the terminal. You could obviously modify it to detect certain pages and run a script when you navigate to them.

#!/bin/bash
while :; do
   osascript -e 'tell application "Safari" to return URL of front document'
   sleep 1
done

Put the above in a file called monitorSafari in your HOME directory. Then go into Terminal and type the following once to make it executable:

chmod +x monitorSafari

Then you can run it by either double-clicking it in the Finder, or by typing

./monitorSafari

in your Terminal. It prints the page you are on once every second.

Upvotes: 1

Hamid Rouhani
Hamid Rouhani

Reputation: 2459

You can :

  1. Start a web server (httpd, lighttpd, ...) on your Mac (or use pre-installed httpd)
  2. Add your preferred script to the document root of the web server to run on a specific address (for example on localhost:8080). This script for example can be a PHP script that invokes your bash script or done the job itself. This can be done with cgi although.
  3. Then add your preferred address (www.facebook.com) to your hosts file to redirect URL requests to localhost:8080
  4. Or instead of modifying hosts file, install dnsmasq to manage redirection of custom requests.

Upvotes: 0

Related Questions