Google chrome does not get values

Get help with using AutoHotkey and its commands and hotkeys
Posts: 22
Joined: 16 Apr 2018, 02:07

Google chrome does not get values

19 Sep 2018, 02:30

Hello guys,

I was trying to automate google chrome, but it doesn't get any values from chrome and I am not quit sure what is wrong.

I set all the libraries to chrome.ahk from ""

Just to make sure: I needed to download these : Jxon.ahk, Websocket.ahk, JSON.ahk and put them in chrome.ahk ?

Could anyone who automate google chrome take a look, it would really help me, Thank you guys very very much!!!

Like this?

Code: Select all

#include, \\xx\xx$\MyPersonalData\Desktop\AHK\JSON.ahk

class Chrome
	static DebugPort := 9222
		Escape a string in a manner suitable for command line parameters
		return """" RegExReplace(Param, "(\\*)""", "$1$1\""") """"
		Finds instances of chrome in debug mode and the ports they're running
		on. If no instances are found, returns a false value. If one or more
		instances are found, returns an associative array where the keys are
		the ports, and the values are the full command line texts used to start
		the processes.
		One example of how this may be used would be to open chrome on a
		different port if an instance of chrome is already open on the port
		you wanted to used.
		; If the wanted port is taken, use the largest taken port plus one
		DebugPort := 9222
		if (Chromes := Chrome.FindInstances()).HasKey(DebugPort)
			DebugPort := Chromes.MaxIndex() + 1
		ChromeInst := new Chrome(ProfilePath,,,, DebugPort)
		Another use would be to scan for running instances and attach to one
		instead of starting a new instance.
		if (Chromes := Chrome.FindInstances())
			ChromeInst := {"base": Chrome, "DebugPort": Chromes.MinIndex()}
			ChromeInst := new Chrome(ProfilePath)
		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
		ProfilePath - Path to the user profile directory to use. Will use the standard if left blank.
		URLs        - The page or array of pages for Chrome to load when it opens
		Flags       - Additional flags for chrome when launching
		ChromePath  - Path to chrome.exe, will detect from start menu when left blank
		DebugPort   - What port should Chrome's remote debugging server run on
	__New(ProfilePath:="", URLs:="about:blank", Flags:="", ChromePath:="", DebugPort:="")
		; Verify ProfilePath
		if (ProfilePath != "" && !InStr(FileExist(ProfilePath), "D"))
			throw Exception("The given ProfilePath does not exist")
		this.ProfilePath := ProfilePath
		; Verify ChromePath
		if (ChromePath == "")
			FileGetShortcut, %A_StartMenuCommon%\Programs\Google Chrome.lnk, ChromePath
		if (ChromePath == "")
			RegRead, ChromePath, HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe
		if !FileExist(ChromePath)
			throw Exception("Chrome could not be found")
		this.ChromePath := ChromePath
		; Verify DebugPort
		if (DebugPort != "")
			if DebugPort is not integer
				throw Exception("DebugPort must be a positive integer")
			else if (DebugPort <= 0)
				throw Exception("DebugPort must be a positive integer")
			this.DebugPort := DebugPort
		; Escape the URL(s)
		for Index, URL in IsObject(URLs) ? URLs : [URLs]
			URLString .= " " this.CliEscape(URL)
		Run, % this.CliEscape(ChromePath)
		. " --remote-debugging-port=" this.DebugPort
		. (ProfilePath ? " --user-data-dir=" this.CliEscape(ProfilePath) : "")
		. (Flags ? " " Flags : "")
		. URLString
		,,, OutputVarPID
		this.PID := OutputVarPID
		End Chrome by terminating the process.
		Process, Close, % this.PID
		Queries chrome for a list of pages that expose a debug interface.
		In addition to standard tabs, these include pages such as extension
		configuration pages.
		http := ComObjCreate("WinHttp.WinHttpRequest.5.1")"GET", "" this.DebugPort "/json")
		return this.Jxon_Load(http.responseText)
		Returns a connection to the debug interface of a page that matches the
		provided criteria. When multiple pages match the criteria, they appear
		ordered by how recently the pages were opened.
		Key        - The key from the page list to search for, such as "url" or "title"
		Value      - The value to search for in the provided key
		MatchMode  - What kind of search to use, such as "exact", "contains", "startswith", or "regex"
		Index      - If multiple pages match the given criteria, which one of them to return
		fnCallback - A function to be called whenever message is received from the page
	GetPageBy(Key, Value, MatchMode:="exact", Index:=1, fnCallback:="", fnClose:="")
		Count := 0
		for n, PageData in this.GetPageList()
			if (((MatchMode = "exact" && PageData[Key] = Value) ; Case insensitive
			|| (MatchMode = "contains" && InStr(PageData[Key], Value))
			|| (MatchMode = "startswith" && InStr(PageData[Key], Value) == 1)
			|| (MatchMode = "regex" && PageData[Key] ~= Value))
			&& ++Count == Index)
				return new this.Page(PageData.webSocketDebuggerUrl, fnCallback, fnClose)
		Shorthand for GetPageBy("url", Value, "startswith")
	GetPageByURL(Value, MatchMode:="startswith", Index:=1, fnCallback:="", fnClose:="")
		return this.GetPageBy("url", Value, MatchMode, Index, fnCallback, fnClose)
		Shorthand for GetPageBy("title", Value, "startswith")
	GetPageByTitle(Value, MatchMode:="startswith", Index:=1, fnCallback:="", fnClose:="")
		return this.GetPageBy("title", Value, MatchMode, Index, fnCallback, fnClose)
		Shorthand for GetPageBy("type", Type, "exact")
		The default type to search for is "page", which is the visible area of
		a normal Chrome tab.
	GetPage(Index:=1, Type:="page", fnCallback:="", fnClose:="")
		return this.GetPageBy("type", Type, "exact", Index, fnCallback, fnClose)
		Connects to the debug interface of a page given its WebSocket URL.
	class Page
		Connected := False
		ID := 0
		Responses := []
			wsurl      - The desired page's WebSocket URL
			fnCallback - A function to be called whenever message is received
			fnClose    - A function to be called whenever the page connection is lost
		__New(wsurl, fnCallback:="", fnClose:="")
			this.fnCallback := fnCallback
			this.fnClose := fnClose
			this.BoundKeepAlive := this.Call.Bind(this, "Browser.getVersion",, False)
			; TODO: Throw exception on invalid objects
			if IsObject(wsurl)
				wsurl := wsurl.webSocketDebuggerUrl
			wsurl := StrReplace(wsurl, "localhost", "") := {"base": this.WebSocket, "_Event": this.Event, "Parent": this}
			while !this.Connected
				Sleep, 50
			Calls the specified endpoint and provides it with the given
			DomainAndMethod - The endpoint domain and method name for the
				endpoint you would like to call. For example:
			Params - An associative array of parameters to be provided to the
				endpoint. For example:
				PageInst.Call("Page.printToPDF", {"scale": 0.5 ; Numeric Value
					, "landscape": Chrome.Jxon_True() ; Boolean Value
					, "pageRanges: "1-5, 8, 11-13"}) ; String value
				PageInst.Call("Page.navigate", {"url": ""})
			WaitForResponse - Whether to block until a response is received from
				Chrome, which is necessary to receive a return value, or whether
				to continue on with the script without waiting for a response.
		Call(DomainAndMethod, Params:="", WaitForResponse:=True)
			if !this.Connected
				throw Exception("Not connected to tab")
			; Use a temporary variable for ID in case more calls are made
			; before we receive a response.
			ID := this.ID += 1{"id": ID
			, "params": Params ? Params : {}
			, "method": DomainAndMethod}))
			if !WaitForResponse
			; Wait for the response
			this.responses[ID] := False
			while !this.responses[ID]
				Sleep, 50
			; Get the response, check if it's an error
			response := this.responses.Delete(ID)
			if (response.error)
				throw Exception("Chrome indicated error in response",, Chrome.Jxon_Dump(response.error))
			return response.result
			Run some JavaScript on the page. For example:
			PageInst.Evaluate("alert(""I can't believe it's not IE!"");")
			response := this.Call("Runtime.evaluate",
			( LTrim Join
				"expression": JS,
				"objectGroup": "console",
				"includeCommandLineAPI": Chrome.Jxon_True(),
				"silent": Chrome.Jxon_False(),
				"returnByValue": Chrome.Jxon_False(),
				"userGesture": Chrome.Jxon_True(),
				"awaitPromise": Chrome.Jxon_False()
			if (response.exceptionDetails)
				throw Exception(response.result.description, -1
					, Chrome.Jxon_Dump({"Code": JS
					, "exceptionDetails": response.exceptionDetails}))
			return response.result
			Waits for the page's readyState to match the DesiredState.
			DesiredState - The state to wait for the page's ReadyState to match
			Interval     - How often it should check whether the state matches
		WaitForLoad(DesiredState:="complete", Interval:=100)
			while this.Evaluate("document.readyState").value != DesiredState
				Sleep, Interval
			Internal function triggered when the script receives a message on
			the WebSocket connected to the page.
		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
			else if (EventName == "Message")
				data := Chrome.Jxon_Load(
				; Run the callback routine
				fnCallback := this.fnCallback
				if (newData := %fnCallback%(data))
					data := newData
				if this.responses.HasKey(data.ID)
					this.responses[data.ID] := data
			else if (EventName == "Close")
				fnClose := this.fnClose
			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.
			if !this.Connected
			this.Connected := False"Parent")
			BoundKeepAlive := this.BoundKeepAlive
			SetTimer, %BoundKeepAlive%, Delete
		#Include \\xx\xx$\MyPersonalData\Desktop\AHK\WebSocket.ahk
	#Include, \\xx\xx$\MyPersonalData\Desktop\AHK\Jxon.ahk
Main code looks like this:

#SingleInstance, Force
#Include, \\Vebp1359\cognev$\MyPersonalData\Desktop\AHK\Chrome.ahk


Tab := Chrome.GetTab() ;Connect to Active tab

data:=Chm_Get(Tab,Method:="ID",Attribute:="firstHeading", Index:=1)
MsgBox % data.InnerText
;~ DebugWindow(ExploreObj(data),1,1,200,0)


Code: Select all



if (Format("{:L}",Method)="class"){ ;Case-insensitive check to see if method = Class

Obj.OuterHTML:= Tab.Evaluate("document.getElementsByClassName('" Attribute "')[" Index-1 "].outerHTML").Value

Obj.Value:= Tab.Evaluate("document.getElementsByClassName('" Attribute "')[" Index-1 "].value").Value

Obj.InnerText:= Tab.Evaluate("document.getElementsByClassName('" Attribute "')[" Index-1 "].innerText").Value

Obj.TextContent:= Tab.Evaluate("document.getElementsByClassName('" Attribute "')[" Index-1 "].textContent").Value

} ;***********Tag*******************

Else if (Format("{:L}",Method)="tag"){  ;Case-insensitive check to see if method = Tag

Obj.OuterHTML:= Tab.Evaluate("document.getElementsByTagName('" Attribute "')[" Index-1 "].outerHTML").Value

Obj.Value:= Tab.Evaluate("document.getElementsByTagName('" Attribute "')[" Index-1 "].value").Value

Obj.InnerText:= Tab.Evaluate("document.getElementsByTagName('" Attribute "')[" Index-1 "].innerText").Value

Obj.TextContent:= Tab.Evaluate("document.getElementsByTagName('" Attribute "')[" Index-1 "].textContent").Value

} ;************Name******************

Else if (Format("{:L}",Method)="name"){  ;Case-insensitive check to see if method = Name

Obj.OuterHTML:= Tab.Evaluate("document.getElementsByName('" Attribute "')[" Index-1 "].outerHTML").Value

Obj.Value:= Tab.Evaluate("document.getElementsByName('" Attribute "')[" Index-1 "].value").Value

Obj.InnerText:= Tab.Evaluate("document.getElementsByName('" Attribute "')[" Index-1 "].innerText").Value

Obj.TextContent:= Tab.Evaluate("document.getElementsByName('" Attribute "')[" Index-1 "].textContent").Value

} ;***********ID*******************

Else if (Format("{:L}",Method)="id"){  ;Case-insensitive check to see if method = ID

Obj.OuterHTML:= Tab.Evaluate("document.getElementById('" Attribute "').outerHTML").Value

Obj.Value:= Tab.Evaluate("document.getElementById('" Attribute "').value").Value

Obj.InnerText:= Tab.Evaluate("document.getElementById('" Attribute "').innerText").Value

Obj.TextContent:= Tab.Evaluate("document.getElementById('" Attribute "').textContent").Value

} Else{ MsgBox fix Attribute- Valid values are: Name, Class, Tag, ID


return obj

Posts: 316
Joined: 28 Apr 2018, 21:59

Re: Google chrome does not get values

19 Sep 2018, 08:18

So there are two things I would suggest and that is the first to make everything in the Evaluate a variable. The second thing is that I don't think you need .Value at the end as it will return the info if it passes.

Return to “Ask For Help”

Who is online

Users browsing this forum: hatross, newbieforever, Portwolf, teadrinker, toni and 92 guests