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

Post your working scripts, libraries and tools for AHK v1.1 and older
SuperJames
Posts: 1
Joined: 28 Apr 2018, 10:15
Contact:

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

12 Oct 2018, 16:35

Thanks for the library GeekDude!

My question: Can I run multiple instances of this class? I would like to have many controllable windows open at the same time.

I tried this, but failed.

Code: Select all

#include <External\Chrome>

; Create an instance of the Chrome class using
; the folder ChromeProfile to store the user profile
FileCreateDir, ChromeProfile
ChromeInst := new Chrome("ChromeProfile")

FileCreateDir, ChromeProfile2
ChromeInst_1 := new Chrome("ChromeProfile2")

; Connect to the newly opened tab and navigate to another website
; Note: If your first action is to navigate away, it may be just as
; effective to provide the target URL when instantiating the Chrome class
PageInstance := ChromeInst.GetPage()
PageInstance.Call("Page.navigate", {"url": "https://autohotkey.com/"})
PageInstance.WaitForLoad()
PageInstance.Evaluate("alert('Hello World!');")

PageInstance_1 := ChromeInst_1.GetPage()
PageInstance_1.Call("Page.navigate", {"url": "https://google.com/"})
PageInstance_1.WaitForLoad()
PageInstance_1.Evaluate("alert('Hello World 2!');")

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

PageInstance_1.Call("Browser.close")
PageInstance_1.Disconnect()

ExitApp
return
chngrcn
Posts: 190
Joined: 29 Feb 2016, 08:55

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

17 Oct 2018, 07:14

Code: Select all

FileAppend % PageInstance.Evaluate("document.documentElement.outerHTML"), C:\Test.txt
when I tried this code, it did not return the page's HTML code to the "test.txt" file. How should I try a code to get the page's HTML code?
User avatar
Xtra
Posts: 2750
Joined: 02 Oct 2015, 12:15

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

17 Oct 2018, 10:43

PageInstance.Evaluate("document.getElementsByTagName('html')[0].textContent;").Value
User avatar
jeeswg
Posts: 6902
Joined: 19 Dec 2016, 01:58
Location: UK

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

30 Oct 2018, 22:25

- I have been experimenting with Chrome.ahk for the first time, and have two queries re. my script below:
- Is there a way to make the tab visible when creating an instance. (And create multiple tabs on one window.)
- Is there a way to list all tabs. Thanks.

Code: Select all

#Include ../Chrome.ahk

q:: ;run Chrome in debug mode
Run, chrome.exe --remote-debugging-port=9222
return

w:: ;attempt at listing all tabs (only listed one tab)
for vKey, oPage in Chrome.GetPageList()
	MsgBox, % oPage.type "`r`n" oPage.title "`r`n" oPage.url

PageInst := Chrome.GetPage(1)
vUrl := PageInst.Evaluate("document.URL;").Value
;vUrl := PageInst.Evaluate("window.location.href;").Value
vTitle := PageInst.Evaluate("document.title;").Value
MsgBox, % vTitle "`r`n" vUrl
return

e:: ;open a tab (but tab was not visible)
ChromeInst := new Chrome("ChromeProfile")
if !(PageInst := ChromeInst.GetPage())
{
	MsgBox, Could not retrieve page!
	ChromeInst.Kill()
}
else
{
	PageInst.Call("Page.navigate", {"url": "https://autohotkey.com/"})
	PageInst.WaitForLoad()
	vUrl := PageInst.Evaluate("document.URL;").Value
	;vUrl := PageInst.Evaluate("window.location.href;").Value
	vTitle := PageInst.Evaluate("document.title;").Value
	MsgBox, % vTitle "`r`n" vUrl
	try
		PageInst.Call("Browser.close") ; Fails when running headless
	catch
		ChromeInst.Kill()
	PageInst.Disconnect()
}
return
homepage | tutorials | wish list | fun threads | donate
WARNING: copy your posts/messages before hitting Submit as you may lose them due to CAPTCHA
Gh0sTG0
Posts: 55
Joined: 25 Jun 2018, 07:58

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

