Skip to content

Instantly share code, notes, and snippets.

@henrik
Created September 1, 2012 18:56
Show Gist options
  • Save henrik/3583291 to your computer and use it in GitHub Desktop.
Save henrik/3583291 to your computer and use it in GitHub Desktop.
Run some JS in Chrome from the command line and get the return value. Useful for scrapers that require JS and perhaps a session that's tricky to set up otherwise.

This AppleScript opens a page in Chrome (where you presumably have a logged-in session if required), opens the passed-in URL, runs the passed-in JavaScript and returns the JS return value.

Waits for 1 second for the page to load before executing the JS. Optionally, pass in a third argument with the number of seconds to wait.

Examples:

osascript js_in_chrome.scpt "http://google.com" "document.title"

# When logged in.
osascript js_in_chrome.scpt "http://search.ancestry.com/Browse/view.aspx?dbid=1670&path=1930.Spring.160V.1" "szImageURL"

# Custom wait.
osascript js_in_chrome.scpt "http://google.com" "document.title" 10
on run argv
set theURL to item 1 of argv
set theJS to item 2 of argv
if length of argv > 2 then
set theDelay to item 3 of argv
else
set theDelay to 1
end if
tell application "Google Chrome"
tell window 1 to make new tab with properties {URL:theURL}
delay theDelay -- Wait for page to load.
set theResult to execute window 1's active tab javascript theJS
delete tab (active tab index of window 1) of window 1
if theResult is not missing value then
theResult
end if
end tell
end run
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment