Reliable “Wait for Safari to Load a Page” Strategies?

I've just started trying to write my first script which interacts with Safari, and have been looking through the Safari dictionary for something I can test to determine if a page has finished loading. I have a lot of trouble with app dictionaries, so I hope this isn't too trivial.

Let's say I have a Safari browser window open with id winID, and a tab in it with index tabIndex. I want to load a web page and get the source HTML. This seems to work (most of the time):

tell application "Safari" to tell window id winID to tell tab tabIndex
set URL to someURL
delay 30
set someHTML to source
end tell

Two problems: (1) most of the time it's unnecessarily dismally slow, and (2) it's still dangerous, if the server is really backed up it can still fail, and I may find my script reading the previous page, or possibly a partial page. It would be nice if tabs or windows had some sort of "busy" property I could test in a delay loop, but if they do I'm missing it in the dictionary. Any ideas for replacing my "delay 30" statement with something better?

Dual 1.2 GHz, Mac OS X (10.5.5)

Posted on Nov 29, 2008 1:15 PM

Reply
3 replies

Nov 30, 2008 10:37 AM in response to Jeff Johnson 1

Here's an example of the Javascript approach:

--your set URL
delay 3 -- this is a delay to allow the page to start loading
--wait till it's loaded
set pageLoaded to false -- this initialises the pageLoaded variable that gets set below
repeat while not pageLoaded -- keep doing this loop until loading complete
if (do JavaScript "document.readyState" in document 1) is "complete" then
set pageLoaded to true
else
delay 3 -- you can try adjusting this delay
end if
end repeat
--your set someHTML ...

Nov 30, 2008 2:45 PM in response to Arkouda

Thanks to you both. That old Apple page was surprisingly helpful on a number of questions. For example, I didn't know I could use Do JavaScript to extract links from a page. I had another way of doing this, but it was comparatively clumsy. On the question I asked, I was up most of last night experimenting, and the JavaScript method works well. There is still a slight problem with one site I use where the login page instantly loads another, which loads yet another before finally loading the home page (and why site designers make things so difficult I don't know), but an initial delay of 3-4 seconds seems to take care of it, and I think I have a handle on things now. Thanks again.

This thread has been closed by the system or the community team. You may vote for any posts you find helpful, or search the Community for additional answers.

Reliable “Wait for Safari to Load a Page” Strategies?

Welcome to Apple Support Community
A forum where Apple customers help each other with their products. Get started with your Apple Account.