问题
How do you wait for a webpage to fully load before proceeding the script?
I know you can use delay 4 if you would want it to wait 4 seconds but this is not safe enough.
In VBA you have a simple code that always works and it goes like this:
Dim x As String
x = "https://na6.salesforce.com/p/attach/NoteAttach?pid=" & Range("T34").Value & "&parentname=" & Range("T35").Value & "&retURL=%2F0018000000sKz8K%3Fpb0%3Dtrue"
Set IE = CreateObject("InternetExplorer.Application")
IE.Navigate (x)
IE.Visible = True
SetParent IE.Hwnd, Application.Hwnd
Do
DoEvents
Loop Until IE.READYSTATE = 4
What would be the equivalent of this on mac with safari for applescript?
I´ve seen many versions on the net but only workarounds similar to the delay or for a specify value to return or to count words on the page and so on.
I simply want the above version which is 100% perfect.
Thank you in advance:)
回答1:
You can access the ready state of a page by calling "document.readyState" from either Safari or Chrome.
tell application "Safari"
if not (exists document 1) then reopen
tell current tab of window 1 to set URL to "https://stackoverflow.com/questions/24500011/how-to-wait-for-webpage-to-fully-load-before-proceeding-script"
set the_state to missing value
repeat until the_state is "complete"
set the_state to (do JavaScript "document.readyState" in document 1)
log "busy"
delay 0.2
end repeat
log "complete"
end tell
回答2:
I do it in this way:
tell document 1 of application "Safari"
set URL to ""
set URL to "/slowly loading page/"
repeat until name is not "about:blank"
end repeat
end tell
Or, even easier:
tell front document of application "Safari"
set URL to "/slowly loading page/"
repeat until length of (source as text) is not 0
end repeat
end tell
Furthermore, there’s no need to do it without any delay:
repeat until length of (source as text) is not 0
delay 0.5
end repeat
回答3:
Googled a bit and found this code that works for Safari Version 5.1.10 (6534.59.10) on Snow Leopard.
From http://macscripter.net/viewtopic.php?id=35176
tell application "Safari"
activate
repeat until SafariWindowHasLoaded(1) of me is true
end repeat
beep
end tell
on SafariWindowHasLoaded(inWindowIndex)
tell application "System Events" to ¬
tell application process "Safari"
set theStatusText to name of static text 1 of group 1 of window inWindowIndex as text
if theStatusText begins with "Contacting" or ¬
theStatusText begins with "Loading" or ¬
theStatusText begins with "Waiting" then
set theReturnValue to false
else
set theReturnValue to true
end if
end tell
return theReturnValue
end SafariWindowHasLoaded
Only problem I had was that this script was for an older version of Safari and the Status Bar element was in a different group than mine.
At http://hints.macworld.com/article.php?story=20071015132722688 it was suggested to change it to
static text 1 of group 2
and it worked!
来源:https://stackoverflow.com/questions/24500011/how-to-wait-for-webpage-to-fully-load-before-proceeding-script