Detect clickable link in Chrome

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
teadrinker
Posts: 4326
Joined: 29 Mar 2015, 09:41
Contact:

Re: Detect clickable link in Chrome

07 May 2020, 17:34

MauroOfCol wrote: isn't that an XSS procedure?
I don't know if this can be thought of as XSS. In any case, I have not encountered any problems so far.
malcev
Posts: 1769
Joined: 12 Aug 2014, 12:37

Re: Detect clickable link in Chrome

07 May 2020, 19:23

It is not xss attack it is self-xss attack.
Therefore You cannot protect from it on server side.
You can protect from it only on client side.
AHKStudent
Posts: 1472
Joined: 05 May 2018, 12:23

Re: Detect clickable link in Chrome

07 May 2020, 20:36

teadrinker wrote:
07 May 2020, 17:34
MauroOfCol wrote: isn't that an XSS procedure?
I don't know if this can be thought of as XSS. In any case, I have not encountered any problems so far.
technically, can't you use this to scrape some data as well? The other day when the topic was getting the ebay listings, can I use something like this, modify the js and get the listings like that?

Edit: I think I see the problem, there is no way to get the data to show in a list view or anything, its only to show the data right in the browser using alert() in js etc, I think this is the reason why it cant be used.
Last edited by AHKStudent on 07 May 2020, 22:17, edited 1 time in total.
reverberation
Posts: 314
Joined: 13 Dec 2015, 20:48

Re: Detect clickable link in Chrome

07 May 2020, 21:18

teadrinker wrote:
07 May 2020, 10:08
In your code there is not something like «Click here to unsubscribe».

 Image

What I need is <a href="./viewtopic.php?p=327386#p327386">07 May 2020, 05:37</a>.
Hi there, I tried f12, inspect frame source etc and only searched for <a href links but there's none that ressembles the above:

https://i.imgur.com/Mg3NydT.png
reverberation
Posts: 314
Joined: 13 Dec 2015, 20:48

Re: Detect clickable link in Chrome

07 May 2020, 21:26

MauroOfCol wrote:
07 May 2020, 12:20
@reverberation Indeed this code does what is intended to do, I strongly recommend you to study the fundamentals of how websites work in order to advance in web scripting. Most websites are based on three pillars, HTML, CSS and JavaScript, the first one provides structure the second the visuals and the third the interactivity. Now this code goes in to the last category and works injecting some JS code directly in the website to retrieve the element that is required. Learning HTML and CSS is fast and easy, in a week you can get a good grasp on it, for JS I recommend the book Head First JavaScript Programming, A Brain Friendly Guide by Eric Freeman and Elisabeth Robson, this is the friendliest book I've seen about JS.

Now commenting code is it marketed as best practice, in reality it does nothing if the code itself is bad, hence the real good practice is produce good code that is high level, succinct, well indented or in other word easy to read and easy to maintain, looking at the code provided by teadrinker I can tell you that this code is high quality. In real life you comment code to remember specific things like fix or polish certain blocks or "TODO" things inside the code, why? because comments are lines of text that do nothing inside the code and when you are reading the code, the comment cuts the logical flow in your head.

This leads to some advice to improve your game. When naming variables be very specific about what the variable does, flp=0 is not easy to read it tells you nothing, flowerPots=0 gives you a real idea what the variable does, it is more typing but in the long run is easier to maintain, also, read the documentation, there is no way to stress this enough, the only way to get better at programming is understanding what the code does, so in top of reading the code line by line you need to understand the function of each word and character on its context, the best way to do so is experimenting with the concept unknown for you in a simple way and reading from the source what does that do (a.k.a. google it, then, trial and error).

Hope this helps in some way, programming is a long journey that requires lots of discipline and hard individual work.
Cool - I just bought the JS book you recommended. Hope to learn more from you guys too!

On a separate note, for button links that lead to a pop-up using JS, is it possible to add it to chrome search engine shortcuts, so that when I visit the URL, it directly opens the pop-up? Sample below (click on Ask a Question):