19 Nov 2018, 08:52

Hi! TY for nice lib. I have one problem with it.
I'm using A:=PageInst.Evaluate("document.getElementsByClassName...").Value and sometimes it stuck.
When I double click script in tray it's window is full of 244: While,!this.responses[ID] 245: Sleep,50 (0.05).
So, I find that place in script and... where's your safety for if page NOT responses?
Added some safety into it, from 242:

Code: Select all

; Wait for the response
			this.responses[ID] := False
			Flag := 0
			while !this.responses[ID]
			{
				Flag += 1
				Sleep, 50
				If (Flag > 100)
				{
					throw Exception("Chrome lag and not sending responce")
					Return
				}
			}
This will try that for 5 seconds and return Error if chrome lags
PS 1) I tried waiting. I left it stuck for ~1hour and nothing
2) I had this stuck earlier. And now, after I made clean reinstall of my win10x64 and clean install of Chrome

PPS can someone check my code for correct working?
Gh0sTG0
Posts: 55
Joined: 25 Jun 2018, 07:58

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

24 Nov 2018, 15:37

Next thing I find: sometime when I use PageInst := Chrome.GetPage(1) it stuck too.
I add some Tooltips, X where X is number, so I know, that ahk shows me ToolTip 1 just before getpage. Then there's tooltip 2, that not shows
r2997790
Posts: 71
Joined: 02 Feb 2017, 02:46

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

29 Dec 2018, 05:58

Hi everyone

I'm trying to hide some elements, by TagName or Class Name, but I seem to have the syntax wrong. Could someone please help me understand the right syntax with this super AHK class from @geekdude? Thank you!

PageInstance.Evaluate(document.getElementsByTagName("h1").style.display = none)

PageInstance.Evaluate(document.getElementsByTagName("h1")[0].style.display = none)

PageInstance.Evaluate(document.getElementsByClassName("example").style.display = none)

PageInstance.Evaluate(document.getElementsByClassName("example")[1].style.display = none)

Thanks!
teadrinker
Posts: 4325
Joined: 29 Mar 2015, 09:41
Contact:

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

29 Dec 2018, 06:23

Hi r2997790

When you use Evaluate() you must pass a javascript-code string and keep right js-syntax. This should work:

Code: Select all

PageInstance.Evaluate("document.getElementsByTagName('h1')[0].style.display = 'none';")
r2997790
Posts: 71
Joined: 02 Feb 2017, 02:46

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

29 Dec 2018, 07:19

teadrinker wrote:
29 Dec 2018, 06:23
Hi r2997790

When you use Evaluate() you must pass a javascript-code string and keep right js-syntax. This should work:

Code: Select all

PageInstance.Evaluate("document.getElementsByTagName('h1')[0].style.display = 'none';")
--- Works like a dream! Thank you @teadrinker!
SupposedToBeWorking
Posts: 34
Joined: 08 Mar 2017, 16:15

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

17 Jan 2019, 11:59

I can not figure out what I am doing wrong to get values from elements in Chrome. Any help is appreciated!

Code: Select all


#Persistent
#SingleInstance, force
#NoEnv
SetWorkingDir, %A_ScriptDir%
SetBatchLines, -1
#Include Chrome.ahk

url=https://teams.microsoft.com

FileCreateDir, ChromeProfile
ChromeInst := new Chrome("ChromeProfile" , url, "")
PageInst := ChromeInst.GetPageByURL(url,,, "Callback")

Loop
{
	MsgBox, % PageInst.Evaluate("document.getElementsByTagName('html')[0].textContent;").Value
	Sleep 1000
}


Return

Msgbox is always empty.


EDIT

I did the following and it worked.

Code: Select all

#Persistent
#SingleInstance, force
#NoEnv
SetWorkingDir, %A_ScriptDir%
SetBatchLines, -1
#Include Chrome.ahk

url=https://teams.microsoft.com

