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

Post your working scripts, libraries and tools for AHK v1.1 and older
densch
Posts: 120
Joined: 29 May 2018, 15:10

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

04 Mar 2020, 15:53

I tried using it but even something as simple as
#Include Chrome.ahk

a:=Chrome.FindInstances()
Msgbox, % a

doesn't work! >:'O

Obviously I had started chrome by entering
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --remote-debugging-port=9222
in the command line but
it just opens an empty messagebax!
(while it should show true or false)

what am I doing wrong?

the more I try it, the more I think that chrome.ahk is just broken as hell and cant be used >:-(
densch
Posts: 120
Joined: 29 May 2018, 15:10

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

04 Mar 2020, 16:22

I now did the following:
#Include Chrome.ahk

Chromes := Chrome.FindInstances()
Length := Chromes.Length()
Chrome := Chromes[9222]


Msgbox, % Chrome


this does give me a msgbox with the command line text that was probably used to create the current running chrome thing.

but I still fail to see what exactly some random commandline text and connecting to an existing season have to do with each other.


According to the chrome.ahk commentary,
now something like

ChromeInst := {"base": Chrome, "DebugPort": Chromes.MinIndex()}
should build the connection to the running season.

even though it's jsut a fancy way of saying, "Yo, the running session has the debug port .... and the thing we call base for whatever eeason is chrome.
whatever this "chrome" is meant to be.
obviously nop object of the chrome class as it hasnt been initialized at all.
it is jsut some undefined term there.

or it just refers to the chrome class as is.

like saying "Yo, it's a house"

but this still has no connection to some actual house, sitting at adress.... , with this and that inside,
and I cant dig into that specific house object I am interested either.

cause the sentence "Yo, it's a hosue" doesnt connect shit to the actually wanted, specific house object that I would work on.

so I somehow fail to see how I sentence like "the sun is round" can even be remotely(!) create a connection to the specific sun object, llocated at the galaxy whatever, and allow me to manipulate some sun.

it's a piece of worthless info, and no actual connection.
gregster
Posts: 8886
Joined: 30 Sep 2013, 06:48

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

07 Mar 2020, 01:46

densch, I answered in your other topic, but it makes probably sense to repeat it here for other users having difficulties connecting to an already running Chrome debug instance:
gregster wrote:
07 Mar 2020, 01:29
[...] currently, you'll have to use FindInstances() to connect to an already running debug instance first; and running as admin hasn't been necessary for me.

If I start Chrome, for example, via run chrome.exe "--remote-debugging-port=9222" in AHK (you could use a shortcut instead), it starts my Chrome with my
default profile in debugging mode. There is no obvious indicator that it is now in debug mode, but you can check, if the protocol is active by, for example, pasting or writing http://localhost:9222/json/version in the address field (assuming you used port 9222).

If you are in debug mode, you should see now a page with a json response that says something like this:

Code: Select all

{
   "Browser": "Chrome/80.0.3987.132",
   "Protocol-Version": "1.3",
   "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36",
   "V8-Version": "8.0.426.26",
   "WebKit-Version": "537.36 (@fcea73228632975e052eb90fcf6cd1752d3b42b4)",
   "webSocketDebuggerUrl": "ws://localhost:9222/devtools/browser/e8562bbb-2048-45fd-a0b5-5edb4adcc6f7"
}
If you are in "normal" mode, it will say "Page not found" or something similar. In that case, the chrome debugging protocol is not active and Chrome.ahk cannot be used. You will need to (re-)start Chrome in debug mode first.

So, if you are in debug mode, this should work:

Code: Select all

#NoEnv
SetBatchLines, -1
SetTitleMatchMode 2
#Include Chrome.ahk											; https://www.autohotkey.com/boards/viewtopic.php?f=6&t=42890

url  := "https://www.autohotkey.com/boards/"

if (Chromes := Chrome.FindInstances())
			ChromeInst := {"base": Chrome, "DebugPort": Chromes.MinIndex()}	; or if you know the port:  ChromeInst := {"base": Chrome, "DebugPort": 9222}
		else
			msgbox That didn't work. Please check if Chrome is running in debug mode.`n(use, for example, http://localhost:9222/json/version )


; --- Connect to the page ---
if !(Page := ChromeInst.GetPage( ))		
{
	MsgBox, Could not retrieve page!
	ChromeInst.Kill()
}
else
	Page.WaitForLoad()

Page.Call("Page.navigate", {"url": url})			; Navigate to url
Page.WaitForLoad()
msgbox Close msgbox to exit script.
ExitApp
I don't think that navigating the DOM via javascript has changed much since the last changes. The latest code examples in the Chrome.ahk thread should still be good.


Not sure, if this is even relevant in this case, but please note that in the Chrome.ahk 1.2 release is a typo in this line:

Code: Select all

RegRead, ChromePath, HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Pahs\chrome.exe
It's missing a t in App Paths and should read instead:

Code: Select all

RegRead, ChromePath, HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe
Better use this version: https://github.com/G33kDude/Chrome.ahk/blob/master/Chrome.ahk (it has two other changes incorporated and was geekdude's latest version)


PS: If you overwrite the Chrome class with something like this: Chrome := Chromes[9222], it cannot work. This is AHK-specific, not Chrome.ahk-specific.
Since AHK v1.1.27+, #Warn is able to warn you about doing this (see WarningType ClassOverwrite):
https://www.autohotkey.com/docs/commands/_Warn.htm#Parameters wrote:ClassOverwrite [v1.1.27+]: Before the script starts to run, show a warning for each assignment targetting a class variable. For example, box := new Box will show a warning if Box is a class, since this would overwrite the class (within the super-global variable, Box). [...]
Tre4shunter
Posts: 139
Joined: 26 Jan 2016, 16:05

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

23 Mar 2020, 09:53

Hey Everyone -

So - i am using the Chrome.ahk on a Terminal Server (Remote Desktop Session Host Server) and ran into an issue...

That being, if multiple users are logged in, and running my App - the FindInstances() funtion doesnt properly list all opened connections to Chrome Debug Ports...this is a permissions issue, because the WMIC cmd function doesnt allow non admins to see other Process Instance full command lines, so i end up with multiple users connecting to each others apps etc etc.


So..i made a sloppy workaround:

Code: Select all

	FindInstances()
	{
	Params := "-ExecutionPolicy Bypass"
	Script := "./InstCh.ps1"
	workingdir := "C:\temp"
	Options := "hide"
	try
	{
		Runwait % "PowerShell.exe " . Params . " -Command &{" . Script . "}", % WorkingDir == "" ? A_ScriptDir : WorkingDir, % Options, PID
		While !FileExist("C:\temp\test.txt")
			sleep, 500
	}catch{
		msgbox, Error - call MD
		return, -1
	}
		fileread,rFile,C:\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":"Blank"}
			}
		}
		FileDelete, C:\temp\test.txt
		return, Out
	}