https://bit.ly/3dj2Lqi
teadrinker
Posts: 4326
Joined: 29 Mar 2015, 09:41
Contact:

Re: Detect clickable link in Chrome

08 May 2020, 12:58

AHKStudent wrote: technically, can't you use this to scrape some data as well? The other day when the topic was getting the ebay listings, can I use something like this, modify the js and get the listings like that?

Edit: I think I see the problem, there is no way to get the data to show in a list view or anything, its only to show the data right in the browser using alert() in js etc, I think this is the reason why it cant be used.
Of course, you can get the data to show in a list view using Clipboard and another methods. But I can't understand what is the problem you see retrieving data this way?
Last edited by teadrinker on 08 May 2020, 13:09, edited 1 time in total.
teadrinker
Posts: 4326
Joined: 29 Mar 2015, 09:41
Contact:

Re: Detect clickable link in Chrome

08 May 2020, 13:07

reverberation wrote: I tried f12, inspect frame source etc and only searched for <a href links
You don't need to search for <a href or something like this manually. You need to open DevTools, click this icon Image, and then place the cursor on the link you interested in. Then its HTML will be highlited on the right.
reverberation
Posts: 314
Joined: 13 Dec 2015, 20:48

Re: Detect clickable link in Chrome

08 May 2020, 23:37

teadrinker wrote:
08 May 2020, 13:07
reverberation wrote: I tried f12, inspect frame source etc and only searched for <a href links
You don't need to search for <a href or something like this manually. You need to open DevTools, click this icon Image, and then place the cursor on the link you interested in. Then its HTML will be highlited on the right.
alright, there you go:

https://i.imgur.com/FGXHmAq.png
https://i.imgur.com/vbPsUEE.png
AHKStudent
Posts: 1472
Joined: 05 May 2018, 12:23

Re: Detect clickable link in Chrome

09 May 2020, 08:25

Removed my post as @swagfag pointed out I overlooked the post with info
Last edited by AHKStudent on 09 May 2020, 09:11, edited 1 time in total.
AHKStudent
Posts: 1472
Joined: 05 May 2018, 12:23

Re: Detect clickable link in Chrome

09 May 2020, 09:10

swagfag wrote:
09 May 2020, 08:49
he already posted code that does that
https://www.autohotkey.com/boards/viewtopic.php?p=326962#p326962
sorry overlooked that, thanks
teadrinker
Posts: 4326
Joined: 29 Mar 2015, 09:41
Contact:

Re: Detect clickable link in Chrome

10 May 2020, 13:50

I need you show a bit more tags below them.
Can you expand this node? :)
SOTE
Posts: 1426
Joined: 15 Jun 2015, 06:21

Re: Detect clickable link in Chrome

11 May 2020, 02:49

This post has me a bit confused. To me the advantage of sending JavaScript is to do something that couldn't be done otherwise or you are trying to automate the browser in the background. However, in looking at reverberation's original code and the picture, it looks like "here" was the hyperlinked word. "Control F" should open search, then you send the word "Here", then send {enter}. This would highlight and get you to the word "here". You would have to press "{esc}" and "{enter}" again, because you have to exit the search box, before you can use enter to activate the link. You might also have to send "Tab" multiple times if there is multiple occurrences of the word. You could also send "Click Here" to the search box, which would likely give you only one occurrence. Seems like this could have been done just using AutoHotkey, and with code somewhat similar to what he originally try to use. Though don't get me wrong, also being able to use JavaScript is cool too.

Code: Select all

Send, ^f
Sleep 200
SendInput, {Raw}Here  ; or send Click Here
Sleep 200
SendInput, {enter}
Sleep 200
Sendinput, {esc}
Sleep 200
SendInput, {enter}
return
reverberation wrote:
04 May 2020, 22:43
I made this script to quickly unsubscribe from junk emails within Gmail. However, there are times where the email puts the link in "CLICK HERE" instead of "Unsubscribe". How do I improve on the code to cater for BOTH situations?

Image

Code: Select all

