Within EACH function that you want to Call/Evaluate against the page, you MUST reconnect to the page (NO GLOBALS!!!!), then, you must DISCONNECT from the page to prevent death.
Also, in chrome.ahk I found it helps sometimes to change "awaitPromise":Chrome.Jxon_false() to "awaitPromise":Chrome.Jxon_True()
Code: Select all
Evaluate(JS)
{
response := this.Call("Runtime.evaluate",
( LTrim Join
{
"expression": JS,
"objectGroup": "console",
"includeCommandLineAPI": Chrome.Jxon_True(),
"silent": Chrome.Jxon_False(),
"returnByValue": Chrome.Jxon_False(),
"userGesture": Chrome.Jxon_True(),
"awaitPromise": Chrome.Jxon_True() ;Change this to Chrome.Jxon_True() instead of Chrome.Jxon_False()
}
))
if (response.exceptionDetails)
throw Exception(response.result.description,, Chrome.Jxon_Dump(response.exceptionDetails))
return response.result
}
Code: Select all
#Persistent
#include %A_ScriptDir%\Lib\Chrome.ahk
FileCreateDir, ChromeProfile
ChromeInst := new Chrome("ChromeProfile", "http://localhost/test.html") ;create the class
sleep, 3000 ;Since we're not running headless, give the UI a chance to draw
pageInst:= ChromeInst.GetPageByURL("http://localhost/test.html",,,"event_callBack") ;Don't Disconnect this one!
pageInst.WaitForLoad()
pageInst.Call("Console.enable")
ESC::
ExitApp
return ;END AUTOEXECUTE
event_callBack(Event)
{
if (Event.Method == "Console.messageAdded" && InStr(Event.params.message.text,"AHK:") >=1)
{
Text := Event.params.message.text
Split := StrSplit(Text, ",","AHK:")
fnName := Split[1]
%fnName%() ;Allows you to call a func dynamically from JS like this console.log("AHK:myFirstFunction").
} else if(Event.Method == "Inspector.detached") {
;You can do stuff here when the user closes the browser.
}
}
getState() {
pageInst:=reconnectToPage()
readyState:= pageInst.Evaluate("document.readyState").value
pageInst.Disconnect() ;You MUST disconnect after each reconnectToPage(). Otherwise you will end up creating several class instances. Too many instances will cause death :https://www.autohotkey.com/boards/viewtopic.php?f=6&t=42890&hilit=chrome.ahk&start=100 (look at bmilcs post)
trayTip,document.readyState, % "is " . readyState
;reloadPage()
}
reloadPage() {
;an example of how to handle a call as opposed to an evaluate
pageInst:=reconnectToPage
pageInst.Call("Page.reload")
pageInst.WaitForLoad()
pageInst.Disconnect()
}
reconnectToPage() {
pageInst:=Chrome.getPage(,,,,"event_callBack") ;call our Chrome class and get a reference back from our first page. You could also use getPageByURL. Make sure to pass the callback func again!
return pageInst
}
Code: Select all
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<button onclick="console.log('AHK:getState')" id="TEST">Get document.readyState</button>
<button onclick="console.log('AHK:reloadPage')" id="TEST">Reload the Page</button>
</body>
</html>