Here is what is in the PS as well:

Code: Select all

$password = ConvertTo-SecureString "xxxxxxx" -AsPlainText -Force
$Cred = New-Object System.Management.Automation.PSCredential("domain\user", $password)
start-process -WindowStyle hidden -FilePath "$env:comspec" -ArgumentList "/c wmic Process where `"name = 'chrome.exe'`" get commandline > C:\temp\test.txt" -Credential $Cred
Basically - i had to write a powershell script - which opens a cmd prompt with Admin Credentials, run the WMIC command, pipe the output to a txt file - then call that from AHK, read and parse the txt file to see which ports are currently being used.

I know there must be a better way - but i was under a time crunch and this solution does atleast work.

Any ideas on improving this?

Thanks - Stay home and be safe!
bmilcs
Posts: 11
Joined: 27 Feb 2017, 13:54

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

23 Mar 2020, 13:36

gregster wrote:
06 Jan 2020, 19:41
@bmilcs: Well, some webpages don't like to be constantly scraped or automated - for example, Cloudflare protections with waiting times sometimes kick in, if you do automation that is deemed excessive (the individual limits can vary wildly from website to website). If that's the problem, I doubt that Brave can really solve that problem.

But what are these "Access Restricted" errors? Are these from Cloudflare? Can you post an example picture ? I could imagine that there could be a whole lot of reasons - for example: proxies, VPNs, malware, just a "bad" or shared IP or third-party browser extensions (just recently, someone here on the forum identified a browser plugin as the reason for the constant captchas on Youtube he had to solve)

I am not even sure, if Brave supports the chrome debugging protocol - not all chromium-based browsers implement it. The new Edge and Opera do it - but Vivaldi does not, and has no current plans to do so, at least the last time I looked.
So, you should first find that out.

Edit: So far, I can't find any mention of the protocol on the Brave forums. So, I would strongly doubt that it's currently possible with Brave or that it is even in the works.
Image

Apologies for my late response! I didn't get any notifications.

Is there any way of hiding the fact that I'm running Chrome in debugging mode? I am 90% sure this is what web pages are detecting and automatically blocking me afterward.

I can clear my browser history, cache, etc. I'll be allowed in ONCE from a Google Search result, and then all subsequent actions on that site are forwarded to Access Restricted.

I'm forced to essentially copy that "Access Restricted" URL to any other browser, and it resolves correctly. It's immensely frustrating and time consuming.

I'm not doing excessive scraping by any means. In fact, it's quite casual when looking at it objectively. I click a link or two within it, and then move on.
gregster
Posts: 8886
Joined: 30 Sep 2013, 06:48

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

23 Mar 2020, 14:15

bmilcs wrote:
23 Mar 2020, 13:36
Is there any way of hiding the fact that I'm running Chrome in debugging mode? I am 90% sure this is what web pages are detecting and automatically blocking me afterward.

I can clear my browser history, cache, etc. I'll be allowed in ONCE from a Google Search result, and then all subsequent actions on that site are forwarded to Access Restricted.

I'm forced to essentially copy that "Access Restricted" URL to any other browser, and it resolves correctly. It's immensely frustrating and time consuming.

I'm not doing excessive scraping by any means. In fact, it's quite casual when looking at it objectively. I click a link or two within it, and then move on.
Afaik, it's not obvious for a website that you are using the chrome debugging protocol.

I think I remember reading one blog post somewhere where someone had a multi-step process of determining if someone used browser automation via the chrome debugging protocol or similar techniques, but as far as I remember, there were people who heavily doubted that generally this would make sense in practice (afaik, they showed how that desribed detection process would create many false positives and be counter-productive for most websites). Perhaps I can find it again.

I am not aware that websites are really regularly trying to detect users of the chrome debugging protocol, or that there is a reliable method to do so.
Detection of unwanted behaviour, on the other hand, is much more common. I have told this anecdote several times before, but I once got Cloudflare waiting pages for reloading a certain website every 30 minutes (!) - back then I used IE COM, though - before I discvored that this specific page actually offered a free WebAPI :facepalm: .

Generally, though, it might depend on what you are doing - afaik, if you are using javascript's click() method (in IE COM, Selenium or whereever), this can usually be detected as "unstrusted javascript clicks" while there are also ways to create "trusted clicks" via the chrome debugging protocol (using the cdp "Input" domain). In my experience, many websites don't seem to care, though, but I haven't tested much... and don't have the right test case, I guess. Let me see, if I find the example that I posted somewhere - but no idea, if it really would make a difference (here).

Not sure, if I am up-to-date on these topics, but if I discover more on this, I will let you know.
dominicx
Posts: 8
Joined: 16 Aug 2017, 07:53

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

03 Apr 2020, 08:38

This library is great! :). I have one question which I cannot figure out how to solve.

Code: Select all

IfNotExist, %ChromeProfileDirectory%
	FileCreateDir, ChromeProfile

if (Chromes := Chrome.FindInstances())
	ChromeInst := {"base": Chrome, "DebugPort": Chromes.MinIndex()}	; or if you know the port:  ChromeInst := {"base": Chrome, "DebugPort": 9222}
Page.Call("Page.navigate", {"url": url})			; Navigate to url
Page.WaitForLoad()	
If Chrome in the debug mode is already open,above commands are performed in the background without activating Chrome.

How do find Chrome debug mode and use something like WinActivate to activate it?

Code: Select all

FindInstances()
	{
static Needle := "--remote-debugging-port=(\d+)"
		Out := {}
		for Item in ComObjGet("winmgmts:")
			.ExecQuery("SELECT CommandLine FROM Win32_Process"
			. " WHERE Name = 'chrome.exe'")
			if RegExMatch(Item.CommandLine, Needle, Match)
				Out[Match1] := Item.CommandLine
		return Out.MaxIndex() ? Out : False
		}
FindInstance() from the library is going through winmgmts but info from there is useless for the WinActivate because it does not retrieve anything that can be used with WinActivate

I have tried this to see if any attribute for chrome debug would be available in WinGet but none are useful either

Code: Select all

WinGet, ID, list, ahk_class Chrome_WidgetWin_1
Loop, %id%
{
	this_id := id%A_Index%
	WinActivate, ahk_id %this_id%
	WinGetClass, this_class, ahk_id %this_id%
	WinGetTitle, this_title, ahk_id %this_id%
	MsgBox, 4, , Visiting All Windows`n%a_index% of %id%`nahk_id %this_id%`nahk_class %this_class%`n%this_title%`n`nContinue?
	IfMsgBox, NO, break
} 

Please help :)
nativenewyorker
Posts: 9
Joined: 03 Jan 2020, 14:51
Contact:

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

15 Apr 2020, 09:32

Hello,

Looking for a way to automate Goto Meeting Web Opener page by clicking a button in a web broswer.
Not sure but the buttom may in fact be generated via JavaScript.

Questions
  • Can Chrome.ahk automate button clicking in popup in this use case?
  • How does Chrome.ahk compare with Google Puppeteer?
  • How to add URL links to a post on this board. It always returns "Broken Link for safety" on preview using native URL tag or untagged web address.
From an AutoHotKey newbie.
Thank you.
Attachments
2020-04-14 14_17_03-GoToMeeting.png
2020-04-14 14_17_03-GoToMeeting.png (86.11 KiB) Viewed 7990 times
gregster
Posts: 8886
Joined: 30 Sep 2013, 06:48

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

15 Apr 2020, 09:45

nativenewyorker wrote:
15 Apr 2020, 09:32
Looking for a way to automate Goto Meeting Web Opener page by clicking a button in a web broswer.
Not sure but the buttom may in fact be generated via JavaScript.

Questions
  • Can Chrome.ahk automate button clicking in popup in this use case?
  • How does Chrome.ahk compare with Google Puppeteer?
  • How to add URL links to a post on this board. It always returns "Broken Link for safety" on preview using native URL tag or untagged web address.
Ad 1: Probably, but not necessarily beginner level. I haven't used Goto, but if I remember correctly, I have done similar things while testing, a few months ago. I will have to look for the code, but your participation will be needed to determine the details in this case, as I don't have a Goto account. But I can't promise anything.

Are you able to right-click the button/dialog and inspect the source code for it?

Ad 2: Chrome.ahk uses the same API protocol to interface with Chromium-based browsers (at least the ones that support it) like puppeteer - so generally, you can probably do all the things puppeteer can do, but the syntax will be different.

Ad 3: As a new user, you are limited in posting external URLs (thanks to a few nasty spammers), although there is a small whitelist. Just post the broken link, if it's useful. People will work it out, or - if you are lucky - a moderator will come around and fix that link for you. Like you already figured out, for pictures the best workaround is to directly upload them to the forum.
geek
Posts: 1051
Joined: 02 Oct 2013, 22:13
Location: GeekDude
Contact:

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

15 Apr 2020, 14:56

I can't stay long, but I thought some of you may be interested in a method for generalizing Chrome.ahk for use with Firefox. This will ONLY work for Firefox Nightly builds. If you don't want to install Nightly you can grab a portable copy here: https://portableapps.com/apps/internet/firefox-portable-nightly or here: https://archive.mozilla.org/pub/firefox/nightly/latest-mozilla-central/ (look for a file ending in .en-US.win64.zip)

Also note that the same rules with Chrome about profiles, port conflicts, re-launching, etc. seem to apply to FF.

The relevant documentation from Mozilla can be found here: https://firefox-source-docs.mozilla.org/remote/index.html

Image

Code: Select all

#NoEnv
SetBatchLines, -1

; --- Constants ---

PORT := 9222


; --- Includes ---

#Include C:\Users\Geek\git\Chrome.ahk\Chrome.ahk


; --- Entry Point ---

; Patch Chrome.ahk to work with Firefox
Print("Patching Chrome.ahk for FF support")
Chrome.Page.__New := Func("PatchChromePage__New")
Chrome.Page.Websocket.__New := Func("PatchChromePageWebsocket__New")

; Start Firefox
Print("Starting Firefox...")
command =
( LTrim Join%A_Space%
"C:\Users\Geek\Desktop\FirefoxPortableNightly\App\Firefox64\firefox.exe"
-profile "C:\Users\Geek\Desktop\FirefoxPortableNightly\Data\profile"
--remote-debugger localhost:%PORT%
https://autohotkey.com
)
exec := ComObjCreate("WScript.Shell").Exec(command)
loop
	(line := exec.StdErr.ReadLine()) ? Print(line) : ""
until RegExMatch(line, "^DevTools listening", Match) || exec.Status != 0
Print(Match ? "Started!" : "Firefox may already be open")

; Get a list of Firefox pages
Print("Querying Firefox for a list of open pages")
http := ComObjCreate("WinHttp.WinHttpRequest.5.1")
http.open("GET", "http://localhost:" PORT "/json/list")
http.send()
page_list := Chrome.Jxon_Load(http.responseText)

; Get the most recent page
Print("Looking for most recent page")
for i, page in page_list
	if (page.type == "page")
		wsurl := page.webSocketDebuggerUrl
if !wsurl
{
	Print("ERROR: No pages found!")
	ExitApp
}

; Connect to it
Print("Connecting to Firefox page at " wsurl)
Page := new Chrome.Page(wsurl)
Page.Call("Runtime.enable")

; Run some JS
Print("Evaluating JS")
Page.Evaluate("alert('Just Another AutoHotkey Hacker');")

ExitApp
return

Print(p*)
{
	static _ := DllCall("AllocConsole"), conout := FileOpen("CONOUT$", "w")
	for k, v in p
		out .= "`t" v
	conout.write(SubStr(out, 2) "`n")
	conout.__handle
}

