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

Post your working scripts, libraries and tools for AHK v1.1 and older
madtuner
Posts: 2
Joined: 29 Mar 2023, 11:21

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

Post by madtuner » 12 Apr 2023, 14:45

lassos wrote:
15 Mar 2023, 02:02
Gh0sTG0 wrote:
14 Mar 2023, 15:53
@lassos
As for shortcut version for me works:

Code: Select all

"C:\Program Files\Google\Chrome\Application\chrome.exe" --remote-debugging-port=9222 --remote-allow-origins=* --user-data-dir="D:\ahk_chrome_profile"
Wow, thanks, this works for me too .-) , pretty cool, it is working again. spent so much time in my automating browser website routines with chrome.ahk. allready considered to develop chrome extension. now i do not need :bravo:
Hi,

would you mind posting your example using the line above for others to follow? Many thanks!

Gh0sTG0
Posts: 55
Joined: 25 Jun 2018, 07:58

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

Post by Gh0sTG0 » 12 Apr 2023, 16:38

madtuner wrote:
12 Apr 2023, 14:45
Gh0sTG0 wrote:
14 Mar 2023, 15:53
As for shortcut version for me works:

Code: Select all

"C:\Program Files\Google\Chrome\Application\chrome.exe" --remote-debugging-port=9222 --remote-allow-origins=* --user-data-dir="D:\ahk_chrome_profile"
Hi, would you mind posting your example using the line above for others to follow? Many thanks!
Hi. If this is question for me, then...

"D:\ahk_chrome_profile" is my way to the folder where separate ahk profile will be. It is not my main instance of chrome, separate profile on separate mail, etc. All files of instance will be in that folder. It will open parallel with main chrome not affecting it.
If you want to use ahk on your main chrome profile (not recomended) then you can delete `--user-data-dir="D:\ahk_chrome_profile"`. But you will need to start chrome from that shortcut, like close chrome completely (including tray), then start from this shortcut.

I just click right mouse button on clear space on desktop, create shortcut, paste full line there, next, finish. Then change icon so that you will see visually what shortcut is for what. Start with double click, set settings for your new chrome, it will not import things from your main.

This example code is not starting chrome. You will need to start it manually before pressing hotkey (here it will be F1). That's my way of how things working better for me.

Code: Select all

#Include Chrome.ahk ; Chrome.ahk is in one folder with this script.ahk file.

F1::
{
	PageInst := Chrome.GetPage(1) ; connecting to the tab you see in front of you (activated tab)
	PageInst.Call("Page.navigate", {"url": "https://www.autohotkey.com/"}) ; opening ahk.com page in current tab of ahk instance
	PageInst.Disconnect() ; don't forget to disconnect, there's some limit on number of opened connections.
	Return
}

madtuner
Posts: 2
Joined: 29 Mar 2023, 11:21

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

Post by madtuner » 13 Apr 2023, 10:27

Thanks @Gh0sTG0 Chrome launches, but I seem to be getting an error "Invalid status: 00000". My hunch is because I am running it on Win 7, Chrome 109.0.5414.120?
---------------------------
test.ahk
---------------------------
Error in #include file "D:\AHK\Chrome\Chrome.ahk":
Invalid status: 00000