#If WinActive("ahk_exe Chrome.exe") ;Find Unsubscribe Button hit it
^u:: 
Send ^f
Sleep 200
SendInput Unsubscribe
Sendinput {esc}
Sleep 100
SendInput ^{enter}
return
burque505
Posts: 1734
Joined: 22 Jan 2017, 19:37

Re: Detect clickable link in Chrome

30 Jun 2020, 16:26

@teadrinker, thank you very much for your code. It's very inspiring. Here is a small GUI I made to use it. Still needs work, as it needs to be modified to scrape each site.
Bloomberg has a habit of blocking my scrapes if I try too many in a row, by the way.

GUI, which can be resized, looks like this:

GUI.PNG
GUI.PNG (23.62 KiB) Viewed 4729 times
The code below uses a dynamic CSS selector.

Code: Select all

SetBatchLines, -1
#SingleInstance, Force

; +----------------------------------------------------------------+
; ¦  Thank you, @teadrinker, for the code at                       ¦
; ¦  https://www.autohotkey.com/boards/viewtopic.php?f=76&t=75527  ¦
; +----------------------------------------------------------------+

; +--------------------------------------------------------------------------+
; ¦  URL is https://www.bloomberg.com/markets/stocks/world-indexes/americas  ¦
; ¦  := "'tbody.data-table-body > tr.data-table-row'"                        ¦
; ¦                                                                          ¦
; +--------------------------------------------------------------------------+

selector := "'tbody.data-table-body > tr.data-table-row'"

; +------------------------------------------------------------+
; ¦  You can use dynamic selectors in the Javascript as shown  ¦
; +------------------------------------------------------------+

js =
(
var items = document.querySelectorAll(%selector%);
var docStr = "";
items.forEach(function(element){
    docStr += element.innerText + "\n";
    });
   (() => {
      if (window.location.protocol === 'https:') {
         document.documentElement.focus();
         const timer = setInterval(() => {
            if (document.hasFocus()) {
               clearInterval(timer);
               navigator.clipboard.writeText(docStr);
            }
         }, 10);
      }
      else {
         const textArea = document.createElement('textarea');
         textArea.value = docStr;
         textArea.wrap = 'off';
         textArea.rows = 100000;
         textArea.style.position = 'fixed';
         document.documentElement.appendChild(textArea);
         textArea.focus();
         textArea.select();
         document.execCommand('copy');
         textArea.parentNode.removeChild(textArea);
      }
   })();
)

; +-------------------------------------------+
; ¦  Code for determining screen position.    ¦
; ¦  On my system it's just where I want it;  ¦
; ¦  at the bottom of the screen, just above  ¦
; ¦  the task bar. Modify to suit.            ¦
; +-------------------------------------------+

xpos := (A_ScreenWidth / 2) -200
ypos := A_ScreenHeight - 380

Gui, New,  +Resize hwndGuiHwnd
Gui, Add, Text, , Enter your Javascript below.
Gui, Add, Edit, xp y+5 vJavascript +Multi +0x100000 w375 h150, %js%
Gui, Add, Button, xp y+5 gRunJavascript vRunButton, Run &Javascript in Chrome
Gui, Show, w400 h200 x%xpos% y%ypos%, Chrome Javascript Injector

return

; +----------------------+
; ¦  Exit possibilities  ¦
; +----------------------+

!Escape::
GuiClose:
ExitApp
return


RunJavascript:
If !(WinExist("ahk_class ahk_class Chrome_WidgetWin_1")) {
   msgbox Please run Chrome before injecting Javascript.
   return
} Else {
Gui, Submit, NoHide
Clipboard := ""
RunJsFromChromeAddressBar(Javascript)
ClipWait, 2

; +-----------------------------------------------------------------------------+
; ¦  This is more in keeping with @teadrinker's original code:                   ¦
; ¦  msgbox, , Table Results, % ErrorLevel ? "Failed to get value" : Clipboard  ¦
; +-----------------------------------------------------------------------------+

; +-----------------------------------------------------------------------------+
; ¦  The code below is from another version that uses msgbox to show results.   ¦
; ¦  Uncomment this and comment out the Excel-related code to use that method.  ¦
; +-----------------------------------------------------------------------------+

xl := ComObjCreate("Excel.Application")
xl.Visible := true
xl.Workbooks.Add
sleep 3000
send, ^v
return
}