PatchChromePage__New(this, wsurl, fnCallback:="", fnClose:="")
{
	this.fnCallback := fnCallback
	this.fnClose := fnClose
	this.BoundKeepAlive := this.Call.Bind(this, "Browser.getVersion",, False)

	this.ws := {"base": this.WebSocket, "_Event": this.Event, "Parent": this}
	this.ws.__New(wsurl)

	while !this.Connected
		Sleep, 50
}

PatchChromePageWebsocket__New(this, WS_URL)
{
	global PORT
	static _wb

	; Create an IE instance
	Gui, +hWndhOld
	Gui, New, +hWndhWnd
	this.hWnd := hWnd
	vIE := FixIE()
	Gui, Add, ActiveX, v_wb, http://localhost:%PORT%/
	wb := _wb
	FixIE(vIE)
	Gui, %hOld%: Default

	while (wb.ReadyState < 4)
		Sleep, 50
	this.document := wb.document

	; Add our handlers to the JavaScript namespace
	this.document.parentWindow.ahk_savews := this._SaveWS.Bind(this)
	this.document.parentWindow.ahk_event := this._Event.Bind(this)
	this.document.parentWindow.ahk_ws_url := WS_URL
	this.document.parentWindow.execScript(""
	. "ws = new WebSocket(ahk_ws_url);"
	. "ws.onopen = function(event){ ahk_event('Open', event); };"
	. "ws.onclose = function(event){ ahk_event('Close', event); };"
	. "ws.onerror = function(event){ ahk_event('Error', event); };"
	. "ws.onmessage = function(event){ ahk_event('Message', event); };")
}

