Open a new tab from address bar in google chrome

Post your working scripts, libraries and tools for AHK v1.1 and older
cdull
Posts: 38
Joined: 11 Jan 2020, 07:34

Open a new tab from address bar in google chrome

Post by cdull » 17 Feb 2021, 14:23

In Firefox it is very easy: Type "about:config" to the address bar -> enter the config mode -> search for "browser.urlbar.openintab" -> then change it to true -> done.

In Chrome there is no way, not in the settings and i have also not found any extension which can do this.

After long search i found a way to do it stable with AutoHotkey:

Code: Select all

#if WinActive("ahk_exe chrome.exe") ; Google Chrome
NumpadEnter::
Enter::
      if WinActive("ahk_exe chrome.exe ahk_class Chrome_WidgetWin_1")
      {
         Acc_Caret := Acc_ObjectFromWindow(WinExist("ahk_class Chrome_WidgetWin_1"), OBJID_CARET := 0xFFFFFFF8)
         Caret_Location := Acc_Location(Acc_Caret)
         caret_check := Caret_Location.y
         WinGetPos,, chrome_y_check,,, A
         chrome_check_result := caret_check - chrome_y_check
         if (chrome_check_result = 0) ; try to get if caret is at location bar
         {
            sendinput {end}
            sleep, 50
            if (chrome_check_result = 50) ; execute when at location bar
            {
               sendinput !{enter}
               return
            }
            else ; execute alt+enter and enter when it is not sure where it is
            {
               sendinput !{enter}
               sleep, 50
               sendinput {enter}
               return
            }
         }
         else if (chrome_check_result = 50) ; execute when at location bar
         {
            sendinput !{enter}
         }
         else ; execute when not at location bar
         {
            sendinput {enter}
         }
         return
      }
      else
      {
         sendinput {enter}
         return
      }
   return
   
;------------------------------------------- Chrome Enter Helper --------------------------------------------

; http://www.autohotkey.com/board/topic/77303-acc-library-ahk-l-updated-09272012/
; https dl.dropbox.com /u/47573473/Web%20Server/AHK_L/Acc.ahk  Broken Link for safety
;------------------------------------------------------------------------------
; Acc.ahk Standard Library
; by Sean
; Updated by jethrow:
; 	Modified ComObjEnwrap params from (9,pacc) --> (9,pacc,1)
; 	Changed ComObjUnwrap to ComObjValue in order to avoid AddRef (thanks fincs)
; 	Added Acc_GetRoleText & Acc_GetStateText
; 	Added additional functions - commented below
; 	Removed original Acc_Children function
; last updated 2/25/2010
;------------------------------------------------------------------------------

Acc_Init()
{
	Static	h
	If Not	h
		h:=DllCall("LoadLibrary","Str","oleacc","Ptr")
}
Acc_ObjectFromEvent(ByRef _idChild_, hWnd, idObject, idChild)
{
	Acc_Init()
	If	DllCall("oleacc\AccessibleObjectFromEvent", "Ptr", hWnd, "UInt", idObject, "UInt", idChild, "Ptr*", pacc, "Ptr", VarSetCapacity(varChild,8+2*A_PtrSize,0)*0+&varChild)=0
	Return	ComObjEnwrap(9,pacc,1), _idChild_:=NumGet(varChild,8,"UInt")
}

Acc_ObjectFromPoint(ByRef _idChild_ = "", x = "", y = "")
{
	Acc_Init()
	If	DllCall("oleacc\AccessibleObjectFromPoint", "Int64", x==""||y==""?0*DllCall("GetCursorPos","Int64*",pt)+pt:x&0xFFFFFFFF|y<<32, "Ptr*", pacc, "Ptr", VarSetCapacity(varChild,8+2*A_PtrSize,0)*0+&varChild)=0
	Return	ComObjEnwrap(9,pacc,1), _idChild_:=NumGet(varChild,8,"UInt")
}

Acc_ObjectFromWindow(hWnd, idObject = -4)
{
	Acc_Init()
	If	DllCall("oleacc\AccessibleObjectFromWindow", "Ptr", hWnd, "UInt", idObject&=0xFFFFFFFF, "Ptr", -VarSetCapacity(IID,16)+NumPut(idObject==0xFFFFFFF0?0x46000000000000C0:0x719B3800AA000C81,NumPut(idObject==0xFFFFFFF0?0x0000000000020400:0x11CF3C3D618736E0,IID,"Int64"),"Int64"), "Ptr*", pacc)=0
	Return	ComObjEnwrap(9,pacc,1)
}

Acc_WindowFromObject(pacc)
{
	If	DllCall("oleacc\WindowFromAccessibleObject", "Ptr", IsObject(pacc)?ComObjValue(pacc):pacc, "Ptr*", hWnd)=0
	Return	hWnd
}

Acc_GetRoleText(nRole)
{
	nSize := DllCall("oleacc\GetRoleText", "Uint", nRole, "Ptr", 0, "Uint", 0)
	VarSetCapacity(sRole, (A_IsUnicode?2:1)*nSize)
	DllCall("oleacc\GetRoleText", "Uint", nRole, "str", sRole, "Uint", nSize+1)
	Return	sRole
}

Acc_GetStateText(nState)
{
	nSize := DllCall("oleacc\GetStateText", "Uint", nState, "Ptr", 0, "Uint", 0)
	VarSetCapacity(sState, (A_IsUnicode?2:1)*nSize)
	DllCall("oleacc\GetStateText", "Uint", nState, "str", sState, "Uint", nSize+1)
	Return	sState
}

Acc_SetWinEventHook(eventMin, eventMax, pCallback)
{
	Return	DllCall("SetWinEventHook", "Uint", eventMin, "Uint", eventMax, "Uint", 0, "Ptr", pCallback, "Uint", 0, "Uint", 0, "Uint", 0)
}

Acc_UnhookWinEvent(hHook)
{
	Return	DllCall("UnhookWinEvent", "Ptr", hHook)
}
/*	Win Events:

	pCallback := RegisterCallback("WinEventProc")
	WinEventProc(hHook, event, hWnd, idObject, idChild, eventThread, eventTime)
	{
		Critical
		Acc := Acc_ObjectFromEvent(_idChild_, hWnd, idObject, idChild)
		; Code Here:

	}
*/

