Applescript Question; Safari Find field...

Discussion in 'Mac Programming' started by NotSponsored, May 1, 2015.

  1. NotSponsored macrumors newbie

    Joined:
    May 1, 2015
    #1
    G'day.

    1. I've managed to programatically fill the find field (command f) of a Safari page - but I have no clue how to obtain/read the results of it.

    Essentially, I want to search for a string. If result>0 … do this, else.. do nothing.

    I did attempt to use Source of Document but it kept returning 'cannot read source' error

    Any suggestions?

    2. I have a script which loops about every 20 or 30 seconds (using Delay and Return) and sometimes it times out - how can such an error be avoided?

    TIA.
     
  2. Dargoth macrumors regular

    Dargoth

    Joined:
    Oct 27, 2014
    #2
    This works for me:

    Code:
    tell application "System Events"
    	get value of text field 1 of group 2 of group 3 of window 1 of application process "Safari"
    end tell
    The only caveat is that this hierarchy is subject to change on a whim with a software update. I could show you how to walk the UI hierarchy if you don't know how.
     
  3. superscape macrumors 6502a

    superscape

    Joined:
    Feb 12, 2008
    Location:
    East Riding of Yorkshire, UK
    #3
    Personally, I'll use UI scripting as an absolute last resort. It tends to be slow, fiddly and a bit unpredictable in my experience. Still, there are situations where you have no choice.

    In this case, you don't really need to use Safari at all. You could do something like this:

    Code:
    --the url to scan
    set theURL to "http://www.macrumors.com"
    
    --the text to look for
    set theSearchString to "Watch"
    
    
    
    --user curl to get the source code
    set theSourceCode to do shell script ("curl " & theURL)
    
    --find out how many characters into the source code the search string first appears
    set theOffset to offset of theSearchString in theSourceCode
    
    if theOffset > 0 then
    	display alert "Success!" message "The text '" & theSearchString & "' was found in the source code."
    else
    	display alert "Failure!" message "The text '" & theSearchString & "' was not found in the source code."
    	
    end if

    Don't fall into the trap of thinking that scripting is about mimicking user actions (clicks, keypresses etc) in the GUI.

    Hope that's of some help!
     
  4. NotSponsored thread starter macrumors newbie

    Joined:
    May 1, 2015

Share This Page