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

Post your working scripts, libraries and tools for AHK v1.1 and older
dbareis
Posts: 39
Joined: 04 Feb 2022, 17:57

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

Post by dbareis » 09 Feb 2022, 17:39

gregster wrote:
09 Feb 2022, 01:27
Try

Code: Select all

PageInstance.Call("Page.bringToFront")
Thanks for that, that works well. Do you know where I can find similar commands documented or at least listed by someone.

And while I'm here I have only seen error handling in a very very few places so here is an example that others may find in future:

Code: Select all

    ChromeInst   := new Chrome(ProfilePath:=DirFS)    ;As far as I can see relative paths aren't supported (doco wrong?) and slashes have to be forward ones
    PageInstance := ChromeInst.GetPageBy("url", NaaPageUrlStartsWith, "startswith")
    if IsObject(PageInstance)
    {
       ;--- bring the existing tab/page into focus
       PageInstance.Call("Page.bringToFront")   ;Thanks gregster :=)
    }   
    else    
    { 
        ;--- It doesn't exist so open the URL and wait for the page to load ---
        PageInstance := ChromeInst.GetPage()
        PageInstance.Call("Page.navigate", {"url": NaaSearchUrl})
       ;SoundBeep, 1050, 200
       PageInstance.WaitForLoad()
       Sleep 500
    }
    
    ...
    
    try
    {
        ;--- WORKS IF AT: "https://recordsearch.naa.gov.au/SearchNRetrieve/Interface/SessionTimeout.aspx"
        PageInstance.Evaluate("document.getElementById('ContentPlaceHolderSNR_lbnGuest').click()")
        PageInstance := ChromeInst.GetPage()
        PageInstance.WaitForLoad()
        Sleep 500
    }
    catch e
    {}

gregster
Posts: 8990
Joined: 30 Sep 2013, 06:48

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

Post by gregster » 10 Feb 2022, 00:06

dbareis wrote:
09 Feb 2022, 17:39
gregster wrote:
09 Feb 2022, 01:27
Try

Code: Select all

PageInstance.Call("Page.bringToFront")
Thanks for that, that works well. Do you know where I can find similar commands documented or at least listed by someone.
These methods are all part of Google's Chrome DevTools protocol, not AHK.