; OPEN CHROME AND CONNECT TO PAGE 
FileCreateDir, ChromeProfile
ChromeInst := new Chrome("ChromeProfile" , url, "")
Try
{
	Sleep 5000
	PageInst := ChromeInst.GetPageByURL(url,,, "Callback")
}
Catch
{
	Sleep 5000
	PageInst := ChromeInst.GetPageByURL(url,,, "Callback")
}
PageInst.Call("Console.enable") 						;watch the console for messages served via javascript
if !(PageInst := ChromeInst.GetPage())
{
	MsgBox, Could not retrieve page!
	ChromeInst.Kill()
}
else
{
	PageInst.WaitForLoad()
}



clickCreateSessionDate = 
(
	var allPostsArrayLength = document.querySelectorAll(".ts-message").length
	var allPostsArrayLength = allPostsArrayLength-1
	var mostRecentPostText = document.querySelectorAll(".ts-message")[allPostsArrayLength].children[0].innerHTML
	alert(mostRecentPostText)
)
msgbox, ready?

Loop, 5
{
	MsgBox, % PageInst.Evaluate("document.querySelectorAll('.ts-message')[1].children[0].innerHTML;").Value
	PageInst.Evaluate(clickCreateSessionDate)
	Sleep 1000
}
ExitApp
The difference is in these lines:

Code: Select all

ChromeInst := new Chrome("ChromeProfile" , url, "")
Try
{
	Sleep 5000
	PageInst := ChromeInst.GetPageByURL(url,,, "Callback")
}
Catch
{
	Sleep 5000
	PageInst := ChromeInst.GetPageByURL(url,,, "Callback")
}
PageInst.Call("Console.enable") 						;watch the console for messages served via javascript
if !(PageInst := ChromeInst.GetPage())
{
	MsgBox, Could not retrieve page!
	ChromeInst.Kill()
}
else
{
	PageInst.WaitForLoad()
}
Stavencross
Posts: 90
Joined: 24 May 2016, 16:42

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

20 Jan 2019, 09:45

SuperJames wrote:
12 Oct 2018, 16:35
Thanks for the library GeekDude!

My question: Can I run multiple instances of this class? I would like to have many controllable windows open at the same time.

I tried this, but failed.

Code: Select all

#include <External\Chrome>

; Create an instance of the Chrome class using
; the folder ChromeProfile to store the user profile
FileCreateDir, ChromeProfile
ChromeInst := new Chrome("ChromeProfile")

FileCreateDir, ChromeProfile2
ChromeInst_1 := new Chrome("ChromeProfile2")

; Connect to the newly opened tab and navigate to another website
; Note: If your first action is to navigate away, it may be just as
; effective to provide the target URL when instantiating the Chrome class
PageInstance := ChromeInst.GetPage()
PageInstance.Call("Page.navigate", {"url": "https://autohotkey.com/"})
PageInstance.WaitForLoad()
PageInstance.Evaluate("alert('Hello World!');")

PageInstance_1 := ChromeInst_1.GetPage()
PageInstance_1.Call("Page.navigate", {"url": "https://google.com/"})
PageInstance_1.WaitForLoad()
PageInstance_1.Evaluate("alert('Hello World 2!');")

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

PageInstance_1.Call("Browser.close")
PageInstance_1.Disconnect()

ExitApp
return
Its been a bit since I played with chrome.ahk but yes you can run up to 5 instances of the class before it starts to fatal err on you ( +/- 1, it gets finicky)

If I recall correctly - you don't need to call a second chrome profile

Code: Select all

ChromeInst_1 := new Chrome("ChromeProfile2")
try

Code: Select all

ChromeInst_1 := new Chrome("ChromeProfile")
Not sure this is the full answer you need but it might start you on the right path
terrypaton2
Posts: 30
Joined: 03 Aug 2018, 20:35

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

13 Apr 2019, 23:24

I am creating a mini ahk tool for my jobs, I want to Autohotkey will be return a msgbox when chrome browser creating a new tab.
how I can detect if a new tab onCreate ?
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!