FixIE(Version=0, ExeName="")
{
	static Key := "Software\Microsoft\Internet Explorer"
	. "\MAIN\FeatureControl\FEATURE_BROWSER_EMULATION"
	, Versions := {7:7000, 8:8888, 9:9999, 10:10001, 11:11001}
	
	if Versions.HasKey(Version)
		Version := Versions[Version]
	
	if !ExeName
	{
		if A_IsCompiled
			ExeName := A_ScriptName
		else
			SplitPath, A_AhkPath, ExeName
	}
	
	RegRead, PreviousValue, HKCU, %Key%, %ExeName%
	if (Version = "")
		RegDelete, HKCU, %Key%, %ExeName%
	else
		RegWrite, REG_DWORD, HKCU, %Key%, %ExeName%, %Version%
	return PreviousValue
}
gregster
Posts: 8886
Joined: 30 Sep 2013, 06:48

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

15 Apr 2020, 15:49

Oh, very interesting - and appreciated. Thank you for the information and the code! I will check it out.

So far, I've only tried the new Edge and Opera (both Chromium-based) with Chrome.ahk, but this seems a bit more tricky.
User avatar
joedf
Posts: 8937
Joined: 29 Sep 2013, 17:08
Location: Canada
Contact:

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

16 Apr 2020, 12:43

