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

Post your working scripts, libraries and tools for AHK v1.1 and older
blue83
Posts: 157
Joined: 11 Apr 2018, 06:38

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

11 May 2021, 08:24

Hi,

Does anyone knows how to get session from Chrome for XMLHttpRequest like on IE?

Thank you
User avatar
kagato
Posts: 10
Joined: 04 Dec 2015, 16:48
Location: 127.0.0.1

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

11 May 2021, 09:53

jsong55 wrote:
09 May 2021, 21:15
Question now is .. How to create a IF statement to detect if Chrome Instance is in Debug mode?

Code: Select all

	DebugPort := 9222 ;Default port for Chrome debugging
	
	IF (Chromes := Chrome.FindInstances()).HasKey(DebugPort) ;If existing instance of Chrome w/ Port 9222 found
	{
		ChromeInst := {"base": Chrome, "DebugPort": DebugPort} ;Attach to existing instance
	}	
	ELSE ;Port 9222 instance was not found, let's launch one.
	{
		ChromeInst := new Chrome(AHKProfilePath,,"--start-maximized",,9222) ;Launch a new instance
	}
Chuck Norris doesn't need garbage collection because he doesn't call .Dispose(), he calls .DropKick().
teadrinker
Posts: 4309
Joined: 29 Mar 2015, 09:41
Contact:

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

11 May 2021, 13:27

blue83 wrote: how to get session from Chrome

Code: Select all

profile := "D:\OneDrive\Scripts\Browsers\Chrome\Chrome.ahk\Examples\ChromeProfile"
url := "https://www.autohotkey.com/boards/viewtopic.php?p=399188"

ChromeInst := new Chrome(profile, url)
Loop 20 {
	try Page := ChromeInst.GetPage()
	Sleep 1000
} until Page
if !Page
	throw "Failed to get the Page object"
res := Page.Call("Target.getTargets")
for k, v in res.targetInfos {
   if (v.type = "page" && v.url = url) {
      targetId := v.targetId
      break
   }
}
; MsgBox, % "targetId: " . targetId
res := Page.Call("Target.attachToTarget", {targetId: targetId, flatten: Chrome.Jxon_True()}) ; or LightJson.true if use my version
MsgBox, % "sessionId: " . res.sessionId
blue83
Posts: 157
Joined: 11 Apr 2018, 06:38

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

12 May 2021, 03:38

Thank you @teadrinker ,

Do you know how to get JSESSIONID which is Httponly and secure?

Or how to handle API request with CSRF token instead of JSESSIONID if it is possible?

Thanks
Blue
User avatar
kagato
Posts: 10
Joined: 04 Dec 2015, 16:48
Location: 127.0.0.1

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

12 May 2021, 12:18

blue83 wrote:
12 May 2021, 03:38
Thank you @teadrinker ,

Do you know how to get JSESSIONID which is Httponly and secure?

Or how to handle API request with CSRF token instead of JSESSIONID if it is possible?

Thanks
Blue
In reference to the CSRF token, it would depend on the site, but there's one I use that exposes the token via jquery as 'CSRFToken';

Code: Select all

var token = CSRFToken
I take that and wrap it back into the header as the value for 'requestverificationtoken' to include with the API POST call:

Code: Select all

connectedPage.Evaluate("var token = CSRFToken; fetch('API_URL_Goes_Here', {'headers': {'content-type': 'application/json;charset=UTF-8','requestverificationtoken': token},'body':'Whatever_Payload_The_API_Expects','method': 'POST'});")
Chuck Norris doesn't need garbage collection because he doesn't call .Dispose(), he calls .DropKick().
blue83
Posts: 157
Joined: 11 Apr 2018, 06:38

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

14 May 2021, 02:25

Hi @kagato ,

Thank you for your reply.

Actually I am asking can CRSF token replace JSESSIONID in API request and can you post that example?

I am trying connect with API on active session in Chrome, I have all the cookies (document.cookies;), but JSESSIONID can not be extracted because it is HTTP only.