; Written by jethrow
Acc_Role(Acc, ChildId=0) {
	try return ComObjType(Acc,"Name")="IAccessible"?Acc_GetRoleText(Acc.accRole(ChildId)):"invalid object"
}
Acc_State(Acc, ChildId=0) {
	try return ComObjType(Acc,"Name")="IAccessible"?Acc_GetStateText(Acc.accState(ChildId)):"invalid object"
}
Acc_Location(Acc, ChildId=0, byref Position="") { ; adapted from Sean's code
	try Acc.accLocation(ComObj(0x4003,&x:=0), ComObj(0x4003,&y:=0), ComObj(0x4003,&w:=0), ComObj(0x4003,&h:=0), ChildId)
	catch
		return
	Position := "x" NumGet(x,0,"int") " y" NumGet(y,0,"int") " w" NumGet(w,0,"int") " h" NumGet(h,0,"int")
	return	{x:NumGet(x,0,"int"), y:NumGet(y,0,"int"), w:NumGet(w,0,"int"), h:NumGet(h,0,"int")}
}
Acc_Parent(Acc) { 
	try parent:=Acc.accParent
	return parent?Acc_Query(parent):
}
Acc_Child(Acc, ChildId=0) {
	try child:=Acc.accChild(ChildId)
	return child?Acc_Query(child):
}
Acc_Query(Acc) { ; thanks Lexikos - www.autohotkey.com/forum/viewtopic.php?t=81731&p=509530#509530
	try return ComObj(9, ComObjQuery(Acc,"{618736e0-3c3d-11cf-810c-00aa00389b71}"), 1)
}
Acc_Error(p="") {
	static setting:=0
	return p=""?setting:setting:=p
}
Acc_Children(Acc) {
	if ComObjType(Acc,"Name") != "IAccessible"
		ErrorLevel := "Invalid IAccessible Object"
	else {
		Acc_Init(), cChildren:=Acc.accChildCount, Children:=[]
		if DllCall("oleacc\AccessibleChildren", "Ptr",ComObjValue(Acc), "Int",0, "Int",cChildren, "Ptr",VarSetCapacity(varChildren,cChildren*(8+2*A_PtrSize),0)*0+&varChildren, "Int*",cChildren)=0 {
			Loop %cChildren%
				i:=(A_Index-1)*(A_PtrSize*2+8)+8, child:=NumGet(varChildren,i), Children.Insert(NumGet(varChildren,i-8)=9?Acc_Query(child):child), NumGet(varChildren,i-8)=9?ObjRelease(child):
			return Children.MaxIndex()?Children:
		} else
			ErrorLevel := "AccessibleChildren DllCall Failed"
	}
	if Acc_Error()
		throw Exception(ErrorLevel,-1)
}
Acc_ChildrenByRole(Acc, Role) {
	if ComObjType(Acc,"Name")!="IAccessible"
		ErrorLevel := "Invalid IAccessible Object"
	else {
		Acc_Init(), cChildren:=Acc.accChildCount, Children:=[]
		if DllCall("oleacc\AccessibleChildren", "Ptr",ComObjValue(Acc), "Int",0, "Int",cChildren, "Ptr",VarSetCapacity(varChildren,cChildren*(8+2*A_PtrSize),0)*0+&varChildren, "Int*",cChildren)=0 {
			Loop %cChildren% {
				i:=(A_Index-1)*(A_PtrSize*2+8)+8, child:=NumGet(varChildren,i)
				if NumGet(varChildren,i-8)=9
					AccChild:=Acc_Query(child), ObjRelease(child), Acc_Role(AccChild)=Role?Children.Insert(AccChild):
				else
					Acc_Role(Acc, child)=Role?Children.Insert(child):
			}
			return Children.MaxIndex()?Children:, ErrorLevel:=0
		} else
			ErrorLevel := "AccessibleChildren DllCall Failed"
	}
	if Acc_Error()
		throw Exception(ErrorLevel,-1)
}
Acc_Get(Cmd, ChildPath="", ChildID=0, WinTitle="", WinText="", ExcludeTitle="", ExcludeText="") {
	static properties := {Action:"DefaultAction", DoAction:"DoDefaultAction", Keyboard:"KeyboardShortcut"}
	AccObj :=   IsObject(WinTitle)? WinTitle
			:   Acc_ObjectFromWindow( WinExist(WinTitle, WinText, ExcludeTitle, ExcludeText), 0 )
	if ComObjType(AccObj, "Name") != "IAccessible"
		ErrorLevel := "Could not access an IAccessible Object"
	else {
		StringReplace, ChildPath, ChildPath, _, %A_Space%, All
		AccError:=Acc_Error(), Acc_Error(true)
		Loop Parse, ChildPath, ., %A_Space%
			try {
				if A_LoopField is digit
					Children:=Acc_Children(AccObj), m2:=A_LoopField ; mimic "m2" output in else-statement
				else
					RegExMatch(A_LoopField, "(\D*)(\d*)", m), Children:=Acc_ChildrenByRole(AccObj, m1), m2:=(m2?m2:1)
				if Not Children.HasKey(m2)
					throw
				AccObj := Children[m2]
			} catch {
				ErrorLevel:="Cannot access ChildPath Item #" A_Index " -> " A_LoopField, Acc_Error(AccError)
				if Acc_Error()
					throw Exception("Cannot access ChildPath Item", -1, "Item #" A_Index " -> " A_LoopField)
				return
			}
		Acc_Error(AccError)
		StringReplace, Cmd, Cmd, %A_Space%, , All
		properties.HasKey(Cmd)? Cmd:=properties[Cmd]:
		try {
			if (Cmd = "Location")
				AccObj.accLocation(ComObj(0x4003,&x:=0), ComObj(0x4003,&y:=0), ComObj(0x4003,&w:=0), ComObj(0x4003,&h:=0), ChildId)
			  , ret_val := "x" NumGet(x,0,"int") " y" NumGet(y,0,"int") " w" NumGet(w,0,"int") " h" NumGet(h,0,"int")
			else if (Cmd = "Object")
				ret_val := AccObj
			else if Cmd in Role,State
				ret_val := Acc_%Cmd%(AccObj, ChildID+0)
			else if Cmd in ChildCount,Selection,Focus
				ret_val := AccObj["acc" Cmd]
			else
				ret_val := AccObj["acc" Cmd](ChildID+0)
		} catch {
			ErrorLevel := """" Cmd """ Cmd Not Implemented"
			if Acc_Error()
				throw Exception("Cmd Not Implemented", -1, Cmd)
			return
		}
		return ret_val, ErrorLevel:=0
	}
	if Acc_Error()
		throw Exception(ErrorLevel,-1)
}

return

I hope you have fun with that script.

For those who not familiar with AutoHotkey i added the script to attachment. Unzip the file and add it to your autostart folder.
Attachments
chrome_addressbar_new_tab.zip
(523.99 KiB) Downloaded 224 times

WoofGrrrr
Posts: 3
Joined: 15 Jul 2021, 09:03

Re: Open a new tab from address bar in google chrome

Post by WoofGrrrr » 15 Jul 2021, 09:11

I don't understand something. When I un-zip the downloaded file, I get an executable (.exe) file: chrome_addressbar_new_tab.exe

I thought it would be a ".ahk" file.

What does this executable file do?

gregster
Posts: 9056
Joined: 30 Sep 2013, 06:48

Re: Open a new tab from address bar in google chrome

Post by gregster » 15 Jul 2021, 09:16

