Get Source of Current Tab in Google Chrome via Applescript Get Source of Current Tab in Google Chrome via Applescript google-chrome google-chrome

Get Source of Current Tab in Google Chrome via Applescript


Since google chrome supports Javascript

--Applescript codetell active tab of window 1    set sourcehtml to execute javascript    document.getElementsByTagName('html')[0].innerHTMLend tell


Chrome's AppleScript library can execute JavaScript.

This will assign the full source of the page to source and return it

tell application "Google Chrome"    set source to execute front window's active tab javascript "document.documentElement.outerHTML"end tell


I'm very excited to learn that Chrome has AppleScript support now. It's unfortunate that it's minimal as yet, but I'm sure (I hope!) it'll get better. Since there's no way to get the source directly, I'd choose the following hackish route:

tell application "Google Chrome"    view source of active tab of window 1 -- Or whichever tab you want    delay 3    repeat while loading of active tab of window 1        delay 3    end repeat    select all of active tab of window 1 -- Must *always* be the active tab    copy selection of active tab of window 1    delete tab (active tab index of window 1) of window 1end telldelay 1return the clipboard

Yes, it's hackish, but that's unavoidable, given the current state of the scripting dictionary. The script should be straightforward: open a source tab, wait for it to load, select the contents, copy it, and close the tab. You can play with the delay 3s to see what works best. Note that the first active tab of window 1 is arbitrary, the rest explicitly refer to the source tab. Also, apparently there's no way to close a tab from within Chrome's scripting dictionary (oy vey), so I had to use JavaScript instead. Also, the last delay 1 shouldn't be necessary, but if it wasn't there, my tests would sometimes return the wrong thing, even though the clipboard contents were correct when I pasted them in. I think it's because there was enough text that it took a noticeable amount of time to update the clipboard.

Edit 1: I replaced execute the active tab of window 1 javascript "window.close()" with the delete tab line, as was suggested to me. Unfortunately, delete tab active tab of window 1 doesn't work, so you need this slightly more convoluted construction.