Access a javascript variable from within AppleScript

The is a easy way to access any variable in  javascript from applescript by using browser’s window title or status. This is very important when you want to retrieve something from web page and parsing result of curl is too complicated. Bellow is an example  to do so with Google Chrome to get web page element with id=’MyDataToGetFromPage’:

set sUrl to "http://www.someserver.com"
tell application "Google Chrome"
   activate
   set oTab to active tab of window 1
   set sResult to ""

   activate oTab
   set oTab's URL to sUrl
   set lDelay to 1
   repeat while oTab is loading and lDelay < 20
      delay 0.1
      set lDelay to lDelay + 1
   end repeat
   tell oTab
      set sMyJava to "if (document.getElementById(\"MyDataToGetFromPage\")) {" & linefeed & "document.title ='Title: ' + document.getElementById(\"MyDataToGetFromPage\").innerHTML;} else {document.title='Can not found data with id :MyDataToGetFromPage';}"
      execute javascript sMyJava
      set sResult to sResult & title of oTab
   end tell
   return sResult
end tell
Advertisements

One Comment on “Access a javascript variable from within AppleScript”

  1. Nico says:

    Useful, too bad the line is cut off but that’s the magic of source code inspection 🙂


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s