@WoofGrrrr:
Afaics (haven't tried the code), the actual code (the ".ahk file") is available in the code box - just copy it and put it into a text file with ahk-extension, and run it.
(See our beginner's tutorial for the basics.)

The attachment is mainly for the ones "not familiar with AutoHotkey", and is simply the compiled ("standalone" so to say) version of that ahk script, I assume.

WoofGrrrr
Posts: 3
Joined: 15 Jul 2021, 09:03

Re: Open a new tab from address bar in google chrome

Post by WoofGrrrr » 15 Jul 2021, 09:26

Doesn't work for me.

I copied and pasted the script above into a .ahk file and then ran it.

I then restarted chrome, clicked on a bookmark to go to a web site, typed over the address with "google.com" in the address/search bar and clicked the <enter> key. The Google Search page replaced the current page. A new tab was not opened.

WoofGrrrr
Posts: 3
Joined: 15 Jul 2021, 09:03

Re: Open a new tab from address bar in google chrome

Post by WoofGrrrr » 15 Jul 2021, 09:32

gregster wrote:
15 Jul 2021, 09:16
@WoofGrrrr:
Afaics (haven't tried the code), the actual code (the ".ahk file") is available in the code box - just copy it and put it into a text file with ahk-extension, and run it.
(See our beginner's tutorial for the basics.)

The attachment is mainly for the ones "not familiar with AutoHotkey", and is simply the compiled ("standalone" so to say) version of that ahk script, I assume.

Ah! I didn't know you could COMPILE an ahk script into an executable. I'm a complete noob. I only just installed AutoHotKey so I could run this very script.

Thank you for the info!

gregster
Posts: 9056
Joined: 30 Sep 2013, 06:48

Re: Open a new tab from address bar in google chrome

Post by gregster » 15 Jul 2021, 09:39

WoofGrrrr wrote:
15 Jul 2021, 09:32
Ah! I didn't know you could COMPILE an ahk script into an executable.
No problem. well, it doesn't get compiled in a strict sense - the text file just gets combined into one file with the interpreter. There will be no speed advantage, and the original script can still be extracted from that exe-file. But nevertheless, it will be a standalone executable.

Re the script: Can't test it momentarily. Perhaps something has changed in Chrome since this script was posted, and it needs to be changed a bit.

cdull
Posts: 38
Joined: 11 Jan 2020, 07:34

Re: Open a new tab from address bar in google chrome

Post by cdull » 20 Nov 2021, 09:59

After using this code for near a year, i have made a little update to it.

It now works in more than 99% of the cases. Every 1-3 months it is not working correct (don't know why). And now you can longpress enter to overwrite the current tab (like previously with enter).

What i found out, if you try to insert something from the clipboard with Win+V to the address bar, nothing will be inserted. You need to use the spacebar to insert it, when you use this script.

A native solution in chrome would be the best, but until then this is the best option. At the moment the Cent Browser have this option, but i don't want to switch.

The script will also work in Microsoft Edge, if you change the "ahk_exe chrome" to "ahk_exe msedge.exe" in line 1 and 13.

Code: Select all

#if WinActive("ahk_exe chrome.exe") ; Google Chrome
NumpadEnter::
Enter::
   KeyWait, enter, T0.2 ; Long press
   if (Errorlevel)
   {
         FileAppend, %A_ThisFunc%_longpress`n, %A_MyDocuments%\keyboardshortcuts_counter.txt
      sendinput {enter}
      return
   }
   else ; Single press
   {
      if WinActive("ahk_exe chrome.exe ahk_class Chrome_WidgetWin_1")
      {
         Acc_Caret := Acc_ObjectFromWindow(WinExist("ahk_class Chrome_WidgetWin_1"), OBJID_CARET := 0xFFFFFFF8)
         Caret_Location := Acc_Location(Acc_Caret)
         caret_check := Caret_Location.y
         WinGetPos,, chrome_y_check,,, A
         chrome_check_result := caret_check - chrome_y_check
         if chrome_check_result between -4 and 50 ; execute when at location bar
         {
            sendinput !{enter}
         }
         else ; execute when not at location bar
         {
            sendinput {enter}
         }
         return
      }
      else
      {
         sendinput {enter}
         return
      }
   }
   return
   
;------------------------------------------- Chrome Enter Helper --------------------------------------------

; http://www.autohotkey.com/board/topic/77303-acc-library-ahk-l-updated-09272012/
; https dl.dropbox.com /u/47573473/Web%20Server/AHK_L/Acc.ahk  Broken Link for safety
;------------------------------------------------------------------------------
; Acc.ahk Standard Library
; by Sean
; Updated by jethrow:
; 	Modified ComObjEnwrap params from (9,pacc) --> (9,pacc,1)
; 	Changed ComObjUnwrap to ComObjValue in order to avoid AddRef (thanks fincs)
; 	Added Acc_GetRoleText & Acc_GetStateText
; 	Added additional functions - commented below
; 	Removed original Acc_Children function
; last updated 2/25/2010
;------------------------------------------------------------------------------

Acc_Init()
{
	Static	h
	If Not	h
		h:=DllCall("LoadLibrary","Str","oleacc","Ptr")
}
Acc_ObjectFromEvent(ByRef _idChild_, hWnd, idObject, idChild)
{
	Acc_Init()
	If	DllCall("oleacc\AccessibleObjectFromEvent", "Ptr", hWnd, "UInt", idObject, "UInt", idChild, "Ptr*", pacc, "Ptr", VarSetCapacity(varChild,8+2*A_PtrSize,0)*0+&varChild)=0
	Return	ComObjEnwrap(9,pacc,1), _idChild_:=NumGet(varChild,8,"UInt")
}

Acc_ObjectFromPoint(ByRef _idChild_ = "", x = "", y = "")
{
	Acc_Init()
	If	DllCall("oleacc\AccessibleObjectFromPoint", "Int64", x==""||y==""?0*DllCall("GetCursorPos","Int64*",pt)+pt:x&0xFFFFFFFF|y<<32, "Ptr*", pacc, "Ptr", VarSetCapacity(varChild,8+2*A_PtrSize,0)*0+&varChild)=0
	Return	ComObjEnwrap(9,pacc,1), _idChild_:=NumGet(varChild,8,"UInt")
}

Acc_ObjectFromWindow(hWnd, idObject = -4)
{
	Acc_Init()
	If	DllCall("oleacc\AccessibleObjectFromWindow", "Ptr", hWnd, "UInt", idObject&=0xFFFFFFFF, "Ptr", -VarSetCapacity(IID,16)+NumPut(idObject==0xFFFFFFF0?0x46000000000000C0:0x719B3800AA000C81,NumPut(idObject==0xFFFFFFF0?0x0000000000020400:0x11CF3C3D618736E0,IID,"Int64"),"Int64"), "Ptr*", pacc)=0
	Return	ComObjEnwrap(9,pacc,1)
}

Acc_WindowFromObject(pacc)
{
	If	DllCall("oleacc\WindowFromAccessibleObject", "Ptr", IsObject(pacc)?ComObjValue(pacc):pacc, "Ptr*", hWnd)=0
	Return	hWnd
}

Acc_GetRoleText(nRole)
{
	nSize := DllCall("oleacc\GetRoleText", "Uint", nRole, "Ptr", 0, "Uint", 0)
	VarSetCapacity(sRole, (A_IsUnicode?2:1)*nSize)
	DllCall("oleacc\GetRoleText", "Uint", nRole, "str", sRole, "Uint", nSize+1)
	Return	sRole
}

Acc_GetStateText(nState)
{
	nSize := DllCall("oleacc\GetStateText", "Uint", nState, "Ptr", 0, "Uint", 0)
	VarSetCapacity(sState, (A_IsUnicode?2:1)*nSize)
	DllCall("oleacc\GetStateText", "Uint", nState, "str", sState, "Uint", nSize+1)
	Return	sState
}

Acc_SetWinEventHook(eventMin, eventMax, pCallback)
{
	Return	DllCall("SetWinEventHook", "Uint", eventMin, "Uint", eventMax, "Uint", 0, "Ptr", pCallback, "Uint", 0, "Uint", 0, "Uint", 0)
}

Acc_UnhookWinEvent(hHook)
{
	Return	DllCall("UnhookWinEvent", "Ptr", hHook)
}
/*	Win Events:

	pCallback := RegisterCallback("WinEventProc")
	WinEventProc(hHook, event, hWnd, idObject, idChild, eventThread, eventTime)
	{
		Critical
		Acc := Acc_ObjectFromEvent(_idChild_, hWnd, idObject, idChild)
		; Code Here:

	}
*/

; Written by jethrow
Acc_Role(Acc, ChildId=0) {
	try return ComObjType(Acc,"Name")="IAccessible"?Acc_GetRoleText(Acc.accRole(ChildId)):"invalid object"
}
Acc_State(Acc, ChildId=0) {
	try return ComObjType(Acc,"Name")="IAccessible"?Acc_GetStateText(Acc.accState(ChildId)):"invalid object"
}
Acc_Location(Acc, ChildId=0, byref Position="") { ; adapted from Sean's code
	try Acc.accLocation(ComObj(0x4003,&x:=0), ComObj(0x4003,&y:=0), ComObj(0x4003,&w:=0), ComObj(0x4003,&h:=0), ChildId)
	catch
		return
	Position := "x" NumGet(x,0,"int") " y" NumGet(y,0,"int") " w" NumGet(w,0,"int") " h" NumGet(h,0,"int")
	return	{x:NumGet(x,0,"int"), y:NumGet(y,0,"int"), w:NumGet(w,0,"int"), h:NumGet(h,0,"int")}
}
Acc_Parent(Acc) { 
	try parent:=Acc.accParent
	return parent?Acc_Query(parent):
}
Acc_Child(Acc, ChildId=0) {
	try child:=Acc.accChild(ChildId)
	return child?Acc_Query(child):
}
Acc_Query(Acc) { ; thanks Lexikos - www.autohotkey.com/forum/viewtopic.php?t=81731&p=509530#509530
	try return ComObj(9, ComObjQuery(Acc,"{618736e0-3c3d-11cf-810c-00aa00389b71}"), 1)
}
Acc_Error(p="") {
	static setting:=0
	return p=""?setting:setting:=p
}
Acc_Children(Acc) {
	if ComObjType(Acc,"Name") != "IAccessible"
		ErrorLevel := "Invalid IAccessible Object"
	else {
		Acc_Init(), cChildren:=Acc.accChildCount, Children:=[]
		if DllCall("oleacc\AccessibleChildren", "Ptr",ComObjValue(Acc), "Int",0, "Int",cChildren, "Ptr",VarSetCapacity(varChildren,cChildren*(8+2*A_PtrSize),0)*0+&varChildren, "Int*",cChildren)=0 {
			Loop %cChildren%
				i:=(A_Index-1)*(A_PtrSize*2+8)+8, child:=NumGet(varChildren,i), Children.Insert(NumGet(varChildren,i-8)=9?Acc_Query(child):child), NumGet(varChildren,i-8)=9?ObjRelease(child):
			return Children.MaxIndex()?Children:
		} else
			ErrorLevel := "AccessibleChildren DllCall Failed"
	}
	if Acc_Error()
		throw Exception(ErrorLevel,-1)
}
Acc_ChildrenByRole(Acc, Role) {
	if ComObjType(Acc,"Name")!="IAccessible"
		ErrorLevel := "Invalid IAccessible Object"
	else {
		Acc_Init(), cChildren:=Acc.accChildCount, Children:=[]
		if DllCall("oleacc\AccessibleChildren", "Ptr",ComObjValue(Acc), "Int",0, "Int",cChildren, "Ptr",VarSetCapacity(varChildren,cChildren*(8+2*A_PtrSize),0)*0+&varChildren, "Int*",cChildren)=0 {
			Loop %cChildren% {
				i:=(A_Index-1)*(A_PtrSize*2+8)+8, child:=NumGet(varChildren,i)
				if NumGet(varChildren,i-8)=9
					AccChild:=Acc_Query(child), ObjRelease(child), Acc_Role(AccChild)=Role?Children.Insert(AccChild):
				else
					Acc_Role(Acc, child)=Role?Children.Insert(child):
			}
			return Children.MaxIndex()?Children:, ErrorLevel:=0
		} else
			ErrorLevel := "AccessibleChildren DllCall Failed"
	}
	if Acc_Error()
		throw Exception(ErrorLevel,-1)
}
Acc_Get(Cmd, ChildPath="", ChildID=0, WinTitle="", WinText="", ExcludeTitle="", ExcludeText="") {
	static properties := {Action:"DefaultAction", DoAction:"DoDefaultAction", Keyboard:"KeyboardShortcut"}
	AccObj :=   IsObject(WinTitle)? WinTitle
			:   Acc_ObjectFromWindow( WinExist(WinTitle, WinText, ExcludeTitle, ExcludeText), 0 )
	if ComObjType(AccObj, "Name") != "IAccessible"
		ErrorLevel := "Could not access an IAccessible Object"
	else {
		StringReplace, ChildPath, ChildPath, _, %A_Space%, All
		AccError:=Acc_Error(), Acc_Error(true)
		Loop Parse, ChildPath, ., %A_Space%
			try {
				if A_LoopField is digit
					Children:=Acc_Children(AccObj), m2:=A_LoopField ; mimic "m2" output in else-statement
				else
					RegExMatch(A_LoopField, "(\D*)(\d*)", m), Children:=Acc_ChildrenByRole(AccObj, m1), m2:=(m2?m2:1)
				if Not Children.HasKey(m2)
					throw
				AccObj := Children[m2]
			} catch {
				ErrorLevel:="Cannot access ChildPath Item #" A_Index " -> " A_LoopField, Acc_Error(AccError)
				if Acc_Error()
					throw Exception("Cannot access ChildPath Item", -1, "Item #" A_Index " -> " A_LoopField)
				return
			}
		Acc_Error(AccError)
		StringReplace, Cmd, Cmd, %A_Space%, , All
		properties.HasKey(Cmd)? Cmd:=properties[Cmd]:
		try {
			if (Cmd = "Location")
				AccObj.accLocation(ComObj(0x4003,&x:=0), ComObj(0x4003,&y:=0), ComObj(0x4003,&w:=0), ComObj(0x4003,&h:=0), ChildId)
			  , ret_val := "x" NumGet(x,0,"int") " y" NumGet(y,0,"int") " w" NumGet(w,0,"int") " h" NumGet(h,0,"int")
			else if (Cmd = "Object")
				ret_val := AccObj
			else if Cmd in Role,State
				ret_val := Acc_%Cmd%(AccObj, ChildID+0)
			else if Cmd in ChildCount,Selection,Focus
				ret_val := AccObj["acc" Cmd]
			else
				ret_val := AccObj["acc" Cmd](ChildID+0)
		} catch {
			ErrorLevel := """" Cmd """ Cmd Not Implemented"
			if Acc_Error()
				throw Exception("Cmd Not Implemented", -1, Cmd)
			return
		}
		return ret_val, ErrorLevel:=0
	}
	if Acc_Error()
		throw Exception(ErrorLevel,-1)
}

return
I added .exe and .ahk files for chrome, edge and both to the attachment.
Attachments
chrome_addressbar_new_tab_updated.zip
(1.66 MiB) Downloaded 220 times

Locolijo
Posts: 1
Joined: 09 Jun 2022, 19:08

Re: Open a new tab from address bar in google chrome

Post by Locolijo » 09 Jun 2022, 19:09

Sorry I am new at this. What exactly does this do and is there a hotkey?
Thank you

Descolada
Posts: 1147
Joined: 23 Dec 2021, 02:30

Re: Open a new tab from address bar in google chrome

Post by Descolada » 10 Jun 2022, 02:53

Same feature (when Enter is pressed in Google Chrome address bar, then the URL is opened in a new tab) but instead of Acc using UIAutomation:

Code: Select all

#NoEnv
SetWorkingDir %A_ScriptDir%

UIA := UIA_Interface(), URLBarName

#if WinActive("ahk_exe chrome.exe ahk_class Chrome_WidgetWin_1") ; Google Chrome. Replace with "ahk_exe msedge.exe" to make it work with Edge
NumpadEnter::
Enter::
	if !URLBarName {
		try {
			cEl := UIA.ElementFromHandle(WinExist("A"))
			EditControlCondition := UIA.CreatePropertyCondition(UIA_ControlTypePropertyId := 30003, UIA_EditControlTypeId := 50004, VT_I4:=3)
			URLBarName := cEl.FindFirst(EditControlCondition).CurrentName
		} catch
			URLBarName := "Address and search bar"
	}
	try {
		el := UIA.GetFocusedElement()
		if (el.CurrentControlType == 50004) && (el.CurrentName == URLBarName) {
			Send, !{Enter}
			return
		}
	}	
	Send {Enter}
	return

; UIA FUNCTIONS
class UIA_Base {
	__New(p="", flag=1) {
		ObjInsert(this,"__Type","IUIAutomation" SubStr(thisClass,5))
		,ObjInsert(this,"__Value",p)
		,ObjInsert(this,"__Flag",flag)
	}
	__Get(member) {
		if member not in base,__UIA ; base & __UIA should act as normal
		{	if raw:=SubStr(member,0)="*" ; return raw data - user should know what they are doing
				member:=SubStr(member,1,-1)
			if RegExMatch(this.__properties, "im)^" member ",(\d+),(\w+)", m) { ; if the member is in the properties. if not - give error message
				if (m2="VARIANT")	; return VARIANT data - DllCall output param different
					return UIA_Hr(DllCall(this.__Vt(m1), "ptr",this.__Value, "ptr",UIA_Variant(out)))? (raw?out:UIA_VariantData(out)):
				else if UIA_Hr(DllCall(this.__Vt(m1), "ptr",this.__Value, "ptr*",out))
					return raw?out:m2="BSTR"?StrGet(out):RegExMatch(m2,"i)IUIAutomation\K\w+",n)?new UIA_%n%(out):out ; Bool, int, DWORD, HWND, CONTROLTYPEID, OrientationType?
			}
			else throw Exception("Property not supported by the " this.__Class " Class.",-1,member)
		}
	}
	__Delete() {
		this.__Flag ? ObjRelease(this.__Value):
	}
	__Vt(n) {
		return NumGet(NumGet(this.__Value+0,"ptr")+n*A_PtrSize,"ptr")
	}
}

class UIA_Interface extends UIA_Base {
	;~ http://msdn.microsoft.com/en-us/library/windows/desktop/ee671406(v=vs.85).aspx
	static __IID := "{30cbe57d-d9d0-452a-ab13-7ac5ac4825ee}"
		,  __properties := ""
	ElementFromHandle(hwnd) {
		return UIA_Hr(DllCall(this.__Vt(6), "ptr",this.__Value, "ptr",hwnd, "ptr*",out))? new UIA_Element(out):
	}
	GetFocusedElement() {
		return UIA_Hr(DllCall(this.__Vt(8), "ptr",this.__Value, "ptr*",out))? new UIA_Element(out):
	}
	CreatePropertyCondition(propertyId, var, type="Variant") {
		if (type!="Variant")
			UIA_Variant(var,type,var)
		return UIA_Hr((A_PtrSize == 4) ? DllCall(this.__Vt(23), "ptr",this.__Value, "int",propertyId, "int64", NumGet(var, 0, "int64"), "int64", NumGet(var, 8, "int64"), "ptr*",out) : DllCall(this.__Vt(23), "ptr",this.__Value, "int",propertyId, "ptr",&var, "ptr*",out))? new UIA_PropertyCondition(out):
	}
}
class UIA_Element extends UIA_Base {
	;~ http://msdn.microsoft.com/en-us/library/windows/desktop/ee671425(v=vs.85).aspx
	static __IID := "{d22108aa-8ac5-49a5-837b-37bbb3d7591e}"
		,  __properties := "CurrentControlType,21,CONTROLTYPEID`r`nCurrentName,23,BSTR"
	
	SetFocus() {
		return UIA_Hr(DllCall(this.__Vt(3), "ptr",this.__Value))
	}
	FindFirst(c="", scope=0x4) {
		return UIA_Hr(DllCall(this.__Vt(5), "ptr",this.__Value, "uint",scope, "ptr",(c=""?this.TrueCondition:c).__Value, "ptr*",out))&&out? new UIA_Element(out):
	}
}
class UIA_Condition extends UIA_Base {
	;~ http://msdn.microsoft.com/en-us/library/windows/desktop/ee671420(v=vs.85).aspx
	static __IID := "{352ffba8-0973-437c-a61f-f64cafd81df9}"
}
class UIA_PropertyCondition extends UIA_Condition {
	;~ http://msdn.microsoft.com/en-us/library/windows/desktop/ee696121(v=vs.85).aspx
	static __IID := "{99ebf2cb-5578-4267-9ad4-afd6ea77e94b}"
		,  __properties := "PropertyId,3,PROPERTYID`r`nPropertyValue,4,VARIANT`r`nPropertyConditionFlags,5,PropertyConditionFlags"
}
UIA_Interface() {
	try {
		if uia:=ComObjCreate("{ff48dba4-60ef-4201-aa87-54103eef594e}","{30cbe57d-d9d0-452a-ab13-7ac5ac4825ee}")
			return uia:=new UIA_Interface(uia, 1), uia.base.base.__UIA:=uia
		throw "UIAutomation Interface failed to initialize."
	} catch e
		MsgBox, 262160, UIA Startup Error, % IsObject(e)?"IUIAutomation Interface is not registered.":e.Message
}
UIA_Hr(hr) {
	;~ http://blogs.msdn.com/b/eldar/archive/2007/04/03/a-lot-of-hresult-codes.aspx
	static err:={0x8000FFFF:"Catastrophic failure.",0x80004001:"Not implemented.",0x8007000E:"Out of memory.",0x80070057:"One or more arguments are not valid.",0x80004002:"Interface not supported.",0x80004003:"Pointer not valid.",0x80070006:"Handle not valid.",0x80004004:"Operation aborted.",0x80004005:"Unspecified error.",0x80070005:"General access denied.",0x800401E5:"The object identified by this moniker could not be found.",0x80040201:"UIA_E_ELEMENTNOTAVAILABLE",0x80040200:"UIA_E_ELEMENTNOTENABLED",0x80131509:"UIA_E_INVALIDOPERATION",0x80040202:"UIA_E_NOCLICKABLEPOINT",0x80040204:"UIA_E_NOTSUPPORTED",0x80040203:"UIA_E_PROXYASSEMBLYNOTLOADED"} ; //not completed
	if hr&&(hr&=0xFFFFFFFF) {
		RegExMatch(Exception("",-2).what,"(\w+).(\w+)",i)
		throw Exception(UIA_Hex(hr) " - " err[hr], -2, i2 "  (" i1 ")")
	}
	return !hr
}
UIA_Hex(p) {
	setting:=A_FormatInteger
	SetFormat,IntegerFast,H
	out:=p+0 ""
	SetFormat,IntegerFast,%setting%
	return out
}
UIA_GUID(ByRef GUID, sGUID) { ;~ Converts a string to a binary GUID and returns its address.
	VarSetCapacity(GUID,16,0)
	return DllCall("ole32\CLSIDFromString", "wstr",sGUID, "ptr",&GUID)>=0?&GUID:""
}
UIA_Variant(ByRef var,type=0,val=0) {
	; Does a variant need to be cleared? If it uses SysAllocString? 
	return (VarSetCapacity(var,8+2*A_PtrSize)+NumPut(type,var,0,"short")+NumPut(type=8? DllCall("oleaut32\SysAllocString", "ptr",&val):val,var,8,"ptr"))*0+&var
}
UIA_IsVariant(ByRef vt, ByRef type="") {
	size:=VarSetCapacity(vt),type:=NumGet(vt,"UShort")
	return size>=16&&size<=24&&type>=0&&(type<=23||type|0x2000)
}
UIA_VariantData(ByRef p, flag=1) {
	return !UIA_IsVariant(p,vt)?"Invalid Variant"
			:vt=3?NumGet(p,8,"int")
			:vt=8?StrGet(NumGet(p,8))
			:vt=9||vt=13||vt&0x2000?ComObj(vt,NumGet(p,8),flag)
			:vt<0x1000&&UIA_VariantChangeType(&p,&p)=0?StrGet(NumGet(p,8)) UIA_VariantClear(&p)
			:NumGet(p,8)
}
UIA_VariantChangeType(pvarDst, pvarSrc, vt=8) { ; written by Sean
	return DllCall("oleaut32\VariantChangeTypeEx", "ptr",pvarDst, "ptr",pvarSrc, "Uint",1024, "Ushort",0, "Ushort",vt)
}
UIA_VariantClear(pvar) { ; Written by Sean
	DllCall("oleaut32\VariantClear", "ptr",pvar)
}
The first time pressing "Enter" might be a bit sluggish, but afterwards it should be fast. This drawback can be avoided if the URL bar name is already known, for example if Chrome is being ran in English, change the line UIA := UIA_Interface(), URLBarName to UIA := UIA_Interface(), URLBarName:="Address and search bar"
The name of the address bar can be found out using UIAViewer or Accessibility Insights

By default this works with Google Chrome, but can work with Edge too (change #if WinActive("ahk_exe chrome.exe ahk_class Chrome_WidgetWin_1") to #if WinActive("ahk_exe msedge.exe")).

cRsh
Posts: 2
Joined: 31 Jul 2022, 13:54

Re: Open a new tab from address bar in google chrome

Post by cRsh » 31 Jul 2022, 13:57

Thx @ Descola.
Works great with URLs and search terms. Is it possible to add the same behavior for the bookmarks?

Thx in advance.

Chris

Descolada
Posts: 1147
Joined: 23 Dec 2021, 02:30

Re: Open a new tab from address bar in google chrome

Post by Descolada » 31 Jul 2022, 15:01

@cRsh, it's technically possible, but practically you wouldn't want to do it since it would slow clicking in Chrome down by a lot... A better solution is described here: https://support.google.com/chrome/thread/104338607/open-bookmarks-in-new-tab-by-default?hl=en

More as an exercise and less for real-life use, perhaps something like this (note: needs UIA_Interface.ahk):

Code: Select all

#NoEnv
SetWorkingDir %A_ScriptDir%

#include <UIA_Interface>
UIA := UIA_Interface(), URLBarName

#if WinActive("ahk_exe chrome.exe ahk_class Chrome_WidgetWin_1")
NumpadEnter::
Enter::
	if !URLBarName {
		try {
			cEl := UIA.ElementFromHandle(WinExist("A"))
			EditControlCondition := UIA.CreatePropertyCondition(UIA_ControlTypePropertyId := 30003, UIA_EditControlTypeId := 50004, VT_I4:=3)
			URLBarName := cEl.FindFirst(EditControlCondition).CurrentName
		} catch
			URLBarName := "Address and search bar"
	}
	try {
		el := UIA.GetFocusedElement()
		if (el.CurrentControlType == 50004) && (el.CurrentName == URLBarName) {
			Send, !{Enter}
			return
		}
	}	
	Send {Enter}
	return

#if ChromeUnderMouse()
LButton Up::Send, {LButton Up}
LButton::
    el := UIA.ElementFromPoint()
    if (el.LocalizedControlType == "Bookmark button") {
        MouseGetPos,,, wId
        el.ControlClick("ahk_id " wId,,"R")
        (butEl := UIA.ElementFromHandle("ahk_id " wId)).WaitElementExistByName("Open in new tab",,,,500).Click()
        if butEl {
            Sleep, 200
            Send, ^{Tab}
        } else
            Send, {LButton down}
    } else
        Send, {LButton down}
    return

ChromeUnderMouse() {
    MouseGetPos,,, wId
    WinGet, wExe, ProcessName, ahk_id %wId%
    return wExe == "chrome.exe"
}

cRsh
Posts: 2
Joined: 31 Jul 2022, 13:54

Re: Open a new tab from address bar in google chrome

Post by cRsh » 01 Aug 2022, 06:51

I'll give it a try. Thx.

Offtopic: Why is it more or less standard for all these chromium based browser out there? Is the google chrome browser restricted? Such simple options to switch on and off but für chrome you has to use third party apps and stuff.

cdull
Posts: 38
Joined: 11 Jan 2020, 07:34

Re: Open a new tab from address bar in google chrome

Post by cdull » 10 Aug 2022, 02:33

It seems chrome has changed something about the size of the top area. To get my script working again you have to change the chrome_check_result from 50 to 55

Old:

Code: Select all

#if WinActive("ahk_exe chrome.exe") ; Google Chrome
NumpadEnter::
Enter::
   KeyWait, enter, T0.2 ; Long press
   if (Errorlevel)
   {
         FileAppend, %A_ThisFunc%_longpress`n, %A_MyDocuments%\keyboardshortcuts_counter.txt
      sendinput {enter}
      return
   }
   else ; Single press
   {
      if WinActive("ahk_exe chrome.exe ahk_class Chrome_WidgetWin_1")
      {
         Acc_Caret := Acc_ObjectFromWindow(WinExist("ahk_class Chrome_WidgetWin_1"), OBJID_CARET := 0xFFFFFFF8)
         Caret_Location := Acc_Location(Acc_Caret)
         caret_check := Caret_Location.y
         WinGetPos,, chrome_y_check,,, A
         chrome_check_result := caret_check - chrome_y_check
         if chrome_check_result between -4 and 50 ; execute when at location bar
         {
            sendinput !{enter}
         }
         else ; execute when not at location bar
         {
            sendinput {enter}
         }
         return
      }
      else
      {
         sendinput {enter}
         return
      }
   }
   return
   
;------------------------------------------- Chrome Enter Helper --------------------------------------------

; http://www.autohotkey.com/board/topic/77303-acc-library-ahk-l-updated-09272012/
; https dl.dropbox.com /u/47573473/Web%20Server/AHK_L/Acc.ahk  Broken Link for safety
;------------------------------------------------------------------------------
; Acc.ahk Standard Library
; by Sean
; Updated by jethrow:
; 	Modified ComObjEnwrap params from (9,pacc) --> (9,pacc,1)
; 	Changed ComObjUnwrap to ComObjValue in order to avoid AddRef (thanks fincs)
; 	Added Acc_GetRoleText & Acc_GetStateText
; 	Added additional functions - commented below
; 	Removed original Acc_Children function
; last updated 2/25/2010
;------------------------------------------------------------------------------

Acc_Init()
{
	Static	h
	If Not	h
		h:=DllCall("LoadLibrary","Str","oleacc","Ptr")
}
Acc_ObjectFromEvent(ByRef _idChild_, hWnd, idObject, idChild)
{
	Acc_Init()
	If	DllCall("oleacc\AccessibleObjectFromEvent", "Ptr", hWnd, "UInt", idObject, "UInt", idChild, "Ptr*", pacc, "Ptr", VarSetCapacity(varChild,8+2*A_PtrSize,0)*0+&varChild)=0
	Return	ComObjEnwrap(9,pacc,1), _idChild_:=NumGet(varChild,8,"UInt")
}

Acc_ObjectFromPoint(ByRef _idChild_ = "", x = "", y = "")
{
	Acc_Init()
	If	DllCall("oleacc\AccessibleObjectFromPoint", "Int64", x==""||y==""?0*DllCall("GetCursorPos","Int64*",pt)+pt:x&0xFFFFFFFF|y<<32, "Ptr*", pacc, "Ptr", VarSetCapacity(varChild,8+2*A_PtrSize,0)*0+&varChild)=0
	Return	ComObjEnwrap(9,pacc,1), _idChild_:=NumGet(varChild,8,"UInt")
}

Acc_ObjectFromWindow(hWnd, idObject = -4)
{
	Acc_Init()
	If	DllCall("oleacc\AccessibleObjectFromWindow", "Ptr", hWnd, "UInt", idObject&=0xFFFFFFFF, "Ptr", -VarSetCapacity(IID,16)+NumPut(idObject==0xFFFFFFF0?0x46000000000000C0:0x719B3800AA000C81,NumPut(idObject==0xFFFFFFF0?0x0000000000020400:0x11CF3C3D618736E0,IID,"Int64"),"Int64"), "Ptr*", pacc)=0
	Return	ComObjEnwrap(9,pacc,1)
}

Acc_WindowFromObject(pacc)
{
	If	DllCall("oleacc\WindowFromAccessibleObject", "Ptr", IsObject(pacc)?ComObjValue(pacc):pacc, "Ptr*", hWnd)=0
	Return	hWnd
}

Acc_GetRoleText(nRole)
{
	nSize := DllCall("oleacc\GetRoleText", "Uint", nRole, "Ptr", 0, "Uint", 0)
	VarSetCapacity(sRole, (A_IsUnicode?2:1)*nSize)
	DllCall("oleacc\GetRoleText", "Uint", nRole, "str", sRole, "Uint", nSize+1)
	Return	sRole
}

Acc_GetStateText(nState)
{
	nSize := DllCall("oleacc\GetStateText", "Uint", nState, "Ptr", 0, "Uint", 0)
	VarSetCapacity(sState, (A_IsUnicode?2:1)*nSize)
	DllCall("oleacc\GetStateText", "Uint", nState, "str", sState, "Uint", nSize+1)
	Return	sState
}

Acc_SetWinEventHook(eventMin, eventMax, pCallback)
{
	Return	DllCall("SetWinEventHook", "Uint", eventMin, "Uint", eventMax, "Uint", 0, "Ptr", pCallback, "Uint", 0, "Uint", 0, "Uint", 0)
}

Acc_UnhookWinEvent(hHook)
{
	Return	DllCall("UnhookWinEvent", "Ptr", hHook)
}
/*	Win Events:

	pCallback := RegisterCallback("WinEventProc")
	WinEventProc(hHook, event, hWnd, idObject, idChild, eventThread, eventTime)
	{
		Critical
		Acc := Acc_ObjectFromEvent(_idChild_, hWnd, idObject, idChild)
		; Code Here:

	}
*/

; Written by jethrow
Acc_Role(Acc, ChildId=0) {
	try return ComObjType(Acc,"Name")="IAccessible"?Acc_GetRoleText(Acc.accRole(ChildId)):"invalid object"
}
Acc_State(Acc, ChildId=0) {
	try return ComObjType(Acc,"Name")="IAccessible"?Acc_GetStateText(Acc.accState(ChildId)):"invalid object"
}
Acc_Location(Acc, ChildId=0, byref Position="") { ; adapted from Sean's code
	try Acc.accLocation(ComObj(0x4003,&x:=0), ComObj(0x4003,&y:=0), ComObj(0x4003,&w:=0), ComObj(0x4003,&h:=0), ChildId)
	catch
		return
	Position := "x" NumGet(x,0,"int") " y" NumGet(y,0,"int") " w" NumGet(w,0,"int") " h" NumGet(h,0,"int")
	return	{x:NumGet(x,0,"int"), y:NumGet(y,0,"int"), w:NumGet(w,0,"int"), h:NumGet(h,0,"int")}
}
Acc_Parent(Acc) { 
	try parent:=Acc.accParent
	return parent?Acc_Query(parent):
}
Acc_Child(Acc, ChildId=0) {
	try child:=Acc.accChild(ChildId)
	return child?Acc_Query(child):
}
Acc_Query(Acc) { ; thanks Lexikos - www.autohotkey.com/forum/viewtopic.php?t=81731&p=509530#509530
	try return ComObj(9, ComObjQuery(Acc,"{618736e0-3c3d-11cf-810c-00aa00389b71}"), 1)
}
Acc_Error(p="") {
	static setting:=0
	return p=""?setting:setting:=p
}
Acc_Children(Acc) {
	if ComObjType(Acc,"Name") != "IAccessible"
		ErrorLevel := "Invalid IAccessible Object"
	else {
		Acc_Init(), cChildren:=Acc.accChildCount, Children:=[]
		if DllCall("oleacc\AccessibleChildren", "Ptr",ComObjValue(Acc), "Int",0, "Int",cChildren, "Ptr",VarSetCapacity(varChildren,cChildren*(8+2*A_PtrSize),0)*0+&varChildren, "Int*",cChildren)=0 {
			Loop %cChildren%
				i:=(A_Index-1)*(A_PtrSize*2+8)+8, child:=NumGet(varChildren,i), Children.Insert(NumGet(varChildren,i-8)=9?Acc_Query(child):child), NumGet(varChildren,i-8)=9?ObjRelease(child):
			return Children.MaxIndex()?Children:
		} else
			ErrorLevel := "AccessibleChildren DllCall Failed"
	}
	if Acc_Error()
		throw Exception(ErrorLevel,-1)
}
Acc_ChildrenByRole(Acc, Role) {
	if ComObjType(Acc,"Name")!="IAccessible"
		ErrorLevel := "Invalid IAccessible Object"
	else {
		Acc_Init(), cChildren:=Acc.accChildCount, Children:=[]
		if DllCall("oleacc\AccessibleChildren", "Ptr",ComObjValue(Acc), "Int",0, "Int",cChildren, "Ptr",VarSetCapacity(varChildren,cChildren*(8+2*A_PtrSize),0)*0+&varChildren, "Int*",cChildren)=0 {
			Loop %cChildren% {
				i:=(A_Index-1)*(A_PtrSize*2+8)+8, child:=NumGet(varChildren,i)
				if NumGet(varChildren,i-8)=9
					AccChild:=Acc_Query(child), ObjRelease(child), Acc_Role(AccChild)=Role?Children.Insert(AccChild):
				else
					Acc_Role(Acc, child)=Role?Children.Insert(child):
			}
			return Children.MaxIndex()?Children:, ErrorLevel:=0
		} else
			ErrorLevel := "AccessibleChildren DllCall Failed"
	}
	if Acc_Error()
		throw Exception(ErrorLevel,-1)
}
Acc_Get(Cmd, ChildPath="", ChildID=0, WinTitle="", WinText="", ExcludeTitle="", ExcludeText="") {
	static properties := {Action:"DefaultAction", DoAction:"DoDefaultAction", Keyboard:"KeyboardShortcut"}
	AccObj :=   IsObject(WinTitle)? WinTitle
			:   Acc_ObjectFromWindow( WinExist(WinTitle, WinText, ExcludeTitle, ExcludeText), 0 )
	if ComObjType(AccObj, "Name") != "IAccessible"
		ErrorLevel := "Could not access an IAccessible Object"
	else {
		StringReplace, ChildPath, ChildPath, _, %A_Space%, All
		AccError:=Acc_Error(), Acc_Error(true)
		Loop Parse, ChildPath, ., %A_Space%
			try {
				if A_LoopField is digit
					Children:=Acc_Children(AccObj), m2:=A_LoopField ; mimic "m2" output in else-statement
				else
					RegExMatch(A_LoopField, "(\D*)(\d*)", m), Children:=Acc_ChildrenByRole(AccObj, m1), m2:=(m2?m2:1)
				if Not Children.HasKey(m2)
					throw
				AccObj := Children[m2]
			} catch {
				ErrorLevel:="Cannot access ChildPath Item #" A_Index " -> " A_LoopField, Acc_Error(AccError)
				if Acc_Error()
					throw Exception("Cannot access ChildPath Item", -1, "Item #" A_Index " -> " A_LoopField)
				return
			}
		Acc_Error(AccError)
		StringReplace, Cmd, Cmd, %A_Space%, , All
		properties.HasKey(Cmd)? Cmd:=properties[Cmd]:
		try {
			if (Cmd = "Location")
				AccObj.accLocation(ComObj(0x4003,&x:=0), ComObj(0x4003,&y:=0), ComObj(0x4003,&w:=0), ComObj(0x4003,&h:=0), ChildId)
			  , ret_val := "x" NumGet(x,0,"int") " y" NumGet(y,0,"int") " w" NumGet(w,0,"int") " h" NumGet(h,0,"int")
			else if (Cmd = "Object")
				ret_val := AccObj
			else if Cmd in Role,State
				ret_val := Acc_%Cmd%(AccObj, ChildID+0)
			else if Cmd in ChildCount,Selection,Focus
				ret_val := AccObj["acc" Cmd]
			else
				ret_val := AccObj["acc" Cmd](ChildID+0)
		} catch {
			ErrorLevel := """" Cmd """ Cmd Not Implemented"
			if Acc_Error()
				throw Exception("Cmd Not Implemented", -1, Cmd)
			return
		}
		return ret_val, ErrorLevel:=0
	}
	if Acc_Error()
		throw Exception(ErrorLevel,-1)
}

return
New:

Code: Select all

#if WinActive("ahk_exe chrome.exe") ; Google Chrome
NumpadEnter::
Enter::
   KeyWait, enter, T0.2 ; Long press
   if (Errorlevel)
   {
         FileAppend, %A_ThisFunc%_longpress`n, %A_MyDocuments%\keyboardshortcuts_counter.txt
      sendinput {enter}
      return
   }
   else ; Single press
   {
      if WinActive("ahk_exe chrome.exe ahk_class Chrome_WidgetWin_1")
      {
         Acc_Caret := Acc_ObjectFromWindow(WinExist("ahk_class Chrome_WidgetWin_1"), OBJID_CARET := 0xFFFFFFF8)
         Caret_Location := Acc_Location(Acc_Caret)
         caret_check := Caret_Location.y
         WinGetPos,, chrome_y_check,,, A
         chrome_check_result := caret_check - chrome_y_check
         if chrome_check_result between -4 and 55 ; execute when at location bar
         {
            sendinput !{enter}
         }
         else ; execute when not at location bar
         {
            sendinput {enter}
         }
         return
      }
      else
      {
         sendinput {enter}
         return
      }
   }
   return
   
;------------------------------------------- Chrome Enter Helper --------------------------------------------

; http://www.autohotkey.com/board/topic/77303-acc-library-ahk-l-updated-09272012/
; https dl.dropbox.com /u/47573473/Web%20Server/AHK_L/Acc.ahk  Broken Link for safety
;------------------------------------------------------------------------------
; Acc.ahk Standard Library
; by Sean
; Updated by jethrow:
; 	Modified ComObjEnwrap params from (9,pacc) --> (9,pacc,1)
; 	Changed ComObjUnwrap to ComObjValue in order to avoid AddRef (thanks fincs)
; 	Added Acc_GetRoleText & Acc_GetStateText
; 	Added additional functions - commented below
; 	Removed original Acc_Children function
; last updated 2/25/2010
;------------------------------------------------------------------------------

Acc_Init()
{
	Static	h
	If Not	h
		h:=DllCall("LoadLibrary","Str","oleacc","Ptr")
}
Acc_ObjectFromEvent(ByRef _idChild_, hWnd, idObject, idChild)
{
	Acc_Init()
	If	DllCall("oleacc\AccessibleObjectFromEvent", "Ptr", hWnd, "UInt", idObject, "UInt", idChild, "Ptr*", pacc, "Ptr", VarSetCapacity(varChild,8+2*A_PtrSize,0)*0+&varChild)=0
	Return	ComObjEnwrap(9,pacc,1), _idChild_:=NumGet(varChild,8,"UInt")
}

Acc_ObjectFromPoint(ByRef _idChild_ = "", x = "", y = "")
{
	Acc_Init()
	If	DllCall("oleacc\AccessibleObjectFromPoint", "Int64", x==""||y==""?0*DllCall("GetCursorPos","Int64*",pt)+pt:x&0xFFFFFFFF|y<<32, "Ptr*", pacc, "Ptr", VarSetCapacity(varChild,8+2*A_PtrSize,0)*0+&varChild)=0
	Return	ComObjEnwrap(9,pacc,1), _idChild_:=NumGet(varChild,8,"UInt")
}

Acc_ObjectFromWindow(hWnd, idObject = -4)
{
	Acc_Init()
	If	DllCall("oleacc\AccessibleObjectFromWindow", "Ptr", hWnd, "UInt", idObject&=0xFFFFFFFF, "Ptr", -VarSetCapacity(IID,16)+NumPut(idObject==0xFFFFFFF0?0x46000000000000C0:0x719B3800AA000C81,NumPut(idObject==0xFFFFFFF0?0x0000000000020400:0x11CF3C3D618736E0,IID,"Int64"),"Int64"), "Ptr*", pacc)=0
	Return	ComObjEnwrap(9,pacc,1)
}

Acc_WindowFromObject(pacc)
{
	If	DllCall("oleacc\WindowFromAccessibleObject", "Ptr", IsObject(pacc)?ComObjValue(pacc):pacc, "Ptr*", hWnd)=0
	Return	hWnd
}

Acc_GetRoleText(nRole)
{
	nSize := DllCall("oleacc\GetRoleText", "Uint", nRole, "Ptr", 0, "Uint", 0)
	VarSetCapacity(sRole, (A_IsUnicode?2:1)*nSize)
	DllCall("oleacc\GetRoleText", "Uint", nRole, "str", sRole, "Uint", nSize+1)
	Return	sRole
}

Acc_GetStateText(nState)
{
	nSize := DllCall("oleacc\GetStateText", "Uint", nState, "Ptr", 0, "Uint", 0)
	VarSetCapacity(sState, (A_IsUnicode?2:1)*nSize)
	DllCall("oleacc\GetStateText", "Uint", nState, "str", sState, "Uint", nSize+1)
	Return	sState
}

Acc_SetWinEventHook(eventMin, eventMax, pCallback)
{
	Return	DllCall("SetWinEventHook", "Uint", eventMin, "Uint", eventMax, "Uint", 0, "Ptr", pCallback, "Uint", 0, "Uint", 0, "Uint", 0)
}

Acc_UnhookWinEvent(hHook)
{
	Return	DllCall("UnhookWinEvent", "Ptr", hHook)
}
/*	Win Events:

	pCallback := RegisterCallback("WinEventProc")
	WinEventProc(hHook, event, hWnd, idObject, idChild, eventThread, eventTime)
	{
		Critical
		Acc := Acc_ObjectFromEvent(_idChild_, hWnd, idObject, idChild)
		; Code Here:

	}
*/

; Written by jethrow
Acc_Role(Acc, ChildId=0) {
	try return ComObjType(Acc,"Name")="IAccessible"?Acc_GetRoleText(Acc.accRole(ChildId)):"invalid object"
}
Acc_State(Acc, ChildId=0) {
	try return ComObjType(Acc,"Name")="IAccessible"?Acc_GetStateText(Acc.accState(ChildId)):"invalid object"
}
Acc_Location(Acc, ChildId=0, byref Position="") { ; adapted from Sean's code
	try Acc.accLocation(ComObj(0x4003,&x:=0), ComObj(0x4003,&y:=0), ComObj(0x4003,&w:=0), ComObj(0x4003,&h:=0), ChildId)
	catch
		return
	Position := "x" NumGet(x,0,"int") " y" NumGet(y,0,"int") " w" NumGet(w,0,"int") " h" NumGet(h,0,"int")
	return	{x:NumGet(x,0,"int"), y:NumGet(y,0,"int"), w:NumGet(w,0,"int"), h:NumGet(h,0,"int")}
}
Acc_Parent(Acc) { 
	try parent:=Acc.accParent
	return parent?Acc_Query(parent):
}
Acc_Child(Acc, ChildId=0) {
	try child:=Acc.accChild(ChildId)
	return child?Acc_Query(child):
}
Acc_Query(Acc) { ; thanks Lexikos - www.autohotkey.com/forum/viewtopic.php?t=81731&p=509530#509530
	try return ComObj(9, ComObjQuery(Acc,"{618736e0-3c3d-11cf-810c-00aa00389b71}"), 1)
}
Acc_Error(p="") {
	static setting:=0
	return p=""?setting:setting:=p
}
Acc_Children(Acc) {
	if ComObjType(Acc,"Name") != "IAccessible"
		ErrorLevel := "Invalid IAccessible Object"
	else {
		Acc_Init(), cChildren:=Acc.accChildCount, Children:=[]
		if DllCall("oleacc\AccessibleChildren", "Ptr",ComObjValue(Acc), "Int",0, "Int",cChildren, "Ptr",VarSetCapacity(varChildren,cChildren*(8+2*A_PtrSize),0)*0+&varChildren, "Int*",cChildren)=0 {
			Loop %cChildren%
				i:=(A_Index-1)*(A_PtrSize*2+8)+8, child:=NumGet(varChildren,i), Children.Insert(NumGet(varChildren,i-8)=9?Acc_Query(child):child), NumGet(varChildren,i-8)=9?ObjRelease(child):
			return Children.MaxIndex()?Children:
		} else
			ErrorLevel := "AccessibleChildren DllCall Failed"
	}
	if Acc_Error()
		throw Exception(ErrorLevel,-1)
}
Acc_ChildrenByRole(Acc, Role) {
	if ComObjType(Acc,"Name")!="IAccessible"
		ErrorLevel := "Invalid IAccessible Object"
	else {
		Acc_Init(), cChildren:=Acc.accChildCount, Children:=[]
		if DllCall("oleacc\AccessibleChildren", "Ptr",ComObjValue(Acc), "Int",0, "Int",cChildren, "Ptr",VarSetCapacity(varChildren,cChildren*(8+2*A_PtrSize),0)*0+&varChildren, "Int*",cChildren)=0 {
			Loop %cChildren% {
				i:=(A_Index-1)*(A_PtrSize*2+8)+8, child:=NumGet(varChildren,i)
				if NumGet(varChildren,i-8)=9
					AccChild:=Acc_Query(child), ObjRelease(child), Acc_Role(AccChild)=Role?Children.Insert(AccChild):
				else
					Acc_Role(Acc, child)=Role?Children.Insert(child):
			}
			return Children.MaxIndex()?Children:, ErrorLevel:=0
		} else
			ErrorLevel := "AccessibleChildren DllCall Failed"
	}
	if Acc_Error()
		throw Exception(ErrorLevel,-1)
}
Acc_Get(Cmd, ChildPath="", ChildID=0, WinTitle="", WinText="", ExcludeTitle="", ExcludeText="") {
	static properties := {Action:"DefaultAction", DoAction:"DoDefaultAction", Keyboard:"KeyboardShortcut"}
	AccObj :=   IsObject(WinTitle)? WinTitle
			:   Acc_ObjectFromWindow( WinExist(WinTitle, WinText, ExcludeTitle, ExcludeText), 0 )
	if ComObjType(AccObj, "Name") != "IAccessible"
		ErrorLevel := "Could not access an IAccessible Object"
	else {
		StringReplace, ChildPath, ChildPath, _, %A_Space%, All
		AccError:=Acc_Error(), Acc_Error(true)
		Loop Parse, ChildPath, ., %A_Space%
			try {
				if A_LoopField is digit
					Children:=Acc_Children(AccObj), m2:=A_LoopField ; mimic "m2" output in else-statement
				else
					RegExMatch(A_LoopField, "(\D*)(\d*)", m), Children:=Acc_ChildrenByRole(AccObj, m1), m2:=(m2?m2:1)
				if Not Children.HasKey(m2)
					throw
				AccObj := Children[m2]
			} catch {
				ErrorLevel:="Cannot access ChildPath Item #" A_Index " -> " A_LoopField, Acc_Error(AccError)
				if Acc_Error()
					throw Exception("Cannot access ChildPath Item", -1, "Item #" A_Index " -> " A_LoopField)
				return
			}
		Acc_Error(AccError)
		StringReplace, Cmd, Cmd, %A_Space%, , All
		properties.HasKey(Cmd)? Cmd:=properties[Cmd]:
		try {
			if (Cmd = "Location")
				AccObj.accLocation(ComObj(0x4003,&x:=0), ComObj(0x4003,&y:=0), ComObj(0x4003,&w:=0), ComObj(0x4003,&h:=0), ChildId)
			  , ret_val := "x" NumGet(x,0,"int") " y" NumGet(y,0,"int") " w" NumGet(w,0,"int") " h" NumGet(h,0,"int")
			else if (Cmd = "Object")
				ret_val := AccObj
			else if Cmd in Role,State
				ret_val := Acc_%Cmd%(AccObj, ChildID+0)
			else if Cmd in ChildCount,Selection,Focus
				ret_val := AccObj["acc" Cmd]
			else
				ret_val := AccObj["acc" Cmd](ChildID+0)
		} catch {
			ErrorLevel := """" Cmd """ Cmd Not Implemented"
			if Acc_Error()
				throw Exception("Cmd Not Implemented", -1, Cmd)
			return
		}
		return ret_val, ErrorLevel:=0
	}
	if Acc_Error()
		throw Exception(ErrorLevel,-1)
}

return

shipaddicted
Posts: 103
Joined: 15 Jul 2016, 19:57

Re: Open a new tab from address bar in google chrome

Post by shipaddicted » 12 Sep 2022, 13:38

Huh. I never noticed this. My first response was, 'well, why couldn't you just do Ctrl+Enter to open in a new tab??' Tried it. Didn't work.

I love your script, but don't think I would want to have the page opening in a new tab every time. Most of the time it's perfectly fine to use the same tab. Would it work if you changed the hotkey to NumPadEnter or Ctrl+Enter to open in a new tab, but leave the Enter key to open the new page normally?

carno
Posts: 265
Joined: 20 Jun 2014, 16:48

Re: Open a new tab from address bar in google chrome

Post by carno » 12 Sep 2022, 15:09

shipaddicted wrote:
12 Sep 2022, 13:38
Huh. I never noticed this. My first response was, 'well, why couldn't you just do Ctrl+Enter to open in a new tab??' Tried it. Didn't work.

I love your script, but don't think I would want to have the page opening in a new tab every time. Most of the time it's perfectly fine to use the same tab. Would it work if you changed the hotkey to NumPadEnter or Ctrl+Enter to open in a new tab, but leave the Enter key to open the new page normally?
Why not trying Ctrl+t ? It opens a new tab in Chrome.

shipaddicted
Posts: 103
Joined: 15 Jul 2016, 19:57

Re: Open a new tab from address bar in google chrome

Post by shipaddicted » 12 Sep 2022, 20:39

carno wrote:
12 Sep 2022, 15:09
shipaddicted wrote:
12 Sep 2022, 13:38
Huh. I never noticed this. My first response was, 'well, why couldn't you just do Ctrl+Enter to open in a new tab??' Tried it. Didn't work.

I love your script, but don't think I would want to have the page opening in a new tab every time. Most of the time it's perfectly fine to use the same tab. Would it work if you changed the hotkey to NumPadEnter or Ctrl+Enter to open in a new tab, but leave the Enter key to open the new page normally?
Why not trying Ctrl+t ? It opens a new tab in Chrome.
you are correct! sometimes you forget the obvious when looking for something 'deeper' LOL !!

But here's a CHALLENGE QUESTION for you:

;)

^t works when I know I want whatever I'm searching for to open in a new tab (cos I would type ^t before entering my search data, obv) , but what about when I'm already typing in the address bar and **then** decide I want the results to open in a new tab? Any suggestions for saving my wasted keystrokes & open whatever I've already typed into a new tab without having to stop & start over?

(former medical transcriptionist here -- each keystroke is $$$ ... & I'm stuck in the mindset of getting the most results from the fewest keystrokes!!)

carno
Posts: 265
Joined: 20 Jun 2014, 16:48

Re: Open a new tab from address bar in google chrome

Post by carno » 12 Sep 2022, 21:14

shipaddicted wrote:
12 Sep 2022, 20:39
carno wrote:
12 Sep 2022, 15:09
shipaddicted wrote:
12 Sep 2022, 13:38
Huh. I never noticed this. My first response was, 'well, why couldn't you just do Ctrl+Enter to open in a new tab??' Tried it. Didn't work.

I love your script, but don't think I would want to have the page opening in a new tab every time. Most of the time it's perfectly fine to use the same tab. Would it work if you changed the hotkey to NumPadEnter or Ctrl+Enter to open in a new tab, but leave the Enter key to open the new page normally?
Why not trying Ctrl+t ? It opens a new tab in Chrome.
you are correct! sometimes you forget the obvious when looking for something 'deeper' LOL !!

But here's a CHALLENGE QUESTION for you:

;)

^t works when I know I want whatever I'm searching for to open in a new tab (cos I would type ^t before entering my search data, obv) , but what about when I'm already typing in the address bar and **then** decide I want the results to open in a new tab? Any suggestions for saving my wasted keystrokes & open whatever I've already typed into a new tab without having to stop & start over?

(former medical transcriptionist here -- each keystroke is $$$ ... & I'm stuck in the mindset of getting the most results from the fewest keystrokes!!)
Easy. If you're already typing in the address bar and decide you want the results to open in a new tab: Ctrl+a followed by Ctrl+c followed by Ctrl+t followed by Ctrl+v followed by Enter!

shipaddicted
Posts: 103
Joined: 15 Jul 2016, 19:57

Re: Open a new tab from address bar in google chrome

Post by shipaddicted » 12 Sep 2022, 23:29

carno wrote:
12 Sep 2022, 21:14
shipaddicted wrote:
12 Sep 2022, 20:39
carno wrote:
12 Sep 2022, 15:09
shipaddicted wrote:
12 Sep 2022, 13:38
Huh. I never noticed this. My first response was, 'well, why couldn't you just do Ctrl+Enter to open in a new tab??' Tried it. Didn't work.

I love your script, but don't think I would want to have the page opening in a new tab every time. Most of the time it's perfectly fine to use the same tab. Would it work if you changed the hotkey to NumPadEnter or Ctrl+Enter to open in a new tab, but leave the Enter key to open the new page normally?
Why not trying Ctrl+t ? It opens a new tab in Chrome.
you are correct! sometimes you forget the obvious when looking for something 'deeper' LOL !!

But here's a CHALLENGE QUESTION for you:

;)

^t works when I know I want whatever I'm searching for to open in a new tab (cos I would type ^t before entering my search data, obv) , but what about when I'm already typing in the address bar and **then** decide I want the results to open in a new tab? Any suggestions for saving my wasted keystrokes & open whatever I've already typed into a new tab without having to stop & start over?

(former medical transcriptionist here -- each keystroke is $$$ ... & I'm stuck in the mindset of getting the most results from the fewest keystrokes!!)
Easy. If you're already typing in the address bar and decide you want the results to open in a new tab: Ctrl+a followed by Ctrl+c followed by Ctrl+t followed by Ctrl+v followed by Enter!
welp ... that's like 8 keystrokes ... but I spose one could create a hotkey to reduce it to 2 or 3 ... :eh:

shipaddicted
Posts: 103
Joined: 15 Jul 2016, 19:57

Re: Open a new tab from address bar in google chrome

Post by shipaddicted » 13 Sep 2022, 15:51

carno wrote:
12 Sep 2022, 21:14
Easy. If you're already typing in the address bar and decide you want the results to open in a new tab: Ctrl+a followed by Ctrl+c followed by Ctrl+t followed by Ctrl+v followed by Enter!
Here's my quick-n-dirty script for when I occasionally need to open whatever I just typed in the address bar in a new tab . I decided to just override the Shift+Enter option because I never very rarely want to open in a new window.

Code: Select all

+Enter:: 
If WinActive("ahk_class Chrome_WidgetWin_1") 
{
	tmpCB := ClipBoard 
	ClipBoard := "" 
	Send ^a^c 
	ClipWait, 4 
	url := ClipBoard 
	If !(InStr(url, "www."))
	{
		url := % "https://www.google.com/search?q='" . url . "'"
	}
	Run, % url 	
	ClipBoard := tmpCB  
} 
Return 
and if I want to go straight to the site but I was too lazy to enter 'www' & '.com':

Code: Select all

!Enter:: 
If WinActive("ahk_class Chrome_WidgetWin_1") 
{
	tmpCB := ClipBoard 
	ClipBoard := "" 
	Send ^a^c 
	ClipWait, 4 
	url := % ClipBoard 
	If !(InStr(url, "www."))
	{
		url := % "www." . trim(url) . ".com"
	}
		
	Run % url 	
	ClipBoard := tmpCB  
} 
Return 
I guess I'll write duplicates of these to open in a new window for those super rare instances that do come up by adding the Ctrl to the hotkeys.

Thanks for the idea!! :P

gimel
Posts: 18
Joined: 15 Aug 2022, 17:31

Re: Open a new tab from address bar in google chrome

Post by gimel » 15 Dec 2022, 15:42

I've tried several of the above codes, including changing 50 to 55 but address bar queries still not opening in a new tab - (msedge)

Post Reply

Return to “Scripts and Functions (v1)”