The protocol is pretty large (and still evolves), and divided up into different domains like Page of "Page.bringToFront" (https://chromedevtools.github.io/devtools-protocol/tot/Page/)
In some parts, it's rather low-level, and a bit of trial-and-error might be needed to understand what they are for. Probably many methods, events, ... are pretty irrelevant for most users.
Unfortunately, not everything is so straightforward like "bringToFront" - and of course, you have to find the goodies first, before you can use them.

dbareis
Posts: 39
Joined: 04 Feb 2022, 17:57

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

Post by dbareis » 10 Feb 2022, 00:13

gregster wrote:
10 Feb 2022, 00:06
These methods are all part of Google's Chrome DevTools protocol, not AHK.

The protocol is pretty large (and still evolves), and divided up into different domains like Page of "Page.bringToFront" (https://chromedevtools.github.io/devtools-protocol/tot/Page/)
Thank you. I did (eventually) realise that I'd be needing to search the dev tools pages but wasn't getting anywhere. The page tools page you provided is a good place to start I should be able to work out the rest from that :-)

isaacbr
Posts: 3
Joined: 04 Feb 2022, 01:58

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

Post by isaacbr » 13 Feb 2022, 18:44

Tre4shunter wrote:
02 Jul 2020, 15:31
Yet another Iteration...

Realized i can just let PS handle the file creation...so no need to loop over the file checking for filesize. Also - like in my edited post above, no longer have the password credential hardcoded in plain text.

Code: Select all

	FindInstances()
	{
			PS = 
			(
				$password = Get-Content F:\UserFolders\md\MCSTool\Chrome\password.txt | ConvertTo-SecureString -Key (Get-Content F:\UserFolders\md\MCSTool\Chrome\aes.key)
				$Cred = New-Object System.Management.Automation.PsCredential(\"vgesinc\md\", $password)
				start-process -WindowStyle hidden -Wait -FilePath "$env:comspec" -ArgumentList \"/c wmic Process where ``\"name = 'chrome.exe'``\" get commandline, processid\" -RedirectStandardOutput $env:TEMP\test.txt -Credential $Cred
			)			
			runwait, % "PowerShell.exe -Command & {" PS "}", % A_Temp , "Hide"
			
			FileRead, rfile, %A_Temp%\test.txt
			FileDelete, %A_Temp%\test.txt
			
			Needle := "--remote-debugging-port=(\d+)"
			Out := {}, i = 0
			Loop, parse, rFile, `n,`r
			{
				if RegExMatch(A_Loopfield, Needle, Match){
					Out[Match1,i++] := {"cmd":Item.CommandLine,"pid":Item.ProcessId,"port":Match1}
				}
			}
			return, Out
	}
Thanks,

Tre4
I am having the same issue but can't use your idea as my code need to run for user who don't know the admin password.
so, I came out with another workaround,
i check first if the current user has a instance and using that if found, if not, ill query to see if ports 9222 to 9299 which is the next available, it not elegant but it works.

here is the code that checks for next aavalble port.

Code: Select all

;save clipboard before usingit
ClipSaved := ClipboardAll 
; get any port 92xx to clipboard
RunWAIT, %ComSpec% /c netstat -NAo | findstr  "127.0.0.1:92.."  | CLIP,,Hide
myports := clipboard
;set back the clipboard to original
Clipboard := ClipSaved 
ClipSaved := "" 
freeport := 0
	Loop {
		freeport := A_Index +9221
			if  !(InStr( myports, freeport ))
				{  
				msgbox, % freeport . " Is the next avaialbe prot"
				break
				} 
		}
Last edited by isaacbr on 14 Feb 2022, 20:36, edited 1 time in total.

dbareis
Posts: 39
Joined: 04 Feb 2022, 17:57

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

Post by dbareis » 14 Feb 2022, 15:36

Hi,

This javascript:

Code: Select all

document.querySelector('#content > div.section-first.create-memorial.form-shaded.step-2 > div > div > div > p') != null ? 'exists' : '';
OR this invoking code:

Code: Select all

JsRc := PageInstance.Evaluate(Js).value
sometimes (rarely) hangs, I'm using it to wait for a control to exist and calling it every 100ms, in this trace I have it hung on loop 8.

Maybe the control is partway there but either way, has anyone seen this before and have a solution? Is there a way of terminating a command that has hung somehow?

I could reduce the risk by waiting longer between retries but that is not ideal (but I have done so for now)

Naits55
Posts: 3
Joined: 17 Feb 2022, 15:25

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

Post by Naits55 » 17 Feb 2022, 21:16

Hello guys,

I'm new to ahk and chrome.ahk... so I hope this question isn't too basic for you guys.

I have read trough the entire thread multiple times, watched all the videos and googled the crap out of this issue I have. But I'm unable to find a solution that works.

So I'm trying to enter a searchterm into a searchbox. The searchbox doesn't have an submit button, only way to activate it is by pressing enter on the keyboard.

I managed to populate the searchbox with:

Code: Select all

document.querySelector(".jss618").innerText = "Example Search Term"
Now I need to press enter...

First problem is, that I can only manually select the searchbox. I didn't find a way of putting my cursor into the box. I tried:

Code: Select all

document.querySelector(".jss618").focus()
document.querySelector(".jss618").click()
are there any other options?

Also I tried manually selecting the box (just for testing) and sending enter key stroke through the console with code like this:

Code: Select all

page.Call("Input.dispatchKeyEvent", {"type" : "rawKeyDown","windowsVirtualKeyCode" : 13,"unmodifiedText" : "\r","text" : "\r"})
I tried all kinds of different types for this event and combinations I could think of.

Only thing that works is this:

Code: Select all

page.Call("Input.dispatchKeyEvent", {"type" : "char", "text" : "Search Example"})
This will write into the searchbox. But only if i select it manually before sending this line. And also I can only submit by manually pressing enter. Which defeats the purpose of the whole thing.

So does anyone have an idea what I'm doing wrong or what else I could try?

Thanks in advance!

User avatar
Xeo786
Posts: 759
Joined: 09 Nov 2015, 02:43
Location: Karachi, Pakistan

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

Post by Xeo786 » 18 Feb 2022, 02:10

Naits55 wrote:
17 Feb 2022, 21:16
So does anyone have an idea what I'm doing wrong or what else I could try?

Thanks in advance!
I am writting Chrome DOM.ahk in order to use chrome.ahk in such similar way we used IE COM and have already implemented above calls and many other stuff you might find helpful
viewtopic.php?t=94276&p=418181
"When there is no gravity, there is absolute vacuum and light travel with no time" -Game changer theory

brunokitano
Posts: 3
Joined: 30 Mar 2022, 16:26

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

Post by brunokitano » 03 Apr 2022, 07:21

Is there a way to detect if it's reloading with this library? I couldn't figure it out

HeXaDeCiMaToR
Posts: 155
Joined: 08 Feb 2021, 12:42

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

Post by HeXaDeCiMaToR » 11 Apr 2022, 14:31

I ran into a situation of Windows 11 not wanting to connect to localhost:9222, but I could get the data by adding "/json/list" at the end of it. Then I noticed that under GetPageList() it was only calling "/json". When I added "/list" to the end of the "http.open" line I could get the Chrome Class to work again.

Hope this helps! :D

Code: Select all

GetPageList()
{
	http := ComObjCreate("WinHttp.WinHttpRequest.5.1")
	http.open("GET", "http://127.0.0.1:" this.DebugPort "/json/list")
	http.send()
	return this.Jxon_Load(http.responseText)
}

User avatar
Xeo786
Posts: 759
Joined: 09 Nov 2015, 02:43
Location: Karachi, Pakistan

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

Post by Xeo786 » 11 Apr 2022, 23:48

HeXaDeCiMaToR wrote:
11 Apr 2022, 14:31
I ran into a situation of Windows 11 not wanting to connect to localhost:9222, but I could get the data by adding "/json/list" at the end of it. Then I noticed that under GetPageList() it was only calling "/json". When I added "/list" to the end of the "http.open" line I could get the Chrome Class to work again.

Hope this helps! :D
Issue: it take little more time to create a localhost server, and our AHK Code try to get detail before server actually exist, it observed when someone try to create fresh chrome remote instant using chrome.ahk, we can make few changes to GetPageList() make it wait, until server initialized and responds,
this idea is from pull request https://github.com/G33kDude/Chrome.ahk/pull/28/commits/10e49a98458379c03f28838f397ff0d711d39832

Code: Select all

	GetPageList()
	{
		http := ComObjCreate("WinHttp.WinHttpRequest.5.1")
		StartTime := A_TickCount
		while (A_TickCount-StartTime < 10*1000)
		{
			try
			{
				http.Open("GET", "http://127.0.0.1:" this.DebugPort "/json/list", true)
				http.Send()
				http.WaitForResponse(-1)
				if (http.Status = 200)
					break
			}
			Sleep, 50
		}
		return this.Jxon_Load(http.responseText)
	}
"When there is no gravity, there is absolute vacuum and light travel with no time" -Game changer theory

fatodubs
Posts: 29
Joined: 20 Sep 2017, 18:53

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

Post by fatodubs » 02 May 2022, 23:13

I'm struggling with this at the very first stages - just opening a page. The problem is that Chrome seems to be attaching to my existing instance even when I tell it to open a new one with a new profile.

Code: Select all

SetBatchLines, -1
SetTitleMatchMode 2
#Include <Chrome>

wb_full_path := "C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe"
wb_exe := "msedge.exe"
wb_name := "Edge"



url1:="https://www.google.com/search?q=Tool forty six and 2 lyrics"
url2:="https://www.google.com/search?q=Pink floyd brick in the wall pt 1 lyrics"

flags = 
fldrChrome:=A_WorkingDir . "\EdgeProfile"
If (FileExist(fldrChrome)!="D")
	FileCreateDir, %fldrChrome%
ChromeInst:=new Chrome(fldrChrome,,,wb_full_path)
winwait, Edge

PageInst:=ChromeInst.GetPage()
PageInst.Call("Page.navigate", {"url": "https://autohotkey.com/"})
PageInst.WaitForLoad()

return
So it opens a new Edge window (or a Chrome window before I tried to do it with Edge), and then it changes the active page on my previously opened Chrome instance to the url.

I did some incremental testing with IsObject, and it is returning 1 with each new step, but obviously there is a disconnect between the object I am intending to connect to / create and what the script is actually doing.


Edit: Keeping this in here for anyone else that experiences it, and so someone can correct me if I'm wrong.
I closed Chrome and re-opened it without debugging mode, and everything started working as expected. I believe the issue is that my initial instance of Chrome was opened with debugging, and likely used the default port. So when the additional instance was created without a port specified - the one I was trying to script - it also tried to use the default port and everything after the initial creation was actually being sent to the original instance.

william_ahk
Posts: 486
Joined: 03 Dec 2018, 20:02

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

Post by william_ahk » 09 May 2022, 00:24

Can anyone help? I'm trying to upload a file with Chrome.ahk
viewtopic.php?f=76&t=103612

kauan014
Posts: 55
Joined: 18 Feb 2021, 20:03

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

Post by kauan014 » 06 Jun 2022, 18:18

How to get the currently active browser tab using the lib?

Yonibrese
Posts: 1
Joined: 14 Jun 2022, 03:59

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

Post by Yonibrese » 14 Jun 2022, 07:20

Hello,
I am new with Autohotkey and Chrome.ahk and I need help with the following script

first I want to explain what I want to accomplish with this script
1. connect to a webpage when chrome opens to the url
2. listen for when Java script sends a console.log (I have an other script running, and this tells AHK when to run)
3. input files from my file list into a File input field

The Issue here is that after I refresh/reload the webpage the script no longer "listens" for the console event.
and I need to run this script multiple times in a row

any Ideas here would be great
I have been beating my head on this for days already

Code: Select all

#NoEnv  ; Recommended for performance and compatibility with future AutoHotkey releases.
#Warn  ; Enable warnings to assist with detecting common errors.
SendMode Input  ; Recommended for new scripts due to its superior speed and reliability.
SetWorkingDir %A_ScriptDir%  ; Ensures a consistent starting directory.
SetBatchLines, -1

#Persistent
#Include, Chrome.ahk_v1.2/Chrome.ahk
#SingleInstance Force

;this script needs to alwalys be "listining" for the console.log event
;then click on a fileinput field button and Upload photos from my photo list
global page
page := Chrome.GetPageByUrl(WEBSITE_URL,,,func("eventCallBack_console").bind())
page.WaitForLoad()
page.call("Console.enable")
page.call("Page.enable")
page.call("Page.setInterceptFileChooserDialog", {enabled: Chrome.Jxon_True()})
return

eventCallBack_file(event){
    ; when the file chooser is opened I place a fileList into the fileInputField
    ; which I define from the backendNodeID that is given as a paramater in the event object
    if(event.method == "Page.fileChooserOpened"){
        ;this file list is manually created until I figure out how to get everyting programaticlly
        fileList := Array(IMAGE_1, IMAGE_2)
        for key, value in fileList{          
            page.call("DOM.setFileInputFiles",{"files":[value],"backendNodeId":event.params.backendNodeID},false)
            sleep 1000  
        }
        page.Disconnect()
    }
    return    
}

eventCallBack_console(event){
    ;finds my console log event that I fire in javascript, connect the second callback then send a clickevent to the browser 
    if(event.method == "Console.messageAdded" && InStr(event.params.message.text,"run_ahk") >= 1){
        page.Disconnect()
        page := Chrome.getPageByUrl(WEBSITE_URL,,,func("eventCallBack_file").bind())
        page.WaitForLoad()
        page.call("Page.enable")
        page.call("Page.setInterceptFileChooserDialog", {enabled: Chrome.Jxon_True()})
        sleep 2000
        page.evaluate("document.querySelector('#uploadr').click()")
        return
    }
    
}

Yogi
Posts: 12
Joined: 06 Jul 2022, 23:03

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

Post by Yogi » 07 Aug 2022, 19:49

Can you run chrome:

1) in the background
and
2) take a screenshot of a webpage using this without ever seeing the application?