thanks,
blue
inseption86
Posts: 198
Joined: 19 Apr 2018, 00:24

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

16 May 2021, 08:14

Hello, how can I hide Chrome only after the page has loaded?

Code: Select all

ChromeInst := new Chrome(profile,, "--incognito)  
Page := ChromeInst.GetPage()
Page.Call("Page.navigate", {"url": URL})
Page.WaitForLoad()
....."--headless".....
letacio
Posts: 48
Joined: 08 Mar 2018, 16:05

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

18 May 2021, 09:10

bmilcs wrote:
02 Jul 2018, 18:14
And as I wear out my welcome here, I think I've found a bug of some type. After I make a dozen or so DOM JS calls, AHK locks up and this is what I'm seeing for output:

Code: Select all

037: if i := InStr("{[", ch)  
047: if InStr("}]", ch)  
049: ObjRemoveAt(stack, 1)  
050: next := stack[1]==tree ? "" : is_arr[stack[1]] ? ",]" : ",}"
051: }
134: }
010: While,( (ch := SubStr(src, ++pos, 1)) != "" )
136: Return,tree[1]
---- E:\autohotkey\Infraware\Chrome\Chrome.ahk
316: fnCallback := this.fnCallback
317: if (newData := %fnCallback%(data))  
320: if this.responses.HasKey(data.ID)  
322: }
329: } (0.91)
Those are the last lines every single time it locks up. I've tried running the same getelementby syntax, which I know works for a fact, several times and it locks up at the same point every time.

;-----------------------------------------------------------------------------------------------------------------------------

EDIT: SOLVED.

Code: Select all

PageInst.Disconnect()
After hours of tinkering with the code and browsing the Chrome DevTools page, I stumbled upon Page.Disconnect(). Apparently, the connection with Chrome was hitting the max allotment of time or only allows for X amount of actions per connection.

I added this to the end of the cycle of actions that I perform. This has completely fixed all issues I was having in regards to AHK freezing up after X amount of lines or time passed.

Hopefully this helps someone <3

The syntax

I'm using chrome 1.2 and it still gives me this error.
It works for some time, and freezes, on the line you mentioned.
I make like "rounds" of connection and disconnection so it doesnt stay for long, but it does not solve it.
This loop happens around 5 to 10 times when a=b is true (its a listener, and keeps refreshing until a=b).
After that, it gets stuck.

My code is like this:

Code: Select all


global vars
global driver

loop,
{
driver := driver.Chromeget("Page name")   

     if (a=b)
     {
     ; bunch of code 
     }

driver.Disconnect()
}

ChromeGet(title) {  ;para Chrome.ahk
	; start chrome.exe --remote-debugging-port=9222
	
	start_chrome:
	driver := Chrome.GetPageByTitle(title, "contains")
	
	if !Isobject(driver)
	{
	msgbox Page with this name not found! Make sure it is opened
	goto start_chrome
	}
	return driver
}
Another issue:
The connection drops for no reason. It gets on the line


242 ; Wait for the response
243 this.responses[ID] := False
244 counter1=0
245
247 while !this.responses[ID] <- keeps repeating this forever

So, i did like this to reconnect when it loses connection. It works, but didnt solve the main problem, and i don't know if it can be influencing on the other issue mentioned above.

Code: Select all

; Wait for the response
			this.responses[ID] := False
			counter1=0
			
			while !this.responses[ID]
			{
				Sleep, 100
				counter1+=1
				
				if (counter1>10)
				{
					;~ msgbox broke
					soundbeep
				driver.Disconnect()
				driver:= ChromeGet("Page name")	  <- here it reconnects, and moves on.		
				;~ goto continue_this
				break
				}
			
			}
I would like to use Chrome.ahk instead of selenium basic for all my projects, but with this issues it's impossible, as it is 100% unreliable.
Appreciate help!
Thanks!

Obs: I've tried also to connect/disconnect on each evaluate.
Takes a lot of time, and doesn't seem to solve it either, keeps freezing.
letacio
Posts: 48
Joined: 08 Mar 2018, 16:05

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