This is super neat! especially since FF is my main browser. :D

I didn't carefully study the example too much in detail, but why is IE needed in there? :think:
Image Image Image Image Image
Windows 10 x64 Professional, Intel i5-8500, NVIDIA GTX 1060 6GB, 2x16GB Kingston FURY Beast - DDR4 3200 MHz | [About Me] | [About the AHK Foundation] | [Courses on AutoHotkey]
[ASPDM - StdLib Distribution] | [Qonsole - Quake-like console emulator] | [LibCon - Autohotkey Console Library]
geek
Posts: 1051
Joined: 02 Oct 2013, 22:13
Location: GeekDude
Contact:

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

16 Apr 2020, 12:48

All requests from AHK to Chrome (or in this case, FF) have to go through a websocket connection. AHK doesn't have websockets natively so I borrowed the websocket support from IE/ActiveX. It's a cheap trick, and has been causing me no end of issues, but it works.
jadams
Posts: 73
Joined: 13 Mar 2020, 10:48

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

16 Apr 2020, 23:39

Joe Glines wrote:
23 Jan 2018, 08:57
... I've also worked-through getting the OuterHTML (however there doesn't seem to be a way to get InnerText) ...
Just wondering if you could share how you got the outer HTML? And if you also were able to get the intertext, would love to know that :-)
Balovauto
Posts: 4
Joined: 17 Apr 2020, 03:22

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

