cycle4passion

IE COM DOM Set Manipulations - Made Easy

Apr 23rd, 2017
162
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. COMDOM(pwb, pGetby, pElemtext, pAction = "", pShowerrors = true, exitonfail := true) ;6/6/17 ----------------------------------------
  2. /* Function allow easy set manipulation of IE COM DOM elements with error checking with suppressible error dialogs.
  3. it is not all inclusive for DOM manipulation and concentrates mostly on Set functions for form elements
  4. In particular, it keeps me from re-learning more complex manipulations of things like selects/options
  5. Auto blurs (removes focus) after setting values allowing native form errorchecking, etc.
  6. Auto enables disabled controls, bypassing native JS blocking
  7. returns element object if error free which can be further manipulated (style, etc), or false if error
  8.  
  9. EXAMPLES:
  10.  
  11. COMDOM(wb, "id", "login", "srhamy")
  12. COMDOM(wb, "name[1]", "login", "srhamy")
  13. COMDOM(wb, "text[a], "Download", "click") ; assumes 1st match
  14. COMDOM(wb, "id", "Optionals", "check[2,3]")
  15.  
  16. ARGUMENTS
  17.     pWb             : IE web browser COM object
  18.     pGetby      : method to conduct search for <elemtext>
  19.                             - id                        : default, same a getElementByID()
  20.                             - name              : same as getElementsByName(), default to [0] or can specify array element like name[1]
  21.                             - class                 : same as getElementsByClass(), defaults to [0] or can specify array element like class[2]
  22.                             - tagname           : same as getElementsByTagName(), defaults to [0] or specify array element like tagname[3]
  23.                             - query             : same as querySelectorAll(), defaults to [0] or can specify array element like query[4]
  24.                             - form                  : same as form[x], defaults to [0] or can specify array element form[5]
  25.                             - text[tagname]     : find HTML element by value/placeholder or HTML Text node by innerText, tagname
  26.                                                           defaults to * or better/faster to filter by element tag type examples: a,div,input, button
  27.     pElemtext   : identifier used for finding desired element
  28.     pAction         : action to perform on found element (exist,click,focus,select,submit,check/uncheck,placeholder) ; set is default
  29.                             - customtext                : set element value to <customtext>
  30.                             - click                         : click element
  31.                             - focus                         : set focus to element
  32.                             - check/select                  : checks/selects option(s) for checkboxes, dropdowns, selects, and mult-selects
  33.                             - uncheck/unselect              : unchecks/unselect option(s) in checkboxes, dropdowns, selects, and mult-selects
  34.                             - submit                        : submits form
  35.                             - exist                         : determine if control exists, aborts remainder of commands if not
  36.                             - placeholder                   : set placeholder text of element
  37.                             - enable                        : enable control (note this is done automatically before issing other commands)
  38.                             - disable                       : disable control
  39.                             - hide                          : hide element
  40.                             - show/unhide                   : show element
  41.     showerrors:
  42.                             - TRUE                          : popup errors
  43.                             - FALSE                         : silent errors
  44.                            
  45.     Examples
  46.  
  47.     Instead of wb.document.getElementByID("login") := "me"
  48.     IECOMDOM(wb, "id", "login", "me") ; finds element by id "login" and with fills with "me"
  49.     Instead of wb.document.getElementsByClassName("password")[2].Focus()
  50.     IECOMDOM(wb, "class", "password[2]", "focus) ; finds elements by classname of "password" and focuses on 1st one (zero based index)
  51.     Instead of a long set of commands...
  52.     IECOMDOM(wb, "id", "location", "check[index1,index2]") ; finds input with id "location" and checks 2nd and 3rd option (zero based index)
  53.     IECOMDOM(wb, "text['a']", "Download", "click") ; click link with HTML showing "Download"
  54.     COMDOM(wb, "tag","*[17]","hide") - hides 17th element on page
  55. */
  56. {
  57.   try
  58.   {
  59.     if (Not IsObject(pWb))
  60.         throw Exception("pWb Object not defined.", -1)
  61.     if (Not InStr(pWb.FullName, "iexplore.exe"))
  62.         throw Exception("pWb Object in not IE Object.", -1)
  63.     if (Not pGetby)
  64.         throw Exception("pGetby argument cannot be blank.", -1)
  65.     if (Not pElemtext)
  66.         throw Exception("pElemText argument cannot be blank.", -1)
  67.     if (Not pAction)
  68.         throw Exception("Action argument cannot be blank.", -1)
  69.  
  70.     arrelemtext := StrSplit(pElemtext,"|",A_Space) , arrgetby :=StrSplit(pGetby,"|",A_Space), arraction :=StrSplit(pAction,"|",A_Space)
  71.  
  72.     if (arrelemtext.Length != arrgetby.Length and arrgetby.Length != 1)
  73.       throw Exception("Unmatched array lengths for pGetby ( " . arrgetby.Length . ") and pElemtext (" . arrelemtext.Length . ") arguments `r`n`r`n pGetBy= """ . pGetBy . """`r`n`r`npElemtext=""" . pElemtext . """", -1)
  74.     if (arrelemtext.Length != arraction.Length)
  75.       throw Exception( "Unmatched array lengths for pElemtext  (" . arrElemtext.Length . ") and pAction (" . arrAction.Length . ") arguments`r`n`r`npElemtext= """ . pElemtext . """`r`n`r`npAction=""" . pAction . """ arguments", -1)
  76.    
  77.     Loop,  % arraction.MaxIndex()
  78.     { ; SPLITS ====================================================================================
  79.     ; Split GetBy[]
  80.       StringLower, getby, % (arrgetby.MaxIndex() = 1) ? trim(arrgetby[1]) : trim(arrgetby[A_Index]) ; if 1 getby apply to all, and lowerase normalize/trim leading/trailing ws
  81.  
  82.       if selpos := RegExMatch(getby, "\[([a-zA-Z0-9 '" . """" . "]*)\]",elemsearchtype)
  83.       {
  84.         StringReplace,elemsearchtype, elemsearchtype1, "", , All ; remove double quotes
  85.         StringReplace, elemsearchtype, elemsearchtype, ', , All ; remove single quotes
  86.         getby  := SubStr(getby,1,selpos-1)                                        ; simplify getby w/o [??]
  87.       }
  88.       ; Split ElemText[]
  89.       elemtext := trim(arrelemtext[A_Index])
  90.       if selpos := RegExMatch(elemtext, "\[([0-9 '" . """" . "]*)\]",elemindex) ; optional enclosing ' or " s
  91.       {
  92.         StringReplace,elemindex, elemindex1, "", , All ; remove double quotes
  93.         StringReplace, elemindex, elemindex, ', , All   ; remove single quotes
  94.         elemtext  := SubStr(elemtext,1,selpos-1)           ; simplify elemtext w/o [??]
  95.       }
  96.       else
  97.         elemindex = 0
  98.  
  99.     ; Split Action[]
  100.       action := trim(arraction[A_Index])
  101.       if selpos := RegExMatch(action, "\[([a-zA-Z0-9, '" . """" . "]*)\]",sels)
  102.       {
  103.         arrsels := StrSplit(sels1,",", "'" . """") ; strips enclosing single and double quotes
  104.         action  := SubStr(action,1,selpos-1) ; simply action w/o [??]
  105.       }
  106.  
  107.     if RegExMatch(action,"i)(click|focus|select|submit|check|uncheck|enable|disable|hide|unhide|show|exist|placeholder|value)")  ; normalize to lower case & avoiding others (ie sent text)
  108.       StringLower, action, action
  109.       if (action = "exist")
  110.         ComObjError(false)
  111.      else
  112.       ComObjError(pShowerrors)
  113.      ; TARGET ========================================================
  114.      if (getby = "name") ; same as getElementsByName, COMDOM(wb, "tag[0]","username","focus")
  115.         target := pWb.document.getElementsByName(elemtext)[elemindex]
  116.       else if (InStr(getby, "class")) ; same as getElementsByClassName, COMDOM(wb, "class","edit-new","focus")
  117.         target := pWb.document.getElementsByClassName(elemtext)[elemindex]
  118.       else if (InStr(getby, "tag") or getby = "index") ; same as GetElementsByTagName
  119.         target := pWb.document.GetElementsByTagName(elemtext)[elemindex]
  120.       else if (InStr(getby,"query")) ; same as get elements by querySelectorAll
  121.         target := pWb.document.querySelectorAll(elemtext)[elemindex]
  122.       else if (InStr(getby,"form"))
  123.         target := pWb.document.forms[elemindex]
  124.       else if (getby = "text") ; get element by HTML text, COMDOM(wb,"text['a'],"Download","click")
  125.       {
  126.         if elemsearchtype =
  127.           elemsearchtype := "*"
  128.         nodes := pWb.document.GetElementsByTagName(elemsearchtype)
  129.         debugbytext := true
  130.         if debugbytext
  131.           out("Matches (type=" . elemsearchtype . ") = " . nodes.Length)
  132.         Loop % nodes.Length
  133.         {
  134.           StringLower, nodetype, % nodes[A_Index-1].tagname
  135.           if (nodetype = "input") {
  136.             if (nodes[A_Index-1].value = trim(elemtext)) or (nodes[A_Index-1].placeholder = trim(elemtext) ) {
  137.             if debugbytext
  138.               out("(" . A_Index  - 1 . ") " . Quote(nodes[A_Index-1].Value) . " (type=" . nodetype . ") ?= " . Quote(elemtext))
  139.             target := nodes[A_Index-1]
  140.             break
  141.             }
  142.           } else { ; examples buttons span p div
  143.             if debugbytext
  144.               out("(" . A_Index  - 1 . ") " . Quote(nodes[A_Index-1].InnerText) . " (type=" . nodetype . ") ?= " . Quote(elemtext))
  145.             if (nodes[A_Index-1].InnerText = trim(elemtext)) {
  146.             target := nodes[A_Index-1]
  147.             break
  148.             }
  149.           }
  150.         }
  151.       }
  152.       else ; assume getby ID
  153.         target := pWb.document.getElementByID(elemtext)
  154.      
  155.       if not target and action != "exist"
  156.         throw Exception("Sent Item #" . A_Index . " - Target elem not found`r`n`r`nelemtext= """ . elemtext . """`r`nusing getby=""" . getby . """", -1)
  157.     ;if target.tagname???? = "option" ; automatically backstep from option to select (user sent wrong one)
  158.         ;target := target.parentNode
  159.     if target.disabled := true
  160.         target.disabled := false  ; Force through disabled controls
  161.       ; ACTION =======================================================
  162.       if (action = "exist")
  163.         if target
  164.           continue
  165.         else
  166.           return "" ; ? false
  167.     else if (action = "value")
  168.         return target.value
  169.     else if (action="click")
  170.       {
  171.         target.Click()
  172.         IEWaitReady(pWb)
  173.       }
  174.         else if (action = "focus")
  175.           target.Focus()
  176.         else if (action = "enable" or action = "disable")
  177.             target.enable := (action="enable") ? true : false
  178.         else if (action = "hide" or action = "unhide" or action = "show")
  179.             target.style.visibility := (action="hide") ? "hidden" : "visible"
  180.         else if (action = "placeholder" and arrsels[1])
  181.           target.placeholder := arrsels[1]
  182.         else if (action = "select" and (target.type = "input" or or target.type = "email" or target.type = "password" or target.type = "textarea"))
  183.           target.Select()
  184.         else if (action = "submit")
  185.         {
  186.           target.Submit()
  187.           IEWaitReady(pWb)
  188.         }
  189.         else if (action = "check" or action = "uncheck" or elemtext ="select" or elemtext ="unselect")
  190.         { ; for select, multi-select, dropdowns and checkboxes
  191.           if (target.type = "checkbox")
  192.             target.checked := (action="check") ? true : false
  193.           else if (InStr(target.type,select) or target.type = "dropdown")
  194.           { ; handles single or multiple select + dropdowns
  195.             Loop % arrsels.MaxIndex()
  196.             {
  197.               seloptvalue := arrsels[A_Index]
  198.               Loop %  target.Length
  199.               {
  200.                 if (seloptvalue = "all" or target.options[A_Index-1].text = Trim(seloptvalue) or target.options[A_Index-1].value = Trim(seloptvalue) or A_Index - 1 = trim(seloptvalue))
  201.                 target[A_Index-1].selected := (action="check" or action = "select") ? true : false
  202.               }
  203.             }
  204.           }
  205.         }
  206.         else
  207.           target.Value := action
  208.         if (action != "focus" and action != "exist") { ; force lose focus to trigger JS error checking/enabling etc.
  209.             ComObjError(false)
  210.             target.Blur()
  211.             ComObjError(pShowerrors)
  212.         }
  213.       } ; Close Loop
  214.   } catch e ; ERRORS ==============================================================================
  215.     {
  216.         target := ""
  217.         errmsg := (e.What = ":= ") ? "Error in " . e.what . " Function - Line " . e.line  : "Error - Line " . e.line . ", " . e.message . "`n", e.message . "`n" . e.extra
  218.         LogErrors(true,false,pShowerrors,"COMDOM",errmsg)
  219.         if (exitonfail)
  220.             Exit
  221.     }
  222. return target
  223. } ; End COMDOM ==================================================================================
Advertisement