18 May 2021, 09:47

hisrRB57 wrote:
07 May 2021, 05:21
Hi, I am using teadrinkers tdChrome.ahk and I wonder when an exception occurs the timer started in the event method should be deleted or not?

here :

Code: Select all

		Call(DomainAndMethod, Params:="", WaitForResponse:=True)
		{
			if !this.Connected
				throw Exception("Not connected to tab")

and here :

Code: Select all

		Evaluate(JS)
		{
			response := this.Call("Runtime.evaluate",
			( LTrim Join
			{
				"expression": JS,
				"objectGroup": "console",
				"includeCommandLineAPI": LightJson.true,
				"silent": LightJson.false,
				"returnByValue": LightJson.false,
				"userGesture": LightJson.true,
				"awaitPromise": LightJson.false
			}
			))
			
			if (response.exceptionDetails)
				throw Exception(response.result.description,, LightJson.Stringify(response.exceptionDetails))
			
			return response.result
		}

Timer set code:

Code: Select all

		Event(EventName, Event)
		{
			; If it was called from the WebSocket adjust the class context
			if this.Parent
				this := this.Parent
			
			; TODO: Handle Error events
			if (EventName == "Open")
			{
				this.Connected := True
				BoundKeepAlive := this.BoundKeepAlive
				SetTimer, %BoundKeepAlive%, 15000
After I have processed a lot page.evaluates it seems a page.disconnect / timer delete is missed and the background timers keep throwing exceptions

Anyone a suggestion?
Had any sucess with that? i'm having the same problem also.
letacio
Posts: 48
Joined: 08 Mar 2018, 16:05

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

18 May 2021, 12:17

@hisrRB57
@bmilcs

Solved the issues I had mentioned!

Not the most elegant or best practices, but works for me for 1 stance:

Solution goes like this
a) Create a global "pageinst" object
b) use it to connect (get page by("title) )
c) Inside tdchrome.ahk, do 2 things
d) Always connect at starting cycle, and disconnect after tasks are done, in each loop, so it has time to clear.

c.1) change this

Code: Select all

if !this.Connected
        throw Exception("Not connected to tab")
for this:

Code: Select all

if !this.Connected
         {
                driver.Disconnect()                 ;disconnects current one
				sleep, 50
				driver:= ChromeGet("Page_name") ; connects again, at the global var, with same parameters	
         }
c.2
in "wait for response", upgrade this lines:

Code: Select all


; Wait for the response
         this.responses[ID] := False
         while !this.responses[ID]
         {
            Sleep, 50
         }

to

Code: Select all

          
         ; Wait for the response
         counter1=0
         this.responses[ID] := False
         while !this.responses[ID]
         {
            Sleep, 50
            
         counter1+=1
				
				if (counter1>10)
				{
					;~ msgbox broke
					soundbeep
				break
				}
           }
I think it can be done in a better way, but I would need to find out how to get data from instance, which is not very clear to me right now, and not my top1 priority, so i'll just leave the idea here:

The steps would be like:

Instead of disconnecting and using the global driver to do "pageget("name")" again, which is hardcoded, the script would get some reference to the actual object (for instance, getting the url or name), disconnect, then call itself again with this data.

like:
var:= this.windowname
this.disconnect
this.getpage(windowname)


Thanks for reading!
User avatar
submeg
Posts: 326
Joined: 14 Apr 2017, 20:39
Contact:

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

31 May 2021, 07:24

Hi all,

I've read through this thread (massive!) and noone has asked about the question I have, so thought I should add it below (I noticed someone suggested creating a separate section in the forums about Chrome.ahk; I'd support that idea as well...)

From what I've seen, When you have a PDF file open in a browser, IE is the only browser that allows you to "print current page". Is there a way, using Chrome.ahk, to print the currently visible page of a PDF file open in Chrome? It's driving some people at work a bit crazy and I thought I'd ask here to see if I could use Chrome.ahk to achieve this.