; +-------------------------------------------+
; ¦  Resize code using @tmplinshi's AutoXYWH  ¦
; +-------------------------------------------+

GuiSize:
	If (A_EventInfo = 1) ; The window has been minimized.
		Return
	AutoXYWH("wh", "Javascript")
	AutoXYWH("y", "RunButton")
return


; +----------------------------------------------------+
; ¦  My choices for showing and hiding the GUI.        ¦
; ¦  Modify to suit, or you can always use the mouse.  ¦
; +----------------------------------------------------+

LAlt & RWin::WinActivate, ahk_id %GuiHwnd%
RAlt & RWin::WinMinimize, ahk_id %GuiHwnd%


; +-------------------------------------------------+
; ¦  This is also from @teadrinker's original code  ¦
; ¦  $+F1:: RunJsFromChromeAddressBar(Javascript)   ¦
; +-------------------------------------------------+


; +------------------------------------------+
; ¦  @teadrinker code from here to the end.  ¦
; ¦  Thanks again!                           ¦
; +------------------------------------------+

RunJsFromChromeAddressBar(js, exe := "chrome.exe") {
   static WM_GETOBJECT := 0x3D
        , ROLE_SYSTEM_TEXT := 0x2A
        , STATE_SYSTEM_FOCUSABLE := 0x100000
        , SELFLAG_TAKEFOCUS := 0x1
   if !AccAddrBar {
      window := "ahk_class Chrome_WidgetWin_1 ahk_exe " . exe
      SendMessage, WM_GETOBJECT, 0, 1, Chrome_RenderWidgetHostHWND1, % window
      AccChrome := AccObjectFromWindow( WinExist(window) )
      AccAddrBar := SearchElement(AccChrome, {Role: ROLE_SYSTEM_TEXT, State: STATE_SYSTEM_FOCUSABLE})
   }
   AccAddrBar.accValue(0) := "javascript:" . js
   AccAddrBar.accSelect(SELFLAG_TAKEFOCUS, 0)
   ControlSend,, {Enter}, % window, Chrome Legacy Window
}

SearchElement(parentElement, params)
{
   found := true
   for k, v in params {
      try {
         if (k = "ChildCount")
            (parentElement.accChildCount != v && found := false)
         else if (k = "State")
            (!(parentElement.accState(0) & v) && found := false)
         else
            (parentElement["acc" . k](0) != v && found := false)
      }
      catch 
         found := false
   } until !found
   if found
      Return parentElement
   
   for k, v in AccChildren(parentElement)
      if obj := SearchElement(v, params)
         Return obj
}

AccObjectFromWindow(hWnd, idObject = 0) {
   static IID_IDispatch   := "{00020400-0000-0000-C000-000000000046}"
        , IID_IAccessible := "{618736E0-3C3D-11CF-810C-00AA00389B71}"
        , OBJID_NATIVEOM  := 0xFFFFFFF0, VT_DISPATCH := 9, F_OWNVALUE := 1
        , h := DllCall("LoadLibrary", "Str", "oleacc", "Ptr")
        
   VarSetCapacity(IID, 16), idObject &= 0xFFFFFFFF
   DllCall("ole32\CLSIDFromString", "Str", idObject = OBJID_NATIVEOM ? IID_IDispatch : IID_IAccessible, "Ptr", &IID)
   if DllCall("oleacc\AccessibleObjectFromWindow", "Ptr", hWnd, "UInt", idObject, "Ptr", &IID, "PtrP", pAcc) = 0
      Return ComObject(VT_DISPATCH, pAcc, F_OWNVALUE)
}

