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

Post your working scripts, libraries and tools for AHK v1.1 and older
Tre4shunter
Posts: 139
Joined: 26 Jan 2016, 16:05

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

Post by Tre4shunter » 07 Jul 2021, 14:47

Hey @malcev -

I noticed that as well - and did some testing with it, appears to work fine. I have alot of other scripts still using console. Do you think there are any performance/reliability issues with leaving those programs as is?

malcev
Posts: 1769
Joined: 12 Aug 2014, 12:37

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

Post by malcev » 07 Jul 2021, 15:00

I dont know, but if it is deprecated then it is possible that it will be removed from feature chrome releases.

erohtar
Posts: 20
Joined: 24 Jun 2021, 10:53

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

Post by erohtar » 08 Jul 2021, 08:01

@Tre4shunter
Yeah I had that earlier in my code, and it would always throw an error:

Code: Select all

     Chrome indicated error in response

Specifically: {"code":-32601,"message":"'Console.Enable' wasn't found"}

	Line#
	481: response := this.responses.Delete(ID)
	482: if (response.error)  
--->	483: Throw,Exception("Chrome indicated error in response",, Chrome.Jxon_Dump(response.error))
	485: Return,response.result
So I replaced it and since I got no error, I just left it such.

@malcev Yes! I saw the deprecation message on that page too. But because I'm using an older portable version of Chrome, I figured maybe it's still there on mine - though I didn't dig deeper to see in which version it was dropped, if at all.

Tre4shunter
Posts: 139
Joined: 26 Jan 2016, 16:05

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

Post by Tre4shunter » 08 Jul 2021, 09:33

Not sure why you're getting that error. Im using Runtime now, and here is a snipped of my larger program with listenting to the messages - works excellent.

Code: Select all

Profile := A_Temp "\ChromeProfile"
if !FileExist(Profile)
	FileCreateDir, % Profile
ChromeInst := new Chrome(profile,"--app=" Path, "--window-size=1010," Height " --disable-web-security --test-type --bwsi --disable-component-extensions-with-background-pages","",port)

WinActivate, QuoteFormOriginal
While !WinExist("QuoteFormOriginal")
	sleep, 100