Also, as @GeekDude originally stated:
Note: I'm not sure what kind of security risks that would open you up to. If Chrome allows non-localhost connections (I think it might) and is allowed through the firewall (probably is) anyone else on the network could sneak into your session without you knowing. I'd need to do some more testing before I can recommend this in good conscience.
If using Chrome.ahk in a work setting, could running Chrome in debug mode make you vulnerable to cyber attack? This is outside my knowledge, so thought I should ask.

Tagging those that may know:

@flyingDman
@Joe Glines
@gregster
@teadrinker

Thanks in advance!
____________________________________
Check out my site, submeg.com
Connect with me on LinkedIn
Courses on AutoHotkey :ugeek:
gregster
Posts: 8918
Joined: 30 Sep 2013, 06:48

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

31 May 2021, 08:05

submeg wrote:
31 May 2021, 07:24
Is there a way, using Chrome.ahk, to print the currently visible page of a PDF file open in Chrome? It's driving some people at work a bit crazy and I thought I'd ask here to see if I could use Chrome.ahk to achieve this.
From the top of my head. I only know the possibility to export a currently open webpage to a pdf file (see this example) which then probably could be send to a printer in a second step. What happens if the open page is already a pdf, remains to be seen; also, if you could determine the correct/current page number of the pdf (although you can set page ranges for the pdf created from the webpage).
Perhaps the pdf will get re-encoded (instead of just downloading it), or it won't work at all. If I find something, I'll let you know.
Spoiler

But there might be other ways 🤷‍♂️ Perhaps something with javascript, run via Chrome.ahk ?
submeg wrote:
31 May 2021, 07:24
Also, as @GeekDude originally stated:
Note: I'm not sure what kind of security risks that would open you up to. If Chrome allows non-localhost connections (I think it might) and is allowed through the firewall (probably is) anyone else on the network could sneak into your session without you knowing. I'd need to do some more testing before I can recommend this in good conscience.
If using Chrome.ahk in a work setting, could running Chrome in debug mode make you vulnerable to cyber attack? This is outside my knowledge, so thought I should ask.
In my understanding the chrome debugging protocol was mainly created by Google for testing purposes, and perhaps not so much for everyday use (I might be wrong). But yes, my guess is that running Chrome in debug mode is most likely less safe than not running it this way. I have never looked into it, though. Sorry.
User avatar
submeg
Posts: 326
Joined: 14 Apr 2017, 20:39
Contact:

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

01 Jun 2021, 04:41

But there might be other ways 🤷‍♂️ Perhaps something with javascript, run via Chrome.ahk ?
Nice suggestion @gregster! I took a look for this and found (the same thing here, and here, and here:

Code: Select all

this.print (false, this.pageNum, this.pageNum);
I then tried to test this Javascript in Chrome to make sure it actually works, but it was just bringing up the print dialgoue box anyway? ¯\_(ツ)_/¯
____________________________________
Check out my site, submeg.com
Connect with me on LinkedIn
Courses on AutoHotkey :ugeek:
neogna2
Posts: 586
Joined: 15 Sep 2016, 15:44

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

14 Jun 2021, 16:09

Is there a way to click "ok" in an alert popup when running Chrome.ahk headless? I'm accessing a website (behind an account so can't link it here) and click() on a button element on the page. The page then shows an alert popup and I want to do the equivalent of clicking "ok" on that alert, which is needed for the page to load new data that I want to work with.

edit: Some answers on https://stackoverflow.com/questions/563890/is-there-a-way-to-simulate-a-click-on-an-alert-in-javascript suggests insert js code that overrides the alert's default functionality, but I don't know if Chrome.ahk has other ways to deal with the alert.
neogna2
Posts: 586
Joined: 15 Sep 2016, 15:44

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

14 Jun 2021, 17:02

burque505 wrote:
14 Jun 2021, 16:17
@neogna2, you might have a look at the posts on this page for a possible solution.
Thanks, your code example here which gets a second instance and uses a callback function worked for me in some quick non-headless tests. I'll keep testing with that approach in headless mode. Edit: it works headless too.
neogna2
Posts: 586
Joined: 15 Sep 2016, 15:44

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