AccChildren(Acc) {
   static VT_DISPATCH := 9
   Loop 1  {
      if ComObjType(Acc, "Name") != "IAccessible"  {
         error := "Invalid IAccessible Object"
         break
      }
      try cChildren := Acc.accChildCount
      catch
         Return ""
      Children := []
      VarSetCapacity(varChildren, cChildren*(8 + A_PtrSize*2), 0)
      res := DllCall("oleacc\AccessibleChildren", "Ptr", ComObjValue(Acc), "Int", 0
                                                , "Int", cChildren, "Ptr", &varChildren, "IntP", cChildren)
      if (res != 0) {
         error := "AccessibleChildren DllCall Failed"
         break
      }
      Loop % cChildren  {
         i := (A_Index - 1)*(A_PtrSize*2 + 8)
         child := NumGet(varChildren, i + 8)
         Children.Push( (b := NumGet(varChildren, i) = VT_DISPATCH) ? AccQuery(child) : child )
         ( b && ObjRelease(child) )
      }
   }
   if error
      ErrorLevel := error
   else
      Return Children.MaxIndex() ? Children : ""
}

AccQuery(Acc) {
   static IAccessible := "{618736e0-3c3d-11cf-810c-00aa00389b71}", VT_DISPATCH := 9, F_OWNVALUE := 1
   try Return ComObject(VT_DISPATCH, ComObjQuery(Acc, IAccessible), F_OWNVALUE)
}

AutoXYWH(DimSize, cList*){       ; http://ahkscript.org/boards/viewtopic.php?t=1079
  static cInfo := {}
 
  If (DimSize = "reset")
    Return cInfo := {}
 
  For i, ctrl in cList {
    ctrlID := A_Gui ":" ctrl
    If ( cInfo[ctrlID].x = "" ){
        GuiControlGet, i, %A_Gui%:Pos, %ctrl%
        MMD := InStr(DimSize, "*") ? "MoveDraw" : "Move"
        fx := fy := fw := fh := 0
        For i, dim in (a := StrSplit(RegExReplace(DimSize, "i)[^xywh]")))
            If !RegExMatch(DimSize, "i)" dim "\s*\K[\d.-]+", f%dim%)
              f%dim% := 1
        cInfo[ctrlID] := { x:ix, fx:fx, y:iy, fy:fy, w:iw, fw:fw, h:ih, fh:fh, gw:A_GuiWidth, gh:A_GuiHeight, a:a , m:MMD}
    }Else If ( cInfo[ctrlID].a.1) {
        dgx := dgw := A_GuiWidth  - cInfo[ctrlID].gw  , dgy := dgh := A_GuiHeight - cInfo[ctrlID].gh
        For i, dim in cInfo[ctrlID]["a"]
            Options .= dim (dg%dim% * cInfo[ctrlID]["f" dim] + cInfo[ctrlID][dim]) A_Space
        GuiControl, % A_Gui ":" cInfo[ctrlID].m , % ctrl, % Options
} } }
Animated GIF: here.

EDIT: A previous version with the 'msgbox' technique.
Spoiler
Regards,
burque505
Last edited by burque505 on 30 Jun 2020, 16:36, edited 1 time in total.
burque505
Posts: 1734
Joined: 22 Jan 2017, 19:37

Re: Detect clickable link in Chrome

30 Jun 2020, 17:35

@teadrinker, :salute: :D

Please take a look at this animated GIF. It uses a minified version of the code by George McKerron that uses some cool techniques and uses a text area too, just as yours does. I used the second GUI version above for it (I think ...) :?: The code by Mr. McKerron deliberately lets variables leak into the global namespace ...

I minified it because I was getting an 'unexpected end of input' error, so maybe there's an upper limit on what Chrome will accept in the address bar.

Minified JS for the GUI:
Spoiler
Animated GIF: here.

Regards,
burque505
teadrinker
Posts: 4326
Joined: 29 Mar 2015, 09:41
Contact:

Re: Detect clickable link in Chrome

30 Jun 2020, 18:56

Interesting techniques :) Here is my more complicated example, which demonstrates a way to copy data from a page to the AHK variable directly.
burque505
Posts: 1734
Joined: 22 Jan 2017, 19:37