17 Apr 2020, 03:26

to gregster and everyone:

Do you guys have example to set proxy for chrome ( and firefox ) using ahk ?

Thanks
User avatar
flyingDman
Posts: 2776
Joined: 29 Sep 2013, 19:01

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

17 Apr 2020, 19:32

My printToPDF looks like this:

Code: Select all

	Base64PDF := PageInst.Call("Page.printToPDF",{"printBackground":Chrome.Jxon_True(), "landscape": Chrome.Jxon_True()}).data
I works well but I would like to set the print margins. How would I set those (custom) print margins? What about the margin presets "none" and "minimum" ?
EDIT: this works:

Code: Select all

Base64PDF := PageInst.Call("Page.printToPDF",{"printBackground":Chrome.Jxon_True(), "landscape": Chrome.Jxon_True(), "marginLeft": 0, "marginTop": 0, "marginRight": 0, "marginBottom": 0}).data
, but I cannot set the margins between 0 and 1. 0 works and 1 works but 0.2, for instance, does not work. ????

EDIT # 2: got it to work with this:

Code: Select all

.... "marginLeft": 1/10, "marginTop": 1/10, "marginRight": 1/10, "marginBottom": 1/10, "scale": 8/10}).data
14.3 & 1.3.7
gregster
Posts: 8886
Joined: 30 Sep 2013, 06:48

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

17 Apr 2020, 20:30

@flyingDman :
Yeah, that's somehow about AHK's number format handling and the number format the protocol expects.
I think I always solved it with something like 0.4 + 0.0, if the problem arised in my tests for floating point numbers (or + 0, if there was a problem with integers).
gregster
Posts: 8886
Joined: 30 Sep 2013, 06:48

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

17 Apr 2020, 20:50

Balovauto wrote:
17 Apr 2020, 03:26
to gregster and everyone:

Do you guys have example to set proxy for chrome ( and firefox ) using ahk ?
I haven't tried it myself, but I think you could either use a "normal" command line parameter, when you create a new Chrome instance in Chrome.ahk, via something like --proxy-server=https://proxy-ip:proxy-port (in the third parameter of the New() method) or you could probably create a new Chrome profile first, start it up, change the proxy settings by hand in the advanced settings (or wherever) and then just use that specific profile (via New() again), when you want to use the proxy. The command line option would be more versatile, of course.

I don't think that you can change the proxy on-the-fly via the chrome debugging protocol itself - at least, I haven't seen it yet.

With Firefox probably the same; perhaps the command line option looks a bit different...
User avatar
flyingDman
Posts: 2776
Joined: 29 Sep 2013, 19:01

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

20 Apr 2020, 10:21

For sake of completeness the printToPDF settings can be found here: https://chromedevtools.github.io/devtools-protocol/tot/Page/#method-printToPDF.
I am using this for an application that creates Gantt charts in HTML. This is the printToPDF definition I use:

Code: Select all

Base64PDF := PageInst.Call("Page.printToPDF"
,{"printBackground":Chrome.Jxon_True()
, "landscape": Chrome.Jxon_True()
, "marginLeft": 2.7/10, "marginTop": 6/10
, "marginRight": 2.7/10, "marginBottom": 6/10
, "scale": 8/10, "paperHeight" : 14})		                          ; << paper size; 14 is legal 11 is letter			
.data
14.3 & 1.3.7

Return to “Scripts and Functions (v1)”

Who is online

Users browsing this forum: JoeWinograd and 78 guests