Browny points for being able to tell it the region to capture.

I liked the IE.Visible = False command to get quick updates on things without launching the browser but sites don't really support it anymore.

User avatar
Xeo786
Posts: 759
Joined: 09 Nov 2015, 02:43
Location: Karachi, Pakistan

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

Post by Xeo786 » 11 Aug 2022, 03:52

Yogi wrote:
07 Aug 2022, 19:49
Can you run chrome:

1) in the background
and
2) take a screenshot of a webpage using this without ever seeing the application?

Browny points for being able to tell it the region to capture.

I liked the IE.Visible = False command to get quick updates on things without launching the browser but sites don't really support it anymore.
You need to Run chrome with headless parameter.

Code: Select all

Chrome := new Chrome(ProfileFolder,URL,"--headless")

and you need to call Page.captureScreenshot it will return Base64-encoded image which you need to decode and save.
"When there is no gravity, there is absolute vacuum and light travel with no time" -Game changer theory

WallNuts
Posts: 3
Joined: 11 Aug 2022, 17:01

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

Post by WallNuts » 11 Aug 2022, 17:13

Hey everyone, long time lurker but having an issue that finally forced me to make an account and ask a question.

Using Chrome AHK I am trying to determine whether a checkbox on a website is checked. Unfortunately, whenever I try to write the element.checked to an AHK variable, it becomes blank (as shown by the MsgBox). See below for the relevant parts of my code.

