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

How to get JSON Response From The Web? #20

Closed KiddoV closed 3 years ago

KiddoV commented 3 years ago
;Some javascript
js =
(
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

xhr.addEventListener("readystatechange", function() {
  if(this.readyState === 4) {
    alert(this.responseText);
    return this.responseText;
  }
});
xhr.open("POST", "https://192.168.2.1/api/commissioning");
xhr.send();
)

; Execute some JavaScript
PageInstance.Evaluate(js)

My question is how do you get the this.responseText (as a JSON format) and parse it to ahk variable? Thanks,

KiddoV commented 3 years ago

According to the example you provided. I think get message from the console will be the only option. I guess we can do something like this:

; --- Create a new Chrome instance ---
FileCreateDir, ChromeProfile
ChromeInst := new Chrome("ChromeProfile")

;Some javascript
js =
(
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

xhr.addEventListener("readystatechange", function() {
  if(this.readyState === 4) {
    console.log("AHK: " + this.responseText);
  }
});
xhr.open("POST", "https://192.168.2.1/api/commissioning");
xhr.send();
)

BoundCallback := Func("Callback").Bind()
PageInst := ChromeInst.GetPage(1, "page", BoundCallback)
PageInst.WaitForLoad()
PageInst.Call("Console.enable")
;; PageInst.Call("Page.navigate", {"url": "<your endpoint>"})

; Execute some JavaScript
PageInstance.Evaluate(js)

CallBack(Event) {
    if (Event.Method == "Console.messageAdded" && InStr(Event.params.message.text, "AHK:") == 1)
    {
        ; Strip out the leading AHK:
        responseJSON:= SubStr(Event.params.message.text, 5)

        MsgBox, %responseJSON%
        Return
    }
}