15 Jun 2021, 11:23

@burque505 , I noticed your script has a close down routine with many steps. I don't see a lingering conhost.exe in Process Explorer after ChromeInst.Kill() and WinKill, chrome.exe so perhaps steps related to that are only needed in special cases? Also why is the taskkill line surrounded by lines that start another cmd window, does AttachConsole to it and afterwards closes its process? Copied from your script:

Code: Select all

PageInstance.Call("Browser.close")
PageInstance.Disconnect()
PageInstance := ""
ChromeInstance.Kill()
WinKill, chrome.exe
; Kill conhost.exe so it doesn't hang around.
DetectHiddenWindows, On
; From GeekDude's tips and tricks: https://www.autohotkey.com/boards/viewtopic.php?f=7&t=7190
Run, cmd,, Hide, PID
WinWait, ahk_pid %PID%
DllCall("AttachConsole", "UInt", PID)
; Run another process that would normally
; make a command prompt pop up, such as
; RunWait, cmd /c dir > PingOutput.txt
Runwait, taskkill /im conhost.exe /f 
; Thanks to @flyingDman post from 2010, 
; https://autohotkey.com/board/topic/49732-kill-process/
; Close the hidden command prompt process
Process, Close, %PID%
ExitApp
burque505
Posts: 1731
Joined: 22 Jan 2017, 19:37

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

15 Jun 2021, 11:29

@neogna2, on my Win7 Pro SP1 installation I am plagued by lingering conhost.exe and cmd.exe processes when using Chrome.ahk. The taskkill surrounding code is to keep the cmd window from appearing. By all means, if you don't experience those problems comment out those lines.
neogna2
Posts: 586
Joined: 15 Sep 2016, 15:44

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

16 Jun 2021, 07:47

burque505 wrote:
15 Jun 2021, 11:29
@neogna2, on my Win7 Pro SP1 installation I am plagued by lingering conhost.exe and cmd.exe processes when using Chrome.ahk. The taskkill surrounding code is to keep the cmd window from appearing. By all means, if you don't experience those problems comment out those lines.
Ok good to know. I see no lingering conhost.exe or cmd.exe processes on my Windows 10 PC.

Some more questions, directed at everyone, about shutting down Chrome.ahk scripts. All of GeekDude's GitHub examples do variants of

Code: Select all

; --- Close the Chrome instance ---
try
	PageInst.Call("Browser.close") ; Fails when running headless
catch
	ChromeInst.Kill()
PageInst.Disconnect()
ExitApp
return
However so far in my tests in Win10 PageInst.Call("Browser.close") works also in headless. I'm using teadrinker's tdChrome.ahk .

Is the "fails when running headless" issue only for some older version of Windows and/or Chrome?

About PageInst.Disconnect() the Chrome.ahk source says
Disconnect from the page's debug interface, allowing the instance to be garbage collected.
This method should always be called when you are finished with a page or else your script will leak memory.
But isn't the memory released when the script exits with ExitApp anyway, making Disconnect() redundant there?

Now some scattered observations.

1. I have when testing stuff seen a few cases where a chrome.exe process lingers after the AutoHotkey script exits which I think (not sure though) was caused by trying to run multiple Chrome.ahk scripts at the same time and it happened both with headless and non-headless mode.

2. If the Microsoft tool Process Explorer is running and filtered to processes with name "chrome.exe" then starting a Chrome.ahk script causes Process Explorer to close. Weird and I don't know why that happens. Doesn't happen when no process name filtering is applied.

3. At one time I noticed a second chrome.exe process which was running with the parameter --type=crashpad-handler. Crashpad is a crash-reporting system and it seems using --headless enables crash reporting by default and makes Chrome upload crash data to Google's servers. There is another parameter --disable-crash-reporter which is said to override that behaviour.

Return to “Scripts and Functions (v1)”

Who is online

Users browsing this forum: JoeWinograd, TOTAL and 137 guests