Code: Select all

#NoEnv
SetBatchLines, -1
#Include Chrome.ahk
#SingleInstance, Force
;**************************************
^DOWN:: 
WinActivate, Google
page := Chrome.GetPageByTitle("Google","contains") ;
If !IsObject(page){
	MsgBox % "That wasn't an object / the page wasn't found"
	ExitApp
}
vResponsive := "Hello" ; done to check if variable is overwritten by next line. It is.
vResponsive := page.Evaluate("document.getElementById('_profileAndPaneCollectionFrame').contentWindow.document.getElementById('_documentProfileFrame').contentWindow.document.querySelector('#_documentProfileEditor__kCuraScrollingDiv_dynamicViewRenderer_ctl09_radioButtonListField_radioButtonList_0').checked") 
; In the Chrome Dev Tools, the above line returns true. FYI the element is buried in a few frames so this iteration is how I set the execution context.
MsgBox % vResponsive
;if statement would be here using vResponsive
Note that I can click the element above using the page.Evaluate("...document.querySelector('element ID').click()").

dbareis
Posts: 39
Joined: 04 Feb 2022, 17:57

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

Post by dbareis » 11 Aug 2022, 17:42

Don't know, your selection is way more complicated than I'm used to I assume that is a frame inside a frame etc.

What happens if the end is "checked = true" or "checked = false" to the end? It helps if you try this in the chrome debugger's (F12) console tab. While you are there you may wish to try "copy" a better selector?