19 Apr 2019, 10:07

So I've been using this fantastic library at work to automate some mundane copy/paste work and GUI navigation, but have run into a hitch. I'm trying to simplify some of the code by pulling back multiple data points from a JSON response in a single jQuery, vs having to run the same jQuery multiple times to capture each needed data point, but can't seem to capture the data via ".Value".
Sample of the code I'm trying to run:

Code: Select all

TicketInfo := TicketData.Evaluate("function ticketInfo() {var data = $.ajax({type: ""GET"", url: ""https blahblahblah "", async: false}).responseText; var obj = JSON.parse(data); ticketResult = [obj.results[0].id,obj.results[0].group_id]; return ticketResult;} ticketInfo();").Value
When I run this via console, it is returning each JSON element asked for, but TicketInfo doesn't seem to get populated with anything when executed. I've wrapped the evaluate script in an Array() (i.e. Array(TicketData.Evaluate...) as well as StrSplit an array .Push, and am still unable to capture any of the returned data. Is there something besides the ".Value" element that needs to be given to capture an Object/Array response properly? Originally didn't have the above wrapped in a function, but have been implementing try/catches (just not added to the above yet) to ensure smooth operation in the event of an error.
Last edited by kagato on 26 Apr 2019, 07:34, edited 1 time in total.
Chuck Norris doesn't need garbage collection because he doesn't call .Dispose(), he calls .DropKick().
reverberation
Posts: 314
Joined: 13 Dec 2015, 20:48

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

19 Apr 2019, 23:59

Hi guys,

noob here. Is there any place that collates all the interesting use-cases / pre-made scripts working along with Chrome.ahk?

For starters, how do I implement a WinWait function reliably once a username/password field is detected and proceed to fill in the credentials?
SupposedToBeWorking
Posts: 34
Joined: 08 Mar 2017, 16:15

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

29 May 2019, 10:42

I am just at the beginning of creating this script, but "PageInst := ChromeInst.GetPage()" seems to be failing, see my example below:

Code: Select all

#Persistent
#SingleInstance, force
#NoEnv
SetBatchLines, -1
SetTitleMatchMode, 2
SetWorkingDir, %A_ScriptDir%
#Include Chrome.ahk

;-----------CREATE CHROME OBJECT--------------------
FileCreateDir, ChromeProfile
ChromeInst := new Chrome("ChromeProfile","https://www.google.com/", "")

while !(PageInst := ChromeInst.GetPageByURL("https://www.google.com/",,, "Callback"))
{
	tooltip, could not retrieve page!
	Sleep 1000
	PageInst := ChromeInst.GetPageByURL("https://www.google.com/",,, "Callback")
}
tooltip, connected to page!
PageInst.WaitForLoad()

;----------EXECUTE JAVASCRIPT--------
PageInst.Evaluate("alert('Hello World!');")

Return
Thanks!
gregster
Posts: 8991
Joined: 30 Sep 2013, 06:48

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

29 May 2019, 17:16

SupposedToBeWorking wrote:
29 May 2019, 10:42
I am just at the beginning of creating this script, but "PageInst := ChromeInst.GetPage()" seems to be failing, see my example below:
What means "seems to be failing"? What happens?

There seems to be no callback function in your code, still you are referencing one - I guess that could lead to an error. Remove "Callback" from the parameters. Edit: No, doesn't seem to be a problem.

Also, the second PageInst := ChromeInst.GetPageByURL(...) seems redundant (, but it shouldn't cause a problem).
On my old computer, adding a Winwait, Google Chrome after the new Chrome( ) line seems to improve reliability. It still seems that a if you call GetPageByURL before the page is available, you will get an error message...

Perhaps this is better:

Code: Select all

;[...]
ChromeInst := new Chrome("ChromeProfile","https://www.google.com/")
Winwait, Google Chrome

loop
{
	try PageInst := ChromeInst.GetPageByURL("https://www.google.com/",,, "Callback")
	if PageInst
		break
	Sleep 1000
}
;[...]
SupposedToBeWorking
Posts: 34
Joined: 08 Mar 2017, 16:15

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

30 May 2019, 08:09

gregster wrote:
29 May 2019, 17:16
What means "seems to be failing"? What happens?
I mean that the JavaScript "Alert" never executes, and the Tooltip never says "connected to page!".

I tried using your code and again when PageInst is evaluated it's never true. I made some changes and tried this:

Code: Select all

...
	FileCreateDir, ChromeProfile
	ChromeInst := new Chrome("ChromeProfile","https://www.google.com/"," --remote-debugging-port=9222 --disable-web-security --user-data-dir=ChromeProfile")

	h_WinTitle:="Google - Google Chrome" 
	WinWait, % h_WinTitle
	WinGet, h_WinID, ID, % h_WinTitle
	h_WinID := "ahk_id " . h_WinID

	while !(PageInst := ChromeInst.GetPage())
	{
		tooltip, could not retrieve page!
		Sleep 1000
	}
	tooltip, connected to page!
	PageInst.WaitForLoad()

	;----------EXECUTE JAVASCRIPT--------
	PageInst.Evaluate("alert('Hello World!');")
	Return
...
This one waits for page to open as you suggested. I also followed the instructions here to set Chrome in debug mode. Does this work for you? If so, might be an issue with my Chrome? I thinks it's worth noting I can't run the examples provided by geekDude either, same issue. Thanks for your help!
bmilcs
Posts: 11
Joined: 27 Feb 2017, 13:54

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

30 May 2019, 13:40

How can I modify this script to work with a Chrome-based browser other than Google Chrome?

Or more simply, alter the code to use a different file location other than the default Google Chrome one.

Goal: Brave browser.

Thanks!
Stavencross
Posts: 90
Joined: 24 May 2016, 16:42

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

31 May 2019, 14:37

Today I figured out how to exit the script when you exit the browser, useful for running cleanup functions, or if you wanted to run another script when you close the browser. See below. This also shows you how to run chrome.ahk with callbacks & in app mode. It also shows you how you can call AHK functions from chrome with javascript. Note that I didn't actually include the event_ExitFunction() function.

Code: Select all

;START GUI CREATION
FileCreateDir, ChromeProfile ;create a debugging profile of chrome
ChromeInst := new Chrome("ChromeProfile", "--app=http://localhost/index.php") ;We'll run chrome in "app" mode, which strips out all the UI buttons. We can run a reg instance by removing --app=
sleep, 3000
PageInst := ChromeInst.GetPageByURL("http://localhost/index.php",,, "event_Callback") ;connect chrome.ahk to the google chrome tab
PageInst.Call("Console.enable") ;watch the console for messages served via javascript, this is how our server will communicate.
return

event_Callback(Event)
{
	;This callback method is what allows us to watch the HTML GUI for AHK function calls. we'll log func calls and their params in the console and run it from there.
	if (Event.Method == "Console.messageAdded"  && InStr(Event.params.message.text,"AHK:") >= 1) ;we only want to run our function if the console message is prefixed with AHK:, however, you can change this if you want.	
	{		
		;Here's an example of a call from JS to AHK console.log("AHK:helper_spitMessage,hello world!");
		Text := Event.params.message.text ;grab the console's message					
		Split := StrSplit(Text, ",","AHK:") ;Turn our console message into an array, but we'll drop the AHK: from it, delimit on commas				
		fnName := Split[1] ;Grab the name of our function			
		Split.RemoveAt(1) ;Drop function name from the array, all we need now are the params.
		%fnName%(Split*) ; Call that function, passing in the rest of the array as parameters
 	} else if(Event.Method == "Inspector.detached") { ;capture browser closing, we can save stuff to our local files before closing.
		event_ExitFunction()
	}
}

helper_spitMessage(msg) {
	msgBox, %msg% ;We'll show a messagebox with the first param you sent thru your console.
}


Return to “Scripts and Functions (v1)”

Who is online

Users browsing this forum: KruschenZ and 58 guests