Re: Detect clickable link in Chrome

30 Jun 2020, 20:52

:thumbup: Working here on Win7 SP1 64-bit, latest Chrome, latest Edge!
AHKStudent
Posts: 1472
Joined: 05 May 2018, 12:23

Re: Detect clickable link in Chrome

30 Jun 2020, 23:11

@burque505

That worked well for me on bloomberg. It actually has many use cases.

Would it work on a site like this?
https://www.dropcatch.com/auctions

I tried

Code: Select all

selector := "'div.ng-tns-c178-10 ng-trigger ng-trigger-listStagger > div.table-list-item ng-tns-c178-10 ng-star-inserted'"
But no luck (it didnt put anything in clipboard)
burque505
Posts: 1734
Joined: 22 Jan 2017, 19:37

Re: Detect clickable link in Chrome

01 Jul 2020, 07:09

@AHKStudent, this will get your data, just tried it. But it contains newlines, so you'll have to transform the data to get rid of them.

Code: Select all

selector := "'div.table-list-item'"
EDIT: Here's a version for you that will work on Dropcatch and put the values in an Excel sheet.
Take a look at the top of the edited default Javascript. This section replaces all newlines with tabs as preprocessing, so pasting it into Excel will format more or less correctly.
(Snippet only)

Code: Select all

var items = document.querySelectorAll(%selector%);
var docStr = "";
var tmp = "";
var res = "";
items.forEach(function(element){
   tmp = element.innerText;
   res = tmp.replace(/(\r\n|\n|\r)/gm, "\t");
    docStr += res + "\n";
    });
Full GUI code:

Code: Select all

SetBatchLines, -1
#SingleInstance, Force

; +----------------------------------------------------------------+
; ¦  Thank you, @teadrinker, for the code at                       ¦
; ¦  https://www.autohotkey.com/boards/viewtopic.php?f=76&t=75527  ¦
; +----------------------------------------------------------------+

; +--------------------------------------------------------------------------+
; ¦  URL is https://www.dropcatch.com/auctions                               ¦
; ¦  := "'tbody.data-table-body > tr.data-table-row'"                        ¦
; ¦                                                                          ¦
; +--------------------------------------------------------------------------+

selector := "'div.table-list-item'"   

; +------------------------------------------------------------+
; ¦  You can use dynamic selectors in the Javascript as shown  ¦
; +------------------------------------------------------------+

js =
(
var items = document.querySelectorAll(%selector%);
var docStr = "";
var tmp = "";
var res = "";
items.forEach(function(element){
   tmp = element.innerText;
   res = tmp.replace(/(\r\n|\n|\r)/gm, "\t");
    docStr += res + "\n";
    });
   (() => {
      if (window.location.protocol === 'https:') {
         document.documentElement.focus();
         const timer = setInterval(() => {
            if (document.hasFocus()) {
               clearInterval(timer);
               navigator.clipboard.writeText(docStr);
            }
         }, 10);
      }
      else {
         const textArea = document.createElement('textarea');
         textArea.value = docStr;
         textArea.wrap = 'off';
         textArea.rows = 100000;
         textArea.style.position = 'fixed';
         document.documentElement.appendChild(textArea);
         textArea.focus();
         textArea.select();
         document.execCommand('copy');
         textArea.parentNode.removeChild(textArea);
      }
   })();
)

; +-------------------------------------------+
; ¦  Code for determining screen position.    ¦
; ¦  On my system it's just where I want it;  ¦
; ¦  at the bottom of the screen, just above  ¦
; ¦  the task bar. Modify to suit.            ¦
; +-------------------------------------------+

xpos := (A_ScreenWidth / 2) -200
ypos := A_ScreenHeight - 420

Gui, New,  +Resize hwndGuiHwnd
Gui, Add, Text, x10, Enter a selector.
Gui, Add, Edit, xp y+5 vSelector w375 +Multi, %selector%
Gui, Add, Text, xp y+5, Enter your Javascript below.
Gui, Add, Edit, xp y+5 vJavascript +Multi +0x100000 w375 h150, %js%
Gui, Add, Button, xp y+5 gRunJavascript vRunButton, Run &Javascript in Chrome
Gui, Show, x%xpos% y%ypos%, Chrome Javascript Injector

