[Library] Chrome.ahk - Automate Google Chrome using native AutoHotkey. No IE!

Post your working scripts, libraries and tools for AHK v1.1 and older
fatodubs
Posts: 29
Joined: 20 Sep 2017, 18:53

Re: [Library] Chrome.ahk - Automate Google Chrome using native AutoHotkey. No Selenium!

19 Oct 2020, 10:07

@gregster Thank you for replying, and hopefully it is helpful for others.

Yeah, my issue appears to be more fundamental. I am able to launch the debug session with my url Array and all the pages open, but the first attempt to GetPage (by any means) results in the scripting error at line 387:

Code: Select all

this.document.body.appendChild(Script)
When I choose to continue scripts on that error, it just goes into an endless loop on lines 204 and 205:

Code: Select all

while !this.Connected
	Sleep, 50
Is there any other way to connect? @GeekDude, any chance you have a beta of 2.0 you want some testing on? :lol:
geek
Posts: 1052
Joined: 02 Oct 2013, 22:13
Location: GeekDude
Contact:

Re: [Library] Chrome.ahk - Automate Google Chrome using native AutoHotkey. No Selenium!

20 Oct 2020, 12:07

fatodubs wrote:
19 Oct 2020, 10:07
Is there any other way to connect? @GeekDude, any chance you have a beta of 2.0 you want some testing on? :lol:
To be honest, I have no idea what's causing the issue you've expressed here. That said, I do have plans for a v2 but have not yet written any code. Those plans exist solely between my ears, currently.
tpitera
Posts: 31
Joined: 27 Oct 2020, 15:56

Re: [Library] Chrome.ahk - Automate Google Chrome using native AutoHotkey. No Selenium!

02 Nov 2020, 11:22

having difficulty with this Chrome.ahk, i am trying to converse between javascript and ahk, i dont see that anywhere in documentation. the script below i put in my own number, i cant seem to save the variable from the function back into ahk properly. Any input you guys could provide would be helpful

Code: Select all

#NoEnv
SetBatchLines, -1

#Include C:\Users\Thomas Pitera\Downloads\Chrome.ahk-master\Chrome.ahk


; --- Create a new Chrome instance ---

; Instead of providing a URL here, let's try
; navigating later for demonstration purposes
FileCreateDir, ChromeProfile
ChromeInst := new Chrome("ChromeProfile")


; --- Connect to the page ---