Line#
595: if this.headers
596: {
597: if ! DllCall("Winhttp\WinHttpAddRequestHeaders", "Ptr", hRequest, "WStr", this.headers, "UInt", -1, "UInt", 0x20000000, "Int")
603: Throw,Exception("WinHttpAddRequestHeaders failed: " this._LastError())
604: }
607: status := "00000"
608: if (!DllCall("Winhttp\WinHttpSetOption", "Ptr", hRequest, "UInt", 114, "Ptr", 0, "UInt", 0, "Int") || !DllCall("Winhttp\WinHttpSendRequest", "Ptr", hRequest, "Ptr", 0, "UInt", 0, "Ptr", 0, "UInt", 0, "UInt", 0, "UPtr", 0, "Int") || !DllCall("Winhttp\WinHttpReceiveResponse", "Ptr", hRequest, "Ptr", 0) || !DllCall("Winhttp\WinHttpQueryHeaders", "Ptr", hRequest, "UInt", 19, "Ptr", 0, "WStr", status, "UInt*", 10, "Ptr", 0, "Int") || status != "101")
---> 613: Throw,Exception("Invalid status: " status)
616: if !(this.Ptr := DllCall("Winhttp\WinHttpWebSocketCompleteUpgrade", "Ptr", hRequest, "Ptr", 0))
617: Throw,Exception("WinHttpWebSocketCompleteUpgrade failed: " this._LastError())
620: DllCall("Winhttp\WinHttpCloseHandle", "Ptr", this.HINTERNETs.Pop())
621: this.HINTERNETs.Push(this.Ptr)
622: this.readyState := 1
625: if (this.async)
626: {

The current thread will exit.
---------------------------
OK
---------------------------

lassos
Posts: 4
Joined: 14 Mar 2023, 15:17

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

Post by lassos » 18 Apr 2023, 03:46

Hello. I have a problem wit the following routine

i send from ahk script1 a command to ahk script 2 which calls a routine (FindInstances) from chrome.ahk

ahk script 2 use the chrome.ahk. but i am getting the following error as attached file

if i will insert sleep, 5000 i a m getting no error

could anybody help me?
Attachments
chromeahkpng.png
chromeahkpng.png (82.93 KiB) Viewed 3728 times

User avatar
Datapoint
Posts: 296
Joined: 18 Mar 2018, 17:06

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

Post by Datapoint » 24 Apr 2023, 14:06

Hi, and thanks to geekdude for making Chrome.ahk and thanks to both geek and joe for the videos linked in the first post! The videos really helped fill in the blanks for me. And thanks to thqby for the v2 versions.

I wanted to share an example script that I made to automate part of a Cognito Forms page that I use at work. (The script won't work exactly as provided because I have replaced the URL with a generic one.) The script navigates to a page, clicks the "Next" button to go to the second page of the form, then it checks "Yes" in all the radio buttons.

Some points of interest:

.WaitForLoad() did not work in this case. I think because the page shows an animation while it is loading data. So I used a while loop to wait for a certain element on the page to be present.

The map function that was mentioned in the videos was perfect for checking all the radio buttons on a page: https://www.youtube.com/watch?v=GqvMwywARvM&list=PL3JprvrxlW26Rz0jb5pp0Rmye3qrwUlhp&index=6&t=461s

I spent longer than I care to admit trying to get it to start a new instance of Chrome with the correct profile. Mainly because in the v2 version of chrome.ahk, ProfilePath is the 5th parameter of __New(), not the first like in v1. I also had to use .NewPage() not .GetPage() :mrgreen: .

Code: Select all

; Example script to fill a Cognito Forms page.
; Note: this script will not run exactly as provided because I have removed personal info and provided a generic URL.

#Requires AutoHotkey v2
#SingleInstance Force
#Include Chrome.ahk
#Include JSON.ahk
;TraySetIcon "Logo.png"

; Parse command line parameters. Ex:
; "My Comapy Division" "0000000-00A" "Some Person" "Some Job Type"
; MsgBox A_Args[1] "`n" A_Args[2] "`n" A_Args[3] "`n" A_Args[4]
; Add JSON data to the url to pre-fill certain fields
; Pre-filling a Cognito form https://www.cognitoforms.com/support/65/data-integration/prefilling-a-form
url := "https://www.cognitoforms.com/mycompany/mycompanyform?entry="
	.	"{"
	.		"`"JobDetails`":"
	.		"{"
	.			"`"Division`":`"" A_Args[1] "`","
	.			"`"JobNumber`":`"" A_Args[2] "`","
	.			"`"User`":`"" A_Args[3] "`","
	.			"`"JobType`":`"" A_Args[4] "`","
	.			"`"Date`":`"" A_YYYY "-" A_MM "-" A_DD "`""
	.		"}"
	.	"}"
; Escape quotes and spaces
url := StrReplace(url, "`"", "%22")
url := StrReplace(url, A_Space, "+")

; Navigate to the url and then evaluate some JS code to manipulate the page.
; Note: Chrome must be started in remote debugger mode. That is why this script will create a new instance of Chrome if
; one is already running. A separate user profile will be used also, located in ChromeProfilePath. The script will
; create a new profile folder if one does not already exist.
; Links:
; 	Chrome.ahk for v1.1 https://www.autohotkey.com/boards/viewtopic.php?p=194724#p194724
; 	Chrome.ahk for v2 https://github.com/thqby/ahk2_lib/blob/master/Chrome.ahk
; 	JSON.ahk for v2 https://github.com/thqby/ahk2_lib/blob/master/JSON.ahk
; 	Chrome DevTools https://chromedevtools.github.io/devtools-protocol/
; 	JS map function https://www.youtube.com/watch?v=GqvMwywARvM&list=PL3JprvrxlW26Rz0jb5pp0Rmye3qrwUlhp&index=6&t=461s
ChromeProfilePath := A_AppData "\Google\Chrome\FormsProfile"
ChromeInst := Chrome( , , , , ChromeProfilePath)
PageInstance := ChromeInst.NewPage()
PageInstance.Call("Page.navigate", {url: url})
; WaitForLoad() does not work, maybe because there is an animation that plays while loading data.
;PageInstance.WaitForLoad()

; Wait for the animation to stop and data to be loaded.
JS := "document.querySelector('body > form')"
;for k, v in PageInstance.Evaluate(JS) ; Evaluate returns a map.
;	MsgBox ">" k "`n>" v ; {subtype: "null", type: "object", value: ""}
while PageInstance.Evaluate(JS)["subtype"] = "null"
	Sleep 100

; Activate the chrome window.
SetTitleMatchMode 2
WinActivate "mycompanyform - Google Chrome"

; Click the "Next" button to go to page 2.
JS := "document.querySelector('.cog-button--next').click()"
PageInstance.Evaluate(JS)

; Check all the "Yes" radio buttons on the second page.
JS := "
(
var x = [].map.call(
	document.querySelectorAll('div.cog-checkable.cog-input'),
	(e) => e.querySelector('.el-radio'));
for (var i = 0; i < x.length; i++) {
    x[i].click()
}
)"
; Edit: This JS seems to work too without the extra call to map.
;JS := "
;(
;var x = document.querySelectorAll('.cog-checkable--inline > div > label:nth-child(1)')
;for (var i = 0; i < x.length; i++) {
;    x[i].click()
;}
;)"
PageInstance.Evaluate(JS)
ExitApp

tpitera
Posts: 31
Joined: 27 Oct 2020, 15:56

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

Post by tpitera » 25 Apr 2023, 01:24

Im running version 1. Having trouble outputting text from a javacript call into AHK

Code: Select all

#Include ..\Chrome.ahk
    FileCreateDir, ChromeProfile
ChromeInst := new Chrome("ChromeProfile", "https://palmbeach.realforeclose.com/index.cfm?zaction=USER&zmethod=CALENDAR")

; --- Connect to the page ---

if !(PageInst := ChromeInst.GetPage())
{
	MsgBox, Could not retrieve page!
	ChromeInst.Kill()
}
else
{
	; --- Perform JavaScript injection ---
	;arialabel := "div[aria-label='" . CurrentDate . "'] span span span"
	;MsgBox, %JS%
	PageInst.WaitForLoad()
	Sleep, 5000
	JS = document.querySelector("div[aria-label='April-25-2023'] span span span").innerText

numProps := PageInst.Evaluate(JS)
	;numProps := PageInst.Evaluate("document.querySelectorAll('div[dayid]')[1].innerHtml;")
	;numProps2 := PageInst.Evaluate("document.querySelectorAll('span.CALACT')[1].innerText;")
	MsgBox, %numProps%
	;MsgBox, %numProps2%
	; --- Close the Chrome instance ---
	
	;try
		;PageInst.Call("Browser.close") ; Fails when running headless
	;catch
		;ChromeInst.Kill()
	;PageInst.Disconnect()
}

ExitApp
return
ESC:: ExitApp
I am just getting a blank variable. Please help.

User avatar
Xtra
Posts: 2750
Joined: 02 Oct 2015, 12:15

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

Post by Xtra » 25 Apr 2023, 09:51

I am just getting a blank variable. Please help.
try using:

Code: Select all

numProps := PageInst.Evaluate(JS).Value


tpitera
Posts: 31
Joined: 27 Oct 2020, 15:56

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

Post by tpitera » 25 Apr 2023, 23:44

JS = document.querySelector("div[aria-label='" . CurrentDate . "'] span span span").innerText
using same code i plugged in this as JS and its not working
the goal is to use current date as input

locoleos
Posts: 4
Joined: 27 Mar 2023, 06:57

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

Post by locoleos » 27 Apr 2023, 07:09

I'm very curious as to the security implications of adding "--remote-allow-origins=*" I haven't been able to find any documentation on what it does through my admittedly somewhat weak google fu; just a horde of selenium users posting it as a workaround for the same problem we're using it for. What exactly are we opening up access to all origins to here? Is it all origins on my localhost, or all origins period? Because it sounds like it might be a scary thing to do.

Sorry if this is a silly question but I am wary of a script on some webpage asking if it can open a headerless instance of Chrome and my Chrome going "--remote-debugging-port=9222 --remote-allow-origins=* so sure!" and then it looks at all my cookies and opens my google linked credit card info (not that I have that linked in there but, you know) which you can do without entering a password for some reason.

Anyone have any input here?

daamian
Posts: 1
Joined: 05 May 2023, 03:00

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

Post by daamian » 05 May 2023, 03:10

Hey everyone,

I'm having some trouble importing the WebSocket.ahk library into my script, and I could really use some help. I keep encountering a syntax error, and I'm not sure what to do about it. I've attached the code of my script and a screenshot of the error for reference.

Here's the code snippet where I'm trying to import the library:

Code: Select all

#Include Chrome.ahk

FileCreateDir, ChromeProfile
ChromeInst := new Chrome("ChromeProfile", "--remote-debugging-port=9222 --remote-allow-origins=*")
Sleep, 1000

!,:: ;odrzucony
MsgBox, Punkt 1
TabInstance := ChromeInst.GetPage()

MsgBox, Punkt 1

TabInstance.Evaluate("document.querySelectorAll('iframe')[3].contentWindow.document.getElementsByClassName('cp-send-recenzent-button')[0].click()")
Sleep, 200
TabInstance.Evaluate("document.querySelectorAll('.form-check-input')[2].click()")
Sleep, 200
TabInstance.Evaluate("document.querySelector('.bootbox-accept').click()")
Sleep, 12500
TabInstance.Evaluate("document.getElementsByClassName('status-picker')[0].click()")
Sleep, 1600
TabInstance.Evaluate("document.getElementsByClassName('form-control')[18].value = document.getElementsByClassName('form-control')[18][2].value")
Sleep, 200
TabInstance.Evaluate("document.getElementsByClassName('btn--primary')[4].click()")
Sleep, 200
TabInstance.Evaluate("document.getElementsByClassName('cp-ore-recenzent-button')[0].click()")
Sleep, 1800

MsgBox, Punkt 2

TabInstance := ChromeInst.GetPage()

If (TabInstance.Evaluate("document.querySelectorAll('span')[5].textContent").Value == "Oczekuje na ocenę"){
    MsgBox, Punkt 3
    
    TabInstance.Evaluate("const rev = document.querySelectorAll('#review-2-table')[2]")
    Sleep, 300
    TabInstance.Evaluate("rev.querySelectorAll('a')[1].click()")
    Sleep, 1000
    TabInstance.Evaluate("document.querySelectorAll('input')[1].click()")
    Sleep, 500
    TabInstance.Evaluate("document.getElementById('add-new-product-attachment-save').click()")
    Sleep, 700
    TabInstance.Evaluate("document.getElementById('confirmationRevertYes').click()")
    
    MsgBox, Punkt 4
    
    return
} else {
    MsgBox, Nie można dodać oceny !!!
    return
}

!.:: ;zaakceptowany
    TabInstance := ChromeInst.GetPage()
    TabInstance.Evaluate("document.querySelectorAll('iframe')[3].contentWindow.document.getElementsByClassName('cp-send-recenzent-button')[0].click()")
    Sleep, 200
    TabInstance.Evaluate("document.querySelectorAll('.form-check-input')[2].click()")
    Sleep, 500
    TabInstance.Evaluate("document.querySelector('.bootbox-accept').click()")
    Sleep, 12500
    TabInstance.Evaluate("document.getElementsByClassName('status-picker')[0].click()")
    Sleep, 1600
    TabInstance.Evaluate("document.getElementsByClassName('form-control')[18].value = document.getElementsByClassName('form-control')[18][4].value")
    Sleep, 100
    TabInstance.Evaluate("document.getElementsByClassName('btn--primary')[4].click()")
    Sleep, 100
    TabInstance.Evaluate("document.getElementsByClassName('cp-ore-recenzent-button')[0].click()")

    Sleep, 1800
    TabInstance := ChromeInst.GetPage()

    If (TabInstance.Evaluate("document.querySelectorAll('span')[5].textContent").Value == "Oczekuje na ocenę"){
        TabInstance.Evaluate("const rev = document.querySelectorAll('#review-2-table')[2]")
        Sleep, 300
        TabInstance.Evaluate("rev.querySelectorAll('a')[1].click()")
        Sleep, 1000
        TabInstance.Evaluate("document.querySelectorAll('input')[0].click()")
        Sleep, 500
        TabInstance.Evaluate("document.getElementsByClassName('review-attachement-input')[1].click()")
        Sleep, 300

        ;TabInstance.Evaluate("document.getElementById('add-new-product-attachment-save').click()")
        ;Sleep, 500
        ;TabInstance.Evaluate("document.getElementById('confirmationRevertYes').click()")
    } else {
        MsgBox, Nie można dodać oceny !!!
        return
    }


I've double-checked the file path, and I'm confident that the WebSocket.ahk library is in the correct location. However, I can't figure out why I'm getting this syntax error.

If anyone has experience with importing libraries or has encountered a similar issue before, I would greatly appreciate your guidance. I'm relatively new to using this library, so any tips or suggestions would be incredibly helpful.

Thank you in advance for your assistance!

Best regards,
Damian

And here's the error message I'm getting:
Attachments
error.png
error.png (253.19 KiB) Viewed 3310 times

User avatar
Xtra
Posts: 2750
Joined: 02 Oct 2015, 12:15

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

Post by Xtra » 05 May 2023, 11:05

Continuation section too long see:
continuation sections
A continuation section cannot produce a line whose total length is greater than 16,383 characters (if it tries, the program will alert you the moment the script is launched). One way to work around this is to do a series of concatenations into a variable.

User avatar
labrint
Posts: 379
Joined: 14 Jun 2017, 05:06
Location: Malta

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

Post by labrint » 12 May 2023, 04:32

Is there a way for Chrome.ahk to connect to an already opened Chrome browser?

If so, how do I identify which opened chrome (if there are multiple) to connect with. For example if I want to identify the open chrome based on the URL of an open tab and then connect to it to control it?

Gh0sTG0
Posts: 55
Joined: 25 Jun 2018, 07:58

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

Post by Gh0sTG0 » 12 May 2023, 04:37

@labrint Hi. Yes, you can, but only if chrome is opened correctly.
Check my post (or just scroll up, it's on this page).
You can't connect to chrome if it is not started correctly. (you need to close current instance and then rerun it)

Code: Select all

--remote-debugging-port=9222 --remote-allow-origins=*

User avatar
labrint
Posts: 379
Joined: 14 Jun 2017, 05:06
Location: Malta

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

Post by labrint » 12 May 2023, 04:42

The problem is this. I have a 3rd party program that when a button is clicked, opens Chrome and loads that URL. I want to connect to that chrome.

Is it possible to set chrome so that it opens this way as mentioned?

User avatar
labrint
Posts: 379
Joined: 14 Jun 2017, 05:06
Location: Malta

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

Post by labrint » 12 May 2023, 04:45

Ah fantastic, I followed your post, changed the chrome target, and it works brilliantly. Thanks!!

Gh0sTG0
Posts: 55
Joined: 25 Jun 2018, 07:58

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

Post by Gh0sTG0 » 12 May 2023, 04:47

@labrint
=) happy that I can help =)

User avatar
labrint
Posts: 379
Joined: 14 Jun 2017, 05:06
Location: Malta

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

Post by labrint » 12 May 2023, 07:38

Problem solved. I corrected the following:

Registry key
Computer\HKEY_CLASSES_ROOT\ChromeHTML\shell\open\command

Target
"C:\Program Files\Google\Chrome\Application\chrome.exe" --remote-debugging-port=9222 -- "%1"

Next question: How do I close specific tabs, like tabs not containing keywords in a URL for example?
Is it possible to focus on the last tab when opening a connection with an existing session?

Hope151
Posts: 2
Joined: 08 Jun 2023, 10:22

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

Post by Hope151 » 08 Jun 2023, 10:39

Selected Element from Dropdown Box

Hello,

I'm trying to automate the selection of an element from a dropdown box. Here is the JS code I'm trying to approach (it's embedded in a frame so that complicates things):
image.png
image.png (14.19 KiB) Viewed 2781 times
[Mod edit: Removed img tags. Attachment tags are sufficient here. Additional tags will break the image. ]

And here's the hotkey code I'm using.

Code: Select all

PageInstance := Chrome.NewSession() 		; creating session

framejs = 
(
var aframe = document.getElementsByName('buscaLocalUf')[0];
aframe.contentDocument.querySelector('#buscaLocalUf').selectedIndex = 2  // AL select
)
PageInstance.Evaluate(framejs).focus() 
[Mod edit: [code][/code] tags added. Please use them yourself going forward.]

I've looked everywhere and can't seem to find anything, please advise. Any help is appreciated.

Thank you.

pavillon
Posts: 2
Joined: 25 Jun 2023, 02:44

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

Post by pavillon » 25 Jun 2023, 04:40

[Mod edit: Removed long, completely unrelated quote.]

Please convert Chrome.ahk from V1 to V2. Thank you much!

Post Reply

Return to “Scripts and Functions (v1)”