return

; +----------------------+
; ¦  Exit possibilities  ¦
; +----------------------+

!Escape::
GuiClose:
ExitApp
return


RunJavascript:
If !(WinExist("ahk_class ahk_class Chrome_WidgetWin_1")) {
   msgbox Please run Chrome before injecting Javascript.
   return
} Else {
Gui, Submit, NoHide
Clipboard := ""
RunJsFromChromeAddressBar(Javascript)
ClipWait, 2

; +-----------------------------------------------------------------------------+
; ¦  This is more in keeping with @teadrinker's original code:                   ¦
; ¦  msgbox, , Table Results, % ErrorLevel ? "Failed to get value" : Clipboard  ¦
; +-----------------------------------------------------------------------------+

; +-----------------------------------------------------------------------------+
; ¦  The code below is from another version that uses msgbox to show results.   ¦
; ¦  Uncomment this and comment out the Excel-related code to use that method.  ¦
; +-----------------------------------------------------------------------------+

xl := ComObjCreate("Excel.Application")
xl.Visible := true
xl.Workbooks.Add
sleep 3000
send, ^v
return
}

; +-------------------------------------------+
; ¦  Resize code using @tmplinshi's AutoXYWH  ¦
; +-------------------------------------------+

GuiSize:
	If (A_EventInfo = 1) ; The window has been minimized.
		Return
	AutoXYWH("wh", "Javascript")
	AutoXYWH("y", "RunButton")
return


; +----------------------------------------------------+
; ¦  My choices for showing and hiding the GUI.        ¦
; ¦  Modify to suit, or you can always use the mouse.  ¦
; +----------------------------------------------------+

LAlt & RWin::WinActivate, ahk_id %GuiHwnd%
RAlt & RWin::WinMinimize, ahk_id %GuiHwnd%


; +-------------------------------------------------+
; ¦  This is also from @teadrinker's original code  ¦
; ¦  $+F1:: RunJsFromChromeAddressBar(Javascript)   ¦
; +-------------------------------------------------+


; +------------------------------------------+
; ¦  @teadrinker code from here to the end.  ¦
; ¦  Thanks again!                           ¦
; +------------------------------------------+

RunJsFromChromeAddressBar(js, exe := "chrome.exe") {
   static WM_GETOBJECT := 0x3D
        , ROLE_SYSTEM_TEXT := 0x2A
        , STATE_SYSTEM_FOCUSABLE := 0x100000
        , SELFLAG_TAKEFOCUS := 0x1
   if !AccAddrBar {
      window := "ahk_class Chrome_WidgetWin_1 ahk_exe " . exe
      SendMessage, WM_GETOBJECT, 0, 1, Chrome_RenderWidgetHostHWND1, % window
      AccChrome := AccObjectFromWindow( WinExist(window) )
      AccAddrBar := SearchElement(AccChrome, {Role: ROLE_SYSTEM_TEXT, State: STATE_SYSTEM_FOCUSABLE})
   }
   AccAddrBar.accValue(0) := "javascript:" . js
   AccAddrBar.accSelect(SELFLAG_TAKEFOCUS, 0)
   ControlSend,, {Enter}, % window, Chrome Legacy Window
}

SearchElement(parentElement, params)
{
   found := true
   for k, v in params {
      try {
         if (k = "ChildCount")
            (parentElement.accChildCount != v && found := false)
         else if (k = "State")
            (!(parentElement.accState(0) & v) && found := false)
         else
            (parentElement["acc" . k](0) != v && found := false)
      }
      catch 
         found := false
   } until !found
   if found
      Return parentElement
   
   for k, v in AccChildren(parentElement)
      if obj := SearchElement(v, params)
         Return obj
}