if !(PageInst := ChromeInst.GetPage())
{
	MsgBox, Could not retrieve page!
	ChromeInst.Kill()
}
else
{
	; --- Navigate to the desired URL ---
	
	PageInst.Call("Page.navigate", {"url": "https www.latlong.net /lat-long-utm.html"})  Broken Link for safety
	PageInst.WaitForLoad()
	
	; Find the root node
	RootNode := PageInst.Call("DOM.getDocument").root
	lat = 12
	; Find and change the name element
	;NameNode := PageInst.Call("DOM.querySelector", {"nodeId": RootNode.nodeId, "selector": "input[name=name]"})
	;PageInst.Call("DOM.setAttributeValue", {"nodeId": NameNode.NodeId, "name": "value", "value": "ChromeBot"})
	;attempt doesnt work
	;LatNode := PageInst.Call("DOM.querySelector", {"nodeId": RootNode.nodeId, "selector": "input[name=lat]"})
	;PageInst.Call("DOM.setAttributeValue", {"nodeId": LatNode.NodeId, "name": "value", "value": "11"})
	PageInst.Evaluate("document.getElementById('lat').click()")
	PageInst.Evaluate("document.getElementById('lat').value = 11")  ;works
	;PageInst.Evaluate("document.getElementById('lat').value = %lat%") ;doesnt work
	;LongNode := PageInst.Call("DOM.querySelector", {"nodeId": RootNode.nodeId, "selector": "input[id=lng]"})
	;PageInst.Call("DOM.setAttributeValue", {"nodeId": LongNode.NodeId, "name": "lng", "value": "22"})
	PageInst.Evaluate("document.getElementById('lng').value = 22")  ;works
	; I would like to do  PageInst.Evaluate("document.getElementById('lng').value = %lat%") variable brought in from previous step
	PageInst.Evaluate("document.getElementsByTagName('button')[0].click()")  ;click button
	Easting = PageInst.Evaluate("document.getElementById('utm-easting').value")
	MsgBox, 4, , Easting = %Easting%`nContinue?
	IfMsgBox, No
    		return
	MsgBox, Program Ended
}		
;PageInst.Evaluate("document.getElementsByTagName('button')[0].click()")
; Put value of dom into Easting variable
;Easting = []
;EastNode := PageInst.Call("DOM.querySelector", {"nodeId": RootNode.nodeId, "selector": "input[name=utm-easting]"})
;Easting := PageInst.Call("DOM.describeNode", {"nodeId": EastNode.nodeId})
				;Easting := PageInstance.Evaluate("document.getElementById("utm-easting").value")
				;Northing := PageInst.Evaluate("document.getElementById("utm-northing").value")
;MsgBox, 4, , Easting = %Easting%`nContinue?
;IfMsgBox, No
    ;return

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

ExitApp
return
burque505
Posts: 1731
Joined: 22 Jan 2017, 19:37

Re: [Library] Chrome.ahk - Automate Google Chrome using native AutoHotkey. No Selenium!

02 Nov 2020, 13:40

@tpitera, maybe this will give you some ideas. I use continuation sections for JS because it's easier for me. Note the seeming redundancy of .value followed by .value for the "Easting" value return - it has to be done this way, apparently.

Code: Select all

#NoEnv
SetBatchLines, -1
SetTitleMatchMode, 2

#Include Chrome.ahk

ChromeInst := new Chrome("ChromeProfile")
lat := 11
lng := 22
jslat =
(
document.getElementById('lat').value = %lat%
)

jslng =
(
document.getElementById('lng').value = %lng%
)

if !(PageInst := ChromeInst.GetPage())
{
	MsgBox, Could not retrieve page!
	ChromeInst.Kill()
}
else
{
	;sleep, 5000
	; --- Navigate to the desired URL ---
	PageInst.WaitForLoad()
	PageInst.Call("Page.navigate", {"url": "https://www.latlong.net/lat-long-utm.html"})  
	PageInst.WaitForLoad()
	
	; Find the root node
	RootNode := PageInst.Call("DOM.getDocument").root

	PageInst.Evaluate("document.getElementById('lat').click()")
	PageInst.Evaluate(jslat) ;works
	;PageInst.Evaluate("document.getElementById('lng').value = 22")  ;works
	sleep, 100
	PageInst.Evaluate(jslng) ;works
	PageInst.Evaluate("document.getElementsByTagName('button')[0].click()")  ;click button
	sleep, 1000
	Easting := PageInst.Evaluate("document.getElementById('utm-easting').value;").value
	MsgBox, 4, , Easting = %Easting%`nContinue?
	IfMsgBox, No
    		return
	MsgBox, Program Ended
}		

PageInstance.Call("Browser.close")
PageInstance.Disconnect()
WinKill, ahk_exe Chrome.exe

ExitApp
return
Regards,
burque505
gregster
Posts: 8916
Joined: 30 Sep 2013, 06:48

Re: [Library] Chrome.ahk - Automate Google Chrome using native AutoHotkey. No Selenium!

02 Nov 2020, 13:51

it has to be done this way, apparently
Yeah, one .value belongs to the (by javascript) selected DOM element, the other to the object returned by the Evaluate() method of the chrome debugging protocol (used by Chrome.ahk). Unfortunate naming...
anaglypta
Posts: 17
Joined: 10 Nov 2020, 10:18

Re: [Library] Chrome.ahk - Automate Google Chrome using native AutoHotkey. No Selenium!

10 Nov 2020, 13:09

@GeekDude:
I believe there is a minor bug in the file Chrome.ahk:

Code: Select all

; before:
val := %value% + 0
; after:
val := %val% + 0

Btw this thread is getting pretty big, is it going to have its own subforum, like the documentation thread?
I want to make a few more unconnected points, but it might be neater to start new threads.

Thanks for Chrome.ahk!
gregster
Posts: 8916
Joined: 30 Sep 2013, 06:48

Re: [Library] Chrome.ahk - Automate Google Chrome using native AutoHotkey. No Selenium!

10 Nov 2020, 13:13

anaglypta wrote:
10 Nov 2020, 13:09
@GeekDude:
I believe there is a minor bug in the file Chrome.ahk:

Code: Select all

; before:
val := %value% + 0
; after:
val := %val% + 0
Not GeekDude here, but yes, that's a bug and this has been mentioned before.
Actually this is a bug from Coco's original json functions which were included in the last release 1.2 of Chrome.ahk years ago (but I think Coco still hasn't fixed it on githbub, although there are pull requests). I assume that GeekDude will fix that in the next release (whenever this will be), if he doesn't replace these functions completely.
burque505
Posts: 1731
Joined: 22 Jan 2017, 19:37

Re: [Library] Chrome.ahk - Automate Google Chrome using native AutoHotkey. No Selenium!

10 Nov 2020, 13:24

I think it was in JXON.ahk. See this thread. The copy I have mentions the above error.
Regards,
gregster wrote:
02 Aug 2020, 04:23
Newer2AHK wrote:
01 Aug 2020, 23:12
This code is in the method Jxon_Load(), and the variable "value" does not occur anywhere else in that method. There is a parameter "Value" in the methods GetPageBy*(), but those parameters don't seem to be accessible in this method. So this does seem to be an error. I tried changing "%value%" to "null" and to "%null%", but those still gave the same warning. I then changed "%value%" to " "" " (i.e., the empty string). After that, the warning ceased, but I worry about whether this is the right correction or might cause some other problem later. Could someone please say if what I've done is right?
Afaik, that's a known bug/typo in Coco's Jxon_Load() function, which is used here - and should read val := %val% + 0 (or an equivalent).
Adding 0 here just makes sure that no string, but a number, is used for the boolean variable.
burque505
anaglypta
Posts: 17
Joined: 10 Nov 2020, 10:18

Re: [Library] Chrome.ahk - Automate Google Chrome using native AutoHotkey. No Selenium!

10 Nov 2020, 13:38

Thank you both, I found the error in the Chrome.ahk file itself, not in an included file. Although the code was probably based on the library by Coco that you mentioned.

@Newer2AHK:
I got the error by passing JS code to the Evaluate method. The JS did a comparison with ==, and returned a true/false value.
gregster
Posts: 8916
Joined: 30 Sep 2013, 06:48

Re: [Library] Chrome.ahk - Automate Google Chrome using native AutoHotkey. No Selenium!

10 Nov 2020, 13:44

anaglypta wrote:
10 Nov 2020, 13:38
Thank you both, I found the error in the Chrome.ahk file itself, not in an included file.
Yes, I know, in the Chrome.ahk release 1.2 it's directly in the file (for convenience, I guess), but the bug is still coming from Coco's original Jxon.ahk functions - well, actually GeekDude's fork of it, which still had the bug (compare at the end of https://github.com/G33kDude/Chrome.ahk/blob/master/Chrome.ahk and https://github.com/G33kDude/AutoHotkey-JSON/blob/1899578d0f0ea394804421b5a5319238238f81e1/Jxon.ahk). Not that it matters much...

In the end, including in AHK is nothing more than copying code into another script file (just automated by AHK).
Quetzal
Posts: 3
Joined: 02 Jun 2018, 08:31

Re: [Library] Chrome.ahk - Automate Google Chrome using native AutoHotkey. No Selenium!

10 Nov 2020, 23:29

great, but what do really means "work only in debug mode" ??
- do this library can be used just to make all the missing keyboard shortcuts for a normal websurf with this awsome webrowser
gregster
Posts: 8916
Joined: 30 Sep 2013, 06:48

Re: [Library] Chrome.ahk - Automate Google Chrome using native AutoHotkey. No Selenium!

10 Nov 2020, 23:33

Quetzal wrote:
10 Nov 2020, 23:29
great, but what do really means "work only in debug mode" ??
you have to start Chrome (or another supported browser) with a special command line parameter, but Chrome.ahk can do this for you - no difference in appearance.
In company environments, it might not be possible, though, depending on your user permissions.
- do this library can be used just to make all the missing keyboard shortcuts for a normal websurf with this awsome webrowser
Possibly, but I am not really sure what that means. Please elaborate!
Natitoun
Posts: 6
Joined: 09 May 2019, 06:57

Re: [Library] Chrome.ahk - Automate Google Chrome using native AutoHotkey. No Selenium!

12 Nov 2020, 10:14

Hi all !

I have one issue that I can't fix, maybe one of you have an idea on how to figure it out :)

While automating Chrome thanks to Chrome.ahk, I am facing an issue with a small popup window, the kind you get with a "Javascript: alert('Hello World!')" command.
This window will appear when I am sending a wrong request to my website.

I'd like to detect this window and close it ("ok" button).

What I tried:
- I am reading the URL thanks to PageInst.Evaluate("document.URL;").Value but when there is the popup, the ahk script stops, waiting endlessly for the return of the function that never comes. Thus I tried to add a TimeOut argument to the PageInst.Evaluate function in order to detect the popup when the timeout is reached. However, I could not make the Timeout work (available accordingly to Chrome Devtools). I tried a couple of different possibilities but it would basically look like this:

Code: Select all

Evaluate(JS,Timeout)
{
	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_False(),
		"timeout": Timeout
	}
	))
- Using ACC: thanks to the GetBrowserURL_ACC function (topic 637687), I can retrieve the URL of the page thanks to ACC. I noticed that when I was facing the popup, the function would return a blank window so I was using this until a new version of Chrome (I guess) that allow the function to return the URL despite of the popup.

I hope I was clear enough. If you have any suggestion that may help I would love to read it.
If you need clarifications, please let me know.
evilmanimani
Posts: 29
Joined: 24 Jun 2020, 16:42

Re: [Library] Chrome.ahk - Automate Google Chrome using native AutoHotkey. No Selenium!

02 Dec 2020, 21:49

Natitoun wrote:
12 Nov 2020, 10:14
Hi all !

I have one issue that I can't fix, maybe one of you have an idea on how to figure it out :)

While automating Chrome thanks to Chrome.ahk, I am facing an issue with a small popup window, the kind you get with a "Javascript: alert('Hello World!')" command.
This window will appear when I am sending a wrong request to my website.

I'd like to detect this window and close it ("ok" button).
Should be simple enough just with a regular timer running in the background, either at the start of the script, or at the start of the function.

Code: Select all

CloseAlert:
If (WinExist("Hello World!")) {
	WinActivate
	Send, {enter}
}
Return

SetTimer, CloseAlert, 100
serzh82saratov
Posts: 137
Joined: 01 Jul 2017, 03:04

Re: [Library] Chrome.ahk - Automate Google Chrome using native AutoHotkey. No Selenium!

06 Dec 2020, 16:06

How can you specify the text?
This is how I did in InternetExplorer

Code: Select all

Str := Clipboard
objIE.document.querySelector("textarea[name=text_or_url]").value := Str
Any text can be on the clipboard.

So with Chrome.ahk in the Clipboard there can only be text that matches the JSON syntax if I understand correctly.

Code: Select all

Str := Clipboard
Page1.evaluate("document.querySelector('textarea[name=text_or_url]').value = '" Str "'")
teadrinker
Posts: 4309
Joined: 29 Mar 2015, 09:41
Contact:

Re: [Library] Chrome.ahk - Automate Google Chrome using native AutoHotkey. No Selenium!

06 Dec 2020, 17:26

serzh82saratov wrote: in the Clipboard there can only be text that matches the JSON syntax
No, it can be any text, but special characters must be escaped.
geek
Posts: 1052
Joined: 02 Oct 2013, 22:13
Location: GeekDude
Contact:

Re: [Library] Chrome.ahk - Automate Google Chrome using native AutoHotkey. No Selenium!

06 Dec 2020, 19:04

It's worth noting, the Jxon_Dump function will correctly format strings for use in javascript evaluation. Also note that strings will get escaped, and numbers will be left alone.

Code: Select all

Page1.evaluate("document.querySelector('textarea[name=text_or_url]').value = " Chrome.Jxon_Dump(Clipboard))
serzh82saratov
Posts: 137
Joined: 01 Jul 2017, 03:04

Re: [Library] Chrome.ahk - Automate Google Chrome using native AutoHotkey. No Selenium!

07 Dec 2020, 14:49

Tell me, how can I find out the PID or HWND of the main window if I found it using FindInstances?
ChromeInst.PID is empty in this case.
teadrinker
Posts: 4309
Joined: 29 Mar 2015, 09:41
Contact:

Re: [Library] Chrome.ahk - Automate Google Chrome using native AutoHotkey. No Selenium!

07 Dec 2020, 19:49

@GeekDude
@serzh82saratov
I'd rewrite FindInstances() like this:

Code: Select all

	FindInstances()
	{
		Out := {}
		for Item in ComObjGet("winmgmts:").ExecQuery("SELECT * FROM Win32_Process WHERE Name = 'chrome.exe'")
			if RegExMatch(Item.CommandLine, "i)chrome.exe""?\s+--remote-debugging-port=(\d+)", Match)
				Out[Match1] := {cmd: Item.CommandLine, PID: Item.ProcessId}
		return Out.MaxIndex() ? Out : False
	}
Then you can get the PID:

Code: Select all

if (Chromes := Chrome.FindInstances()) {
   ChromeInst := {"base": Chrome, "DebugPort": Chromes.MinIndex()}
   ChromeInst.PID := Chromes[Chromes.MinIndex(), "PID"]
}
MsgBox, % ChromeInst.PID
The bug with the wrong registry key is still present in the new version:
RegRead, ChromePath, HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe

Return to “Scripts and Functions (v1)”

Who is online

Users browsing this forum: gwarble and 128 guests