G33kDude / Chrome.ahk

Automate Google Chrome using native AutoHotkey
https://autohotkey.com/boards/viewtopic.php?t=42890
MIT License
336 stars 82 forks source link

WaitForLoad not waiting on pages opened directly on chromeinstance #41

Open cycle4passion opened 8 months ago

cycle4passion commented 8 months ago

I think I have found a bug in Chrome.ahk. When instantiating Chrome with url included, WaitForLoad() Method does not work. Using the code example from the 1st page, things work as expected.

#Include Chrome.ahk

; Create an instance of the Chrome class using
; the folder ChromeProfile to store the user profile
FileCreateDir, ChromeProfile
ChromeInst := new Chrome("ChromeProfile")

; Connect to the newly opened tab and navigate to another website
; Note: If your first action is to navigate away, it may be just as
; effective to provide the target URL when instantiating the Chrome class
PageInstance := ChromeInst.GetPage()
PageInstance.Call("Page.navigate", {"url": "https://autohotkey.com/"})
PageInstance.WaitForLoad()

; Execute some JavaScript
PageInstance.Evaluate("alert('Hello World!');")

; Close the browser (note: this closes *all* pages/tabs)
PageInstance.Call("Browser.close")
PageInstance.Disconnect()

ExitApp
return

Now lets change it as suggested in the comment "...it may be just as effective to provide the target URL when instantiating the Chrome class"

#Include Chrome.ahk
FileCreateDir, ChromeProfile
ChromeInst := new Chrome("ChromeProfile", "https://autohotkey.com/") ; this line changed
PageInstance := ChromeInst.GetPage()
; PageInstance.Call("Page.navigate", {"url": "https://autohotkey.com/"}) ; this line removed
PageInstance.WaitForLoad()
PageInstance.Evaluate("alert('Hello World!');")
PageInstance.Call("Browser.close")
PageInstance.Disconnect()

ExitApp
return

The alert fires before the page is fully loaded and causes a subsequent error. Here is a workaround.

#Include Chrome.ahk
url := "https://autohotkey.com/"
ChromeInst := new Chrome("ChromeProfile", url) ; new instance
PageInstance := ChromeInst.GetPage()
PageInstance.Call("Page.navigate", {"url": url}) ; must renavigate to make WaitForLoad() work
PageInstance.WaitForLoad()
PageInstance.Evaluate("alert('Hello World!');")
PageInstance.Call("Browser.close")
PageInstance.Disconnect()
ExitApp
return