AccObjectFromWindow(hWnd, idObject = 0) {
   static IID_IDispatch   := "{00020400-0000-0000-C000-000000000046}"
        , IID_IAccessible := "{618736E0-3C3D-11CF-810C-00AA00389B71}"
        , OBJID_NATIVEOM  := 0xFFFFFFF0, VT_DISPATCH := 9, F_OWNVALUE := 1
        , h := DllCall("LoadLibrary", "Str", "oleacc", "Ptr")
        
   VarSetCapacity(IID, 16), idObject &= 0xFFFFFFFF
   DllCall("ole32\CLSIDFromString", "Str", idObject = OBJID_NATIVEOM ? IID_IDispatch : IID_IAccessible, "Ptr", &IID)
   if DllCall("oleacc\AccessibleObjectFromWindow", "Ptr", hWnd, "UInt", idObject, "Ptr", &IID, "PtrP", pAcc) = 0
      Return ComObject(VT_DISPATCH, pAcc, F_OWNVALUE)
}

AccChildren(Acc) {
   static VT_DISPATCH := 9
   Loop 1  {
      if ComObjType(Acc, "Name") != "IAccessible"  {
         error := "Invalid IAccessible Object"
         break
      }
      try cChildren := Acc.accChildCount
      catch
         Return ""
      Children := []
      VarSetCapacity(varChildren, cChildren*(8 + A_PtrSize*2), 0)
      res := DllCall("oleacc\AccessibleChildren", "Ptr", ComObjValue(Acc), "Int", 0
                                                , "Int", cChildren, "Ptr", &varChildren, "IntP", cChildren)
      if (res != 0) {
         error := "AccessibleChildren DllCall Failed"
         break
      }
      Loop % cChildren  {
         i := (A_Index - 1)*(A_PtrSize*2 + 8)
         child := NumGet(varChildren, i + 8)
         Children.Push( (b := NumGet(varChildren, i) = VT_DISPATCH) ? AccQuery(child) : child )
         ( b && ObjRelease(child) )
      }
   }
   if error
      ErrorLevel := error
   else
      Return Children.MaxIndex() ? Children : ""
}

AccQuery(Acc) {
   static IAccessible := "{618736e0-3c3d-11cf-810c-00aa00389b71}", VT_DISPATCH := 9, F_OWNVALUE := 1
   try Return ComObject(VT_DISPATCH, ComObjQuery(Acc, IAccessible), F_OWNVALUE)
}

AutoXYWH(DimSize, cList*){       ; http://ahkscript.org/boards/viewtopic.php?t=1079
  static cInfo := {}
 
  If (DimSize = "reset")
    Return cInfo := {}
 
  For i, ctrl in cList {
    ctrlID := A_Gui ":" ctrl
    If ( cInfo[ctrlID].x = "" ){
        GuiControlGet, i, %A_Gui%:Pos, %ctrl%
        MMD := InStr(DimSize, "*") ? "MoveDraw" : "Move"
        fx := fy := fw := fh := 0
        For i, dim in (a := StrSplit(RegExReplace(DimSize, "i)[^xywh]")))
            If !RegExMatch(DimSize, "i)" dim "\s*\K[\d.-]+", f%dim%)
              f%dim% := 1
        cInfo[ctrlID] := { x:ix, fx:fx, y:iy, fy:fy, w:iw, fw:fw, h:ih, fh:fh, gw:A_GuiWidth, gh:A_GuiHeight, a:a , m:MMD}
    }Else If ( cInfo[ctrlID].a.1) {
        dgx := dgw := A_GuiWidth  - cInfo[ctrlID].gw  , dgy := dgh := A_GuiHeight - cInfo[ctrlID].gh
        For i, dim in cInfo[ctrlID]["a"]
            Options .= dim (dg%dim% * cInfo[ctrlID]["f" dim] + cInfo[ctrlID][dim]) A_Space
        GuiControl, % A_Gui ":" cInfo[ctrlID].m , % ctrl, % Options
} } }
Regards,
burque505

Return to “Ask for Help (v1)”

Who is online

Users browsing this forum: aitaixy, Nerafius, RandomBoy and 187 guests