BoundCallback := Func("Callback").Bind()	
PageInstCreate := ChromeInst.GetPageByURL("file:///" StrReplace(Path,"\","/"), "exact",,BoundCallBack)
if !PageInstCreate
{
	ChromeInst.Kill()
	MsgBox, Could not Connect to Quote Page!
	ExitFunc()
}else{
	PageInstCreate.Call("Runtime.enable")
	if(XL.activesheet.name = "quote  ")
	{
		WinShow, % DocTitle
		WinActivate, % DocTitle
	}
}
return

ESC:
ExitFunc()
return

Callback(event){
	GLOBAL
	
	ahkpath := "F:\userfolders\md\autohotkey\autohotkey.exe"
	if(Event.Method = "Runtime.consoleAPICalled"){
		Arg := Event.params.args[1].value

		  InStr(Arg,"AHK:Print") ? Print(Arg) 
		: InStr(Arg,"AHK:OpenSaved") ? SearchQuotes(Arg)
		: InStr(Arg,"AHK:PageReady") ? pageReady()
		: InStr(Arg,"AHK:openconfigselect") ? pageReady(Arg)
		: InStr(Arg,"AHK:OpenQuote") ? OpenQuote(Arg)
		: InStr(Arg,"AHK:PasteTM") ? PasteTMData()
		: InStr(Arg,"AHK:CopyLines") ? (clipboard := StrSplit(Arg,"~:").2)
		: InStr(Arg,"AHK:PasteLines") ? PasteDirectLineItems()
		: InStr(Arg,"AHK:email") ? sendEmail(Arg)
		: InStr(Arg,"AHK:runsiemensservice") ? RunPath(ahkpath " F:\notebook\prices\Configurator_Scripts\QuoteForm\Service\ServiceV2.ahk """ Doctitle """ " ScriptHwnd """", "F:\notebook\prices\Configurator_Scripts\QuoteForm\Service\")
		: InStr(Arg,"AHK:ResetQuote") ? ResetQuote()
		: InStr(Arg,"AHK:Import") ? LoadLines()
		: InStr(Arg,"AHK:openconfig") ? RunPath(ahkpath " F:\notebook\prices\Configurator_Scripts\SiemensConfigurator\SiemensFY18Pricing_WithPIA_H.ahk """ doctitle """", "F:\notebook\prices\Configurator_Scripts\SiemensConfigurator\")
		: InStr(Arg,"AHK:opennewconfig") ? RunPath(ahkpath " F:\notebook\prices\Configurator_Scripts\SiemensConfigurator2021\SiemensSelector.ahk """ Doctitle """ " ScriptHwnd """", "F:\notebook\prices\Configurator_Scripts\SiemensConfigurator2021\")
		: InStr(Arg,"AHK:NoteStamp") ? InsertStamp()
		: InStr(Arg,"AHK:convertOrder") ? Order(Arg)
		: InStr(Arg,"AHK:fillspr") ? RunPath("F:\userfolders\md\autohotkey\autohotkey.exe F:\notebook\prices\Configurator_Scripts\QuoteForm\PIA_SPR.ahk ""."" . """ doctitle """", "F:\notebook\prices\Configurator_Scripts\QuoteForm\OrderForm")
		: ""
	}else if (Event.Method = "Inspector.Detached"){
		ExitFunc()
	}
	return
}

EDIT**** Just realized your error is because its case sensitive. ***********
PageInst.Call("Console.enable") will work, while PageInst.call("Console.Enable") WILL NOT.

Thanks

erohtar
Posts: 20
Joined: 24 Jun 2021, 10:53

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

Post by erohtar » 08 Jul 2021, 11:12

@Tre4shunter
:facepalm:
That was it!! I knew it had to be something silly I was doing! ugh.. sorry!
And thank you so much for pointing it out! :salute:

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 » 09 Jul 2021, 03:35

How many of you run into following error? while making new chrome instance very first time after starting PC,
(ChromeInst := new Chrome( A_ScriptDir "\ChromeProfile")) and then you reload script and re-create ChromeInst and it work without any issue, its only one time case after starting PC, :think: please tell me coz I really wana know about it...!
Image

So what is going on above?:
As far as I know...... When we create ChromeInst := new Chrome( A_ScriptDir "\ChromeProfile") chrome create 1 process chrome.exe (we can check it in task manager) and after that, chrome try to create New tab by putting few more chrome.exe as processes and we know chrome setting up debugging ip and port ( if you using chrome.ahk you can find it all in there), but very first time chrome takes time (idk why its only for first time), and thats where we/I face above error because chrome haven't created that TAB,

thats only my theory not fact chrome dev know more about it

Everyday I have faced above error, I know I gonna face this error running chrome.ahk when ever I make first ChromeInst after starting PC, :headwall: idk this happened to y'all or its only with me, So, I have studied it for weeks and came up with a solution which worked,

Code: Select all

ChromeInst := new Chrome( A_ScriptDir "\ChromeProfile")
WaitforNewChromeProcess() ; all this is doing waiting for new TAB to be created by counting chrome.exe processes
and you can test it something like this, and I was surprised my above theory was correct :HeHe:

Code: Select all

s := ChromeProcessCount()
ChromeInst := new Chrome( A_ScriptDir "\ChromeProfile")
r := WaitforNewChromeProcess()
msgbox, % "Chrome.exe process count:`nBefore creating instance:" s "`n" r
return

WaitforNewChromeProcess(sleep=500)
{
	i := n := ChromeProcessCount()	
	while (n = i)
	{
		sleep, % sleep
		i := ChromeProcessCount()
	}
	return "after creating instance:" n "`nAfter Creating new Tab:" i
}

ChromeProcessCount()
{
	n := 0
	for process in ComObjGet("winmgmts:").ExecQuery("Select * from Win32_Process")
		if( process.Name = "Chrome.exe")
			++n
	return n
}
and thats my result
Image
Hope y'all find this useful, and its common sense while WaitforNewChromeProcess if you close any chrome tab (any mean every chrome tab both created with chrome.ahk or User), above code stop gonna wait and you might face error :angel:
if anyone having same issue please tell me if WaitforNewChromeProcess worked you too?
I should have named this function something like WaitForChromeProcessChange or wfcpc :cookie:
"When there is no gravity, there is absolute vacuum and light travel with no time" -Game changer theory

Tre4shunter
Posts: 139
Joined: 26 Jan 2016, 16:05

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

Post by Tre4shunter » 09 Jul 2021, 07:08

I just do this:

Code: Select all

ChromeInst := new Chrome(profile,"--app=" Path, "--window-size=1010," Height " --disable-web-security,"",port)

WinActivate, QuoteFormOriginal
While !WinExist("QuoteFormOriginal")
	sleep, 100
Seems to work reliably for me each time - just change 'QuoteFormOriginal' to whatever the document title/tab is in your case. obviously, add timeouts or whatnot in case the tab never does exist, etc...

Thanks!

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 » 09 Jul 2021, 07:47

Tre4shunter wrote:
09 Jul 2021, 07:08
Seems to work reliably for me each time - just change 'QuoteFormOriginal' to whatever the document title/tab is in your case. obviously, add timeouts or whatnot in case the tab never does exist, etc...

Thanks!
Nice..! who is not familiar with WinExist().... :D but sadly my web page does not change title and I have more than one chrome instance and every instance has an entirely different task with different sub-url but with same title, you know why did I use approach like this :crazy: but I can assure ComObjGet("winmgmts:") is damn fast,
"When there is no gravity, there is absolute vacuum and light travel with no time" -Game changer theory

Tre4shunter
Posts: 139
Joined: 26 Jan 2016, 16:05

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

Post by Tre4shunter » 09 Jul 2021, 09:35

Are your webpages custom html?

In my case..i have several running too. What I do, is they all start with the same name i.e. "OriginalPage", and there is a function that executes on DOMContentLoaded, which fires a callback to my ahk script -> telling the script that the page is ready to be interacted with. The next action is to change the document.title to a unique identifier for that page i.e. FormPage - %A_TickCount% - which is how I interact with it from that point forward.

Hope that helps!

Thanks

-tre4

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 » 10 Jul 2021, 01:01

Tre4shunter wrote:
09 Jul 2021, 09:35
Are your webpages custom html?

In my case..i have several running too. What I do, is they all start with the same name i.e. "OriginalPage", and there is a function that executes on DOMContentLoaded, which fires a callback to my ahk script -> telling the script that the page is ready to be interacted with. The next action is to change the document.title to a unique identifier for that page i.e. FormPage - %A_TickCount% - which is how I interact with it from that point forward.

Hope that helps!

Thanks

-tre4
The issue is when I set page title using document.title its do changes the visible name/wintitle, but when I get page title var := document.title or WinExist() it remains unchanged, :facepalm: they use something (called crystal report and saps ) beside js and their HTML is also tricky like I have hundreds of div and every div have same ID having single innertext inside two table #id.table.tbody.tr.td.table.tr.td.innerText
"When there is no gravity, there is absolute vacuum and light travel with no time" -Game changer theory

erohtar
Posts: 20
Joined: 24 Jun 2021, 10:53

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

Post by erohtar » 13 Jul 2021, 02:35

I'm just a beginner with javascript, but shouldn't these work?

Code: Select all

;1
js = myFunc(); function myFunc() {const json = '{"result":true, "count":42}'; const obj = JSON.parse(json); return obj.count;};
msgbox % pageInst.Evaluate(js)

;2
js = myFunc(); function myFunc() {const json = '{"result":true, "count":42}'; const obj = JSON.parse(json); return obj;};
ret := pageInst.Evaluate(js)
msgbox % ret["count"]

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 » 13 Jul 2021, 03:21

erohtar wrote:
13 Jul 2021, 02:35
I'm just a beginner with javascript, but shouldn't these work?

Code: Select all

;1
js = myFunc(); function myFunc() {const json = '{"result":true, "count":42}'; const obj = JSON.parse(json); return obj.count;};
msgbox % pageInst.Evaluate(js)

;2
js = myFunc(); function myFunc() {const json = '{"result":true, "count":42}'; const obj = JSON.parse(json); return obj;};
ret := pageInst.Evaluate(js)
msgbox % ret["count"]
by doing pageInst.Evaluate(js).value;1 is working for me, to make ;2 work, you need to change parameters of Runtime.evaluate specifically parameter returnByValue you need to change it to true like this "returnByValue": Chrome.Jxon_True() in chrome.ahk

read my following post, there I passed a function to read a table and save it as array and using eval_obj() to extract it
https://www.autohotkey.com/boards/viewtopic.php?f=6&t=42890&start=360#p382858
"When there is no gravity, there is absolute vacuum and light travel with no time" -Game changer theory

erohtar
Posts: 20
Joined: 24 Jun 2021, 10:53

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

Post by erohtar » 13 Jul 2021, 08:15

@Xeo786 Thank you! That .value correction and your function are very helpful! :)

erohtar
Posts: 20
Joined: 24 Jun 2021, 10:53

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

Post by erohtar » 13 Jul 2021, 09:19

What is the way to retrieve an object contents that's written to the console?
Say I wanted to retrieve sender and value here.

Code: Select all

<button onclick="console.log({'sender':'button1', 'value':'clicked'})">Click Me!</button>
msgbox % Event.params.message.text ;this gives me [object Object]

Edit: One roundabout way is to do this

Code: Select all

<button onclick="var x = {'sender':'button1', 'value':'clicked'}; console.log(JSON.stringify(x))">Click Me!</button>
and receive the string and then parse/convert it to an AHK object, but that's not ideal.

@Xeo786
FWIW I restarted after several days today, and got that error too that you mentioned above.

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 » 14 Jul 2021, 01:21

erohtar wrote:
13 Jul 2021, 09:19
What is the way to retrieve an object contents that's written to the console?
Say I wanted to retrieve sender and value here.

Code: Select all

<button onclick="console.log({'sender':'button1', 'value':'clicked'})">Click Me!</button>
msgbox % Event.params.message.text ;this gives me [object Object]
You can use element.getAttribute('onclick') and then you can parse the result to extract sender value
"When there is no gravity, there is absolute vacuum and light travel with no time" -Game changer theory

erohtar
Posts: 20
Joined: 24 Jun 2021, 10:53

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

Post by erohtar » 14 Jul 2021, 03:10

@Xeo786
Hahha that's simple and efficient! Thank you!

AHK_user
Posts: 515
Joined: 04 Dec 2015, 14:52
Location: Belgium

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

Post by AHK_user » 18 Jul 2021, 14:31

:dance: :dance: :dance:
I figured out a method to improve the speed of the evaluate function.
When the return value becomes large, it can take some seconds to retrieve the data.
A workarround is to quickly copy the data to the clipboard.

Is this the best way to retrieve data, or is there a better/cleaner/faster way :think:?

Code: Select all

js =
(
var dummy = document.createElement("textarea");
document.body.appendChild(dummy);
dummy.value = document.documentElement.outerHTML;
dummy.select();
document.execCommand("copy");
document.body.removeChild(dummy);
)

ClipboardSaved := ClipboardAll
Clipboard:=""
ArrElements := page.Evaluate(js).value
ClipWait
result:= Clipboard
Clipboard := ClipboardSaved
ClipboardSaved := ""

malcev
Posts: 1769
Joined: 12 Aug 2014, 12:37

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

Post by malcev » 18 Jul 2021, 15:02

Use teadrinker`s json parser.

AHK_user
Posts: 515
Joined: 04 Dec 2015, 14:52
Location: Belgium

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

Post by AHK_user » 18 Jul 2021, 15:44

malcev wrote:
18 Jul 2021, 15:02
Use teadrinker`s json parser.
Do you mean that it is best to modify the evaluate function of Chrome?

malcev
Posts: 1769
Joined: 12 Aug 2014, 12:37

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

Post by malcev » 18 Jul 2021, 16:24

No, this will not modify evaluate function, but increase speed of chrome response decoding
GeekDude uses Coco json parser which is very slow.
https://www.autohotkey.com/boards/viewtopic.php?p=218916#p218916

Post Reply

Return to “Scripts and Functions (v1)”