I assume you mean the variable is blank and not the checkbox becoming blank? In anycase the console and other tabs make working this out way easier.

User avatar
Xeo786
Posts: 759
Joined: 09 Nov 2015, 02:43
Location: Karachi, Pakistan

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

Post by Xeo786 » 12 Aug 2022, 02:22

WallNuts wrote:
11 Aug 2022, 17:13
Hey everyone, long time lurker but having an issue that finally forced me to make an account and ask a question.

Using Chrome AHK I am trying to determine whether a checkbox on a website is checked. Unfortunately, whenever I try to write the element.checked to an AHK variable, it becomes blank (as shown by the MsgBox). See below for the relevant parts of my code.

Code: Select all

#NoEnv
SetBatchLines, -1
#Include Chrome.ahk
#SingleInstance, Force
;**************************************
^DOWN:: 
WinActivate, Google
page := Chrome.GetPageByTitle("Google","contains") ;
If !IsObject(page){
	MsgBox % "That wasn't an object / the page wasn't found"
	ExitApp
}
vResponsive := "Hello" ; done to check if variable is overwritten by next line. It is.
vResponsive := page.Evaluate("document.getElementById('_profileAndPaneCollectionFrame').contentWindow.document.getElementById('_documentProfileFrame').contentWindow.document.querySelector('#_documentProfileEditor__kCuraScrollingDiv_dynamicViewRenderer_ctl09_radioButtonListField_radioButtonList_0').checked") 
; In the Chrome Dev Tools, the above line returns true. FYI the element is buried in a few frames so this iteration is how I set the execution context.
MsgBox % vResponsive
;if statement would be here using vResponsive
Note that I can click the element above using the page.Evaluate("...document.querySelector('element ID').click()").
try msgbox, % vResponsive.value
"When there is no gravity, there is absolute vacuum and light travel with no time" -Game changer theory

WallNuts
Posts: 3
Joined: 11 Aug 2022, 17:01

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

Post by WallNuts » 12 Aug 2022, 09:11

Xeo786 wrote:
12 Aug 2022, 02:22
try msgbox, % vResponsive.value
Thank you for the help Xeo786! Unfortunately neither
msgbox, % vResponsive.value
nor
msgbox, % vResponsive.checked
worked. Both still sent a blank msgbox.

Post Reply

Return to “Scripts and Functions (v1)”