AutoHotkey Homepage AutoHotkey Community
Let's help each other out
 
 FAQFAQ   SearchSearch   MemberlistMemberlist   RegisterRegister 
 ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

Automation IE7 Navigation and Scripting with Tabs
Goto page 1, 2, 3, 4, 5, 6  Next
 
Post new topic   Reply to topic    AutoHotkey Community Forum Index -> Scripts & Functions
View previous topic :: View next topic  

Do you find this group pf wrapper functions for IE Automation Usefull
no you suck
0%
 0%  [ 0 ]
need better Documentation
33%
 33%  [ 5 ]
What is DHTML i dont understand how this helps
13%
 13%  [ 2 ]
I use Firefox this is a stupid idea
33%
 33%  [ 5 ]
I know DHTML this is a reasonably good AHK adaption
6%
 6%  [ 1 ]
This is the best DHTML too in the AHK Forum
13%
 13%  [ 2 ]
Total Votes : 15

Author Message
tank



Joined: 21 Dec 2007
Posts: 678

PostPosted: Wed Apr 09, 2008 4:14 pm    Post subject: Automation IE7 Navigation and Scripting with Tabs Reply with quote

Important **** if you have not copied these scripts since 6-29 and are having trouble please re copy now
Documentation/tutorial
**********************************************************
tank wrote:
I have posted as a separate thread some documentation and COM\IE tutorials

Included are some basic instructions for accessing DOM

These are not wrapped this is a tutorial so that folks with questions can find there own answers
http://www.autohotkey.com/forum/viewtopic.php?t=34972

**********************************************************
Finally learned something worth posting .... maybe
Firstly Credits.
ahklerner: without his inject JS function i would have never really had a goal
Lexikos for using small simple words and lots and lots of patience to really educate me in the most basic fashion in the most simple concepts of the webbrowser object
Sean for his fantastic com work without which well so much would just not be possible with AHK.
Actually to these three I owe my current career as this is the primary use in my job in automating several web based interfaces
firstly for those wishing to learn or improve my code
http://msdn2.microsoft.com/en-us/library/aa752127.aspx
is what this is driven from

and seans most excelent starting place for IE
EDIT Found this after i posted the script
it bears noting the Sean also has a different solution to the navigation thing
http://www.autohotkey.com/forum/viewtopic.php?t=24930&highlight=ie7
http://www.autohotkey.com/forum/topic19255.html
Com library required
OK now to the meat

IE7_Nav Edit thanks for the shortened version ahklerner
EDIT: added the missing alt new window and tab thanks sean
EDIT 5-30-2008 corrected a couple minor typos and released the doc and rdy objects
EDIT 6-29-2008 thanks Lexikos corrected a few farely serious flaws
Code:
IE7_InjectJS("auto","alert('js worked')")

   ;~ title is any prtion if the title of the tab. since im using instring fuction no need to set titlematch mode
   ;~ url is anny fully qualified domain and path the http:// isnt really required tho
   ;~ this function will wait for the page to fully load before releasing to next call to execute

   IE7_Nav(title="A",url="http://autohotkey.com") {
   COM_Init()
   Loop, %   COM_Invoke(psw := COM_Invoke(psh:=COM_CreateObject("Shell.Application"), "Windows"), "Count")
   {
      If ( InStr(tabname:=COM_Invoke(pwb := COM_Invoke(psw, "Item", A_Index-1), "LocationName"),title,0) )
      {
         result:=COM_Invoke(pwb, "Navigate",url) ;execute the navigation return result ; like S_OK
         ;COM_Invoke(pwb, "Navigate", sURL, 0x1)   ; navOpenInNewWindow
         /*   IE7 Only!
         COM_Invoke(pwb, "Navigate", sURL, 0x800)   ; navOpenInNewTab
         COM_Invoke(pwb, "Navigate", sURL, 0x1000)   ; navOpenInBackgroundTab
         */

         parentWindow:=COM_Invoke(Document:=COM_Invoke(pwb, "Document"), "parentWindow")
         loop
         {
            COM_Invoke(parentWindow, "execScript","var rdy=document.readyState")
            If (rdy:=COM_Invoke(parentWindow, "rdy") = "complete") ;Better to use the document readystate more consistent page load results
            {   
               COM_Release(rdy)
               break
            }
            Sleep, 500   
         }
         COM_Release(parentWindow), COM_Release(Document), COM_Release(pwb)
         Break ; added this because its only supposed to execute once
      }
    COM_Release(pwb)
   }
   COM_Release(psh),COM_Release(psw), COM_Term()
}

Use like this
Code:

IE7_Nav("auto","http://google.com") ; auto for title of an autohotkey page sorry that was confusing to me too a month later


now for those of us freaks who like to manipilate the dom
let me first start with a couple links
executeScript is just one of many things that can be done from the document or window object basically if the msdn has it for these objects you can use com to do it also thanks again Sean
in other examples in this forum this was accessed thru the
IID_IHTMLWindow2 interface as in this example

IE_InjectJS by ahklerner
IE_InjectJSbyTT by SinClair to use with tabs

both work tho
SinClair's requires the tab to be selected tho so it just ddidnt satisfy my need for moving to IE7 as i need to force the window to be minimized to keep users from interacting with complicated routines

Lexikos pointed out that both have alot of overhead lots of looping

Mine will have some looping too and it is still a flaw till i get a way to get it nailed down better

However, Mine does not use acc library nor does it use the conventional IHTMLWindow2 interfaces. in addition its quite a bit shorter thAn either
As well they my function works on minimised non selected tabs. and should work on both ie6 as well as ie7 i tested this script on IE7 on Vista ultimate FYI edit now also tested on xp wiht ie6

For those of us that write long automation tasks that require the user to be free to do other things while they run in the back ground this solution will be IDEAL
without further ado
Edit thanks for the shortened version ahklerner
EDIT 5-30-2008 released all variables and some minor code clean up
EDIT 6-29-2008 thanks for the help Sean and lexikos with obvious flaws
Code:

IE7_InjectJS(Access_Tab_Title, JS_to_Inject, VarNames_to_Return="") {
   COM_Init()
   Loop, %   COM_Invoke(psw := COM_Invoke(psh:=COM_CreateObject("Shell.Application"), "Windows"), "Count")
      {
      If (InStr(tabname:=COM_Invoke(pwb := COM_Invoke(psw, "Item", A_Index-1), "LocationName"),Access_Tab_Title,0)) && (JS_to_Inject || VarNames_to_Return) {
         window:= COM_Invoke(Document:=COM_Invoke(pwb, "Document"), "parentWindow")
         If JS_to_Inject
         COM_Invoke(window, "execScript",JS_to_Inject)
         If VarNames_to_Return {
            StringSplit, Vars_, VarNames_to_Return, `,
            Loop, %Vars_0%
               Ret .= COM_Invoke(window,Vars_%A_Index%) . ","
            StringTrimRight, Ret, Ret, 1
            }
         COM_Release(Document),COM_Release(window), COM_Release(pwb)
         break
         }         
      COM_Release(pwb)
      }
   COM_Release(psh),COM_Release(psw), COM_Term()
   Return Ret
}

execution is this way
Code:

jscript=
(
var x=document.body.innerHTML;
)
msgbox % IE7_InjectJS("autohotkey", jscript,"x")

or
Code:

msgbox % IE7_InjectJS("autohotkey", "var x=document.body.innerHTML;","x")


Thanks all who are interested and I love feedback
Lexikos or Sean Do either of you know a way to get the Tab desired without the Looping sequence?

edit: with ahklerner shortened version below thanks man
eddit removed the release acc command as its not needed any more
_________________
Read this
Com
Automate IE7 with Tabs


Last edited by tank on Sun Aug 24, 2008 7:25 am; edited 18 times in total
Back to top
View user's profile Send private message
ahklerner



Joined: 26 Jun 2006
Posts: 1205
Location: USA

PostPosted: Wed Apr 09, 2008 5:18 pm    Post subject: Reply with quote

Here is a slightly shorter version. Hope you dont mind.
Code:

IE7_Nav(title="A",url="http://autohotkey.com") {
   COM_Init()
   Loop, %   COM_Invoke(psw := COM_Invoke(psh := COM_CreateObject("Shell.Application"), "Windows"), "Count")
      {
      If ( InStr(tabname:=COM_Invoke(pwb := COM_Invoke(psw, "Item", A_Index-1), "LocationName"),title,0) ) {
         COM_Invoke(pwb, "Navigate",url) ;xecute the navigation
         doc:= COM_Invoke(pwb, "Document")
         loop {
            If (rdy:=COM_Invoke(doc,"readyState") = "complete") ;Better to use the document readystate more consistent page load results
               break
            Sleep, 500
            }
         COM_Release(doc)
         }
      COM_Release(tabname), COM_Release(pwb)
      }
   COM_Release(psw), COM_Release(psh), COM_Term()
   }

Code:

IE7_InjectJS(Access_Tab_Title, JS_to_Inject, VarNames_to_Return="") {
   COM_Init()
   Loop, %   COM_Invoke(psw := COM_Invoke(psh := COM_CreateObject("Shell.Application"), "Windows"), "Count")
      {
      If (InStr(title:=COM_Invoke(pwb := COM_Invoke(psw, "Item", A_Index-1), "LocationName"), title, 0)) && (JS_to_Inject || VarNames_to_Return) {
         window:= COM_Invoke(doc:= COM_Invoke(pwb, "Document"), "parentWindow")
         If JS_to_Inject
         COM_Invoke(window, "execScript",JS_to_Inject)
         If VarNames_to_Return {
            StringSplit, Vars_, VarNames_to_Return, `,
            Loop, %Vars_0%
               Ret .= COM_Invoke(window,Vars_%A_Index%) . ","
            StringTrimRight, Ret, Ret, 1
            }
         COM_Release(window), COM_Release(doc) ; , ACC_Term()
         break
         }         
      COM_Release(title), COM_Release(pwb)
      }
   COM_Release(psw), COM_Release(psh), COM_Term()
   Return Ret
   }

_________________
Back to top
View user's profile Send private message
tank



Joined: 21 Dec 2007
Posts: 678

PostPosted: Wed Apr 09, 2008 5:54 pm    Post subject: Reply with quote

Dude i will never mind your input
and shorter is always better
I really hope you dont mind me using you in my examples so much but your function was the foundation for my end goal
Very Happy
_________________
Read this
Com
Automate IE7 with Tabs
Back to top
View user's profile Send private message
tank



Joined: 21 Dec 2007
Posts: 678

PostPosted: Thu Apr 10, 2008 1:26 am    Post subject: cross fram scripting forms Reply with quote

I have been asked several times professionally and privately in this community for scripting acrross frames

http://msdn.microsoft.com/en-us/library/ms533028(VS.85).aspx
About Cross-Frame Scripting and Security


outlines the difficulty with this

Now given this very important restriction

MSDN wrote:
only pages with identical domain properties are allowed free interaction. The protocol of the URL must also match. For instance, an HTTP page cannot access HTTPS content.


that said thie following function has been added to the IE7 functions

Code:

IE7_SetFrame_Form_DOM(parentWindow,FRM,FOM,ID1,val=0)
{
   if FRM is integer
      ahkframe:="document.frames(" . FRM . ")"
   Else
      ahkframe:="document.frames('" . FRM . "')"
   if FOM is integer
      ahkform:=ahkframe . ".document.forms(" . FOM . ")"
   Else
      ahkform:=ahkframe . ".document.forms('" . FOM . "')"
   if ID1 is integer
      ahkele:=ahkform . ".elements(" . ID1 . ")"
   Else
      ahkele:=ahkform . ".elements('" . ID1 . "')"
    
   tagName:=IE7_ExecuteJS(parentWindow, "var tagName=" . ahkele . ".tagName;" , "tagName")
   teststring:="inputselecttextarea"
   IfInString,teststring,%tagName%
      domString := ahkele . ".value"
   Else
      domString := ahkele . ".innerHTML"
   if val
      Return IE7_ExecuteJS(parentWindow, "var oDom=" . domString . "='" . val . "';","oDom")
   Else
      Return IE7_ExecuteJS(parentWindow, "var oDom=" . domString . ";","oDom")
   Return
}

and this one below ignores frame and uses the all collection
Code:

IE7_SetFrame_DOM(parentWindow,FRM,ID1,val=0)
{
   if FRM is integer
      ahkframe:="document.frames(" . FRM . ")"
   Else
      ahkframe:="document.frames('" . FRM . "')"
   if ID1 is integer
      ahkele:=ahkframe . ".document.all(" . ID1 . ")"
   Else
      ahkele:=ahkframe . ".document.all('" . ID1 . "')"
    
   tagName:=IE7_ExecuteJS(parentWindow, "var tagName=" . ahkele . ".tagName;" , "tagName")
   teststring:="inputselecttextarea"
   IfInString,teststring,%tagName%
      domString := ahkele . ".value"
   Else
      domString := ahkele . ".innerHTML"
   if val
      Return IE7_ExecuteJS(parentWindow, "var oDom=" . domString . "='" . val . "';","oDom")
   Else
      Return IE7_ExecuteJS(parentWindow, "var oDom=" . domString . ";","oDom")
   Return
}

_________________
Read this
Com
Automate IE7 with Tabs


Last edited by tank on Fri Jul 11, 2008 6:07 am; edited 9 times in total
Back to top
View user's profile Send private message
tank



Joined: 21 Dec 2007
Posts: 678

PostPosted: Mon May 19, 2008 4:23 pm    Post subject: IE Automation Reply with quote

Important **** if you have not copied these scripts since 6-29 and are having trouble please re copy now

the following builds on the above concepts and duplicates some actions found elsewhere(in spirit but not method) im posting here
if not obvious still relys on IE 6 or 7 as well as a microsoft OS
tested on vista and xp
hope someone finds this usefull
Code:
  ;~ ******************************************************************************************
;~ ******************************************************************************************
;~ IE 7 functions
;~ ******************************************************************************************
;~ ******************************************************************************************
;~ function list
;~ IE7_Get(title,url="http") gets iwebrowser interface pointer and returns automation dhtml window obj ie parentWindow used itn the below functions
;~ IE7_Navigate(parentWindow,url)  Navigate and wait for page Load to complete in same frame
;~ IE7_ExecuteJS(parentWindow, JS_to_Inject, VarNames_to_Return="") Full insertion of javascript or execution or retrieval of new or existing fucntions or variables
;~ IE7_readyState(parentWindow) wait for page Load to complete
;~ IE7_Quit(parentWindow) Closes Window
;~ IE7_New(url) Loads a new window even if one does not currently exist and wait for page Load to complete in same frame
;~ IE7_Click_Text(parentWindow,innerHTML)Clicks a link byt text in the inner html of the a tag and wait for page Load to complete in same frame
;~ IE7_Click_Element(parentWindow,ID1=0) ; clicks first element it finds to match returns error if not found will also trigger readystate
;~ IE7_Button_click(parentWindow,value)Click a button based on the text of the button and wait for page Load to complete in same frame
;~ IE7_Get_DOM(parentWindow,ID1)retreive a dom object by index of all collection id or name attribute
;~ IE7_Set_DOM(parentWindow,ID1,val="innerHTML") set  a dom object by index of all collection id or name attribute
;~ IE7_SetFrame_Form_DOM(parentWindow,FRM,FOM,ID1,val=0)
;~ IE7_SetFrame_DOM(parentWindow,FRM,ID1,val=0)
;~ ******************************************************************************************
;~ ******************************************************************************************
IE7_Get(title="",url="http")
{
   if not title ;test for a blank page_title
   {
      IfWinExist,ahk_class IEFrame ; ensure that an ie window exists
         WinGetTitle,title,ahk_class IEFrame ;try grab an active ie window and use whatever tab is selected
      Else
         Return IE7_New("http://www.autohotkey.com/forum/viewtopic.php?t=30599") ; no window found just create a new window     
   }
;~    title is required and is not case sensitive
;~    url is optional and since . exists in all url schemas it will allow un entered url to default to first found
;~  loop thru open windows for a match
   Loop, %   COM_Invoke(psw := COM_Invoke(psh:=COM_CreateObject("Shell.Application"), "Windows"), "Count")
   {
      If ( InStr(LocationName:=COM_Invoke(pwb:=COM_Invoke(psw, "Item", A_Index-1), "LocationName"),title,0)) && (InStr(taburl:=COM_Invoke(pwb, "LocationURL"),url,0) )
      {
       parentWindow:=COM_Invoke(Document:=COM_Invoke(pwb, "Document"), "parentWindow")
            COM_Release(pwb),COM_Release(Document)
Break
      }
         COM_Release(pwb),COM_Release(Document)
   }
   COM_Release(psw),COM_Release(psh) ; release the objects each loop itineration
   if parentWindow is integer
   {
      return parentWindow
   }
   else
   {
      Return A_LastError   
   }
}
;~ Navigate the given window
IE7_Navigate(parentWindow,url) ; begins navigation process and holds execution till page has loaded fully
{
;~    parent windw is a Dom window object
   if parentWindow is integer
   {   
      result:=COM_Invoke(parentWindow, "Navigate",url) ;execute the navigation returns SOK
      IE7_readyState(parentWindow) ;Holds till document onload event is ready
      Return result
   }
}


IE7_ExecuteJS(parentWindow, JS_to_Inject, VarNames_to_Return="") ;execute some js on a tab returns comma delimited list of vars if specified
{
   if parentWindow is integer
   {

      If JS_to_Inject
         COM_Invoke(parentWindow, "execScript",JS_to_Inject)
      If VarNames_to_Return
      {
         StringSplit, Vars_, VarNames_to_Return, `,
         Loop, %Vars_0%
            Ret .= COM_Invoke(parentWindow,Vars_%A_Index%) . ","
         StringTrimRight, Ret, Ret, 1
         Return Ret
      }
         Else
         Return 0
   }
   Else
      Return error
}
IE7_readyState(parentWindow) ;pauses till there is no loading activity returns DOM window handle
{
   
   
   if parentWindow is integer
   {
      loop 120{ ;limit to 60 seconds
         Sleep, 500
         rdy:=IE7_ExecuteJS(parentWindow, "var rdy=document.readyState","rdy") ; best method
         If (rdy = "complete") ;Better to use the document readystate more consistent page load results
            break
         }
      Return 0
   }
   else
      Return A_LastError   
   
}
IE7_Quit(parentWindow) ;Close a DOM window handle
{
   COM_Invoke(parentWindow, "execScript","window.opener='top';window.close();")
}

IE7_New(url) ;only if at least one IE window already exists return parentWindow js accessable object returns DOM window handle
{
   oIE := COM_CreateObject("InternetExplorer.Application")
   COM_Invoke(oIE, "Visible=", "True") ;"False" ;"True" ;
   COM_Invoke(oIE, "Navigate", url)
   loop 10{ ;limit to 60 seconds
      Sleep, 500
      rdy:=COM_Invoke(oIE,"readyState")
      If (rdy = 4)
         break
      COM_Release(rdy)
   }
   oDoc := COM_Invoke(oIE,"Document")
   parentWindow :=COM_Invoke(oDoc, "parentWindow")
   COM_Release(oDoc)
   COM_Release(oIE)
   IE7_readyState(parentWindow)
   return parentWindow
}


IE7_Click_Text(parentWindow,innerHTML) ; searches a tags and clicks first text it finds to match returns error if not found will also trigger readystate
{
   js=
   (
      var links=document.links;
      var count=links.length;
   )
   
   count1 := IE7_ExecuteJS(parentWindow, js, "count")
   loop, % count1
   {
   
      js=
      (
         var text=document.links(%A_Index%-1).innerHTML;
      )
      text1 := IE7_ExecuteJS(parentWindow, js, "text")
      IfNotInString,text1,%innerHTML%
      Continue ;skip the rest and go to next loop
      js=
      (
         document.links(%A_Index%-1).click();
      )
      IE7_ExecuteJS(parentWindow, js)     
      Break
   }
IE7_readyState(parentWindow) ; wait for page change to finish
Return
}

IE7_Click_Element(parentWindow,ID1=0) ; clicks first element it finds to match returns error if not found will also trigger readystate
{
   clickme=
   (
     
   if (isNaN("%ID1%")){ // determins if an index or id is entered
         document.all("%ID1%").click();
      }else{ // must be an index
         document.all(%ID1%).click();
      }
     
   )
   
   COM_Invoke(parentWindow, "execScript",clickme)
IE7_readyState(parentWindow) ; wait for page change to finish
Return
}

IE7_Button_click(parentWindow,value) ;Searches input tags for type button then compares the value with the sought text if found clicks returns error if not found will also trigger readystate
{
   button_click=
   (
   var i=0;
   while (i<document.all.length)
   {
      var tag=document.all(i).tagName;
      if (tag.toLowerCase()=='input')
      {
         var typ=document.all(i).type;
         if (typ.toLowerCase()=='button' || typ.toLowerCase()=='submit' || typ.toLowerCase()=='reset')
         {
            var myVal=document.all(i).value;
            var theVal='%value%';
            if (myVal.toLowerCase()==theVal.toLowerCase())
            {
               document.all(i).click(); //click the button
               tag=undefined;
               typ=undefined;
               break; // end the loop
            }
         }
      }
      i=i+1;
   }

)
IE7_ExecuteJS(parentWindow, button_click)
IE7_readyState(parentWindow) ; wait for page change to finish
Return
}

;~ IE7_Get_DOM(parentWindow,ID,val="innerHTML",method="ID" )
;~ parentWindow assigned by IE7_Get(title,url="http") and must be an integer that represents a dom window handle
;~ ID will be an element id, index of all
IE7_Get_DOM(parentWindow,ID1) ;gets DOM object by ID Tag and returns string or error
{
   get_=
   (
   if (isNaN("%ID1%")){ // determins if an index or id is entered
         var tag=document.all("%ID1%").tagName;
         var i=1;
      }else{ // must be an index
         var tag=document.all(%ID1%).tagName;
         var i=2;
      }
   var tag1=tag.toLowerCase();
   
   

   switch(tag1)
      {
      case "input":
        var t=1;
        break;   
      case "textarea":
        var t=1;
        break;   
      case "select":
        var t=1;
        break;
      default:
        var t=2;
      }
   if(i==1 && t==1)
      var myVal=document.all("%ID1%").value;
   else if(i==2 && t==1)
      var myVal=document.all(%ID1%).value;
   else if(i==1 && t==2)
      var myVal=document.all("%ID1%").innerHTML;
   else if(i==2 && t==2)
      var myVal=document.all(%ID1%).innerHTML;
     
        var t=0;
        var i=0;
        var tag1=0;
        var tag=0;
   )
   myVal:=IE7_ExecuteJS(parentWindow, get_,"myVal")
   IE7_ExecuteJS(parentWindow, "var myVal='undefined';")
   Return myVal
}

IE7_Set_DOM(parentWindow,ID1,val="innerHTML") ;gets DOM object by ID Tag and returns string or error
{
   set_=
   (
   if (isNaN("%ID1%")){ // determins if an index or id is entered
         var tag=document.all("%ID1%").tagName;
         var i=1;
      }else{ // must be an index
         var tag=document.all(%ID1%).tagName;
         var i=2;
      }
   var tag1=tag.toLowerCase();
   
   

   switch(tag1)
      {
      case "input":
        var t=1;
        break;   
      case "textarea":
        var t=1;
        break;   
      case "select":
        var t=1;
        break;
      default:
        var t=2;
      }

   if(i==1 && t==1)
   {
      document.all("%ID1%").value='%val%';
      document.all("%ID1%").fireEvent('onchange')
      document.all("%ID1%").fireEvent('onblur')
   }
   else if(i==2 && t==1)
   {
      document.all(%ID1%).value='%val%';
      document.all(%ID1%).fireEvent('onchange')
      document.all(%ID1%).fireEvent('onblur')
   }
   else if(i==1 && t==2)
      document.all("%ID1%").innerHTML='%val%';
   else if(i==2 && t==2)
      document.all(%ID1%).innerHTML='%val%';
        var t=0;
        var i=0;
        var tag1=0;
        var tag=0;
   )
   IE7_ExecuteJS(parentWindow, set_)
   Return
}
IE7_SetFrame_Form_DOM(parentWindow,FRM,FOM,ID1,val=0) ;gets DOM object by ID Tag and returns string or error
{
   if FRM is integer
      ahkframe:="document.frames(" . FRM . ")"
   Else
      ahkframe:="document.frames('" . FRM . "')"
   if FOM is integer
      ahkform:=ahkframe . ".document.forms(" . FOM . ")"
   Else
      ahkform:=ahkframe . ".document.forms('" . FOM . "')"
   if ID1 is integer
      ahkele:=ahkform . ".elements(" . ID1 . ")"
   Else
      ahkele:=ahkform . ".elements('" . ID1 . "')"
   
   tagName:=IE7_ExecuteJS(parentWindow, "var tagName=" . ahkele . ".tagName;" , "tagName")
   teststring:="inputselecttextarea"
   IfInString,teststring,%tagName%
      domString := ahkele . ".value"
   Else
      domString := ahkele . ".innerHTML"
   if val
      Return IE7_ExecuteJS(parentWindow, "var oDom=" . domString . "='" . val . "';","oDom")
   Else
      Return IE7_ExecuteJS(parentWindow, "var oDom=" . domString . ";","oDom")
   Return
}


IE7_SetFrame_DOM(parentWindow,FRM,ID1,val=0) ;gets DOM object by ID Tag and returns string or error
{
   if FRM is integer
      ahkframe:="document.frames(" . FRM . ")"
   Else
      ahkframe:="document.frames('" . FRM . "')"
   if ID1 is integer
      ahkele:=ahkframe . ".document.all(" . ID1 . ")"
   Else
      ahkele:=ahkframe . ".document.all('" . ID1 . "')"
   
;~    tagName:=IE7_ExecuteJS(parentWindow, "var tagName=" . ahkele . ".sourceIndex;" , "tagName")
;~    MsgBox % tagName
   tagName:=IE7_ExecuteJS(parentWindow, "var tagName=" . ahkele . ".tagName;" , "tagName")
   teststring:="inputselecttextarea"
   IfInString,teststring,%tagName%
      domString := ahkele . ".value"
   Else
      domString := ahkele . ".innerHTML"
   if val
      Return IE7_ExecuteJS(parentWindow, "var oDom=" . domString . "='" . val . "';","oDom")
   Else
      Return IE7_ExecuteJS(parentWindow, "var oDom=" . domString . ";","oDom")
   Return
}

at some point in the near future ill probably get around to adding an image click function but i just havent had a personal need yet
EDIT: decided to go with click element instead of click image
Edit added the frame dom and updated the new function
_________________
Read this
Com
Automate IE7 with Tabs


Last edited by tank on Tue Aug 05, 2008 2:01 am; edited 15 times in total
Back to top
View user's profile Send private message
tank



Joined: 21 Dec 2007
Posts: 678

PostPosted: Mon May 19, 2008 4:28 pm    Post subject: Dom Tool Reply with quote

this is a script i wrote based on the above demostrates some limited use but helps get you some valuable information for implementing an automation project
Again i hope someone finds this usefull
Code:


clickinfo=
(
function whichElement()
{
tname=event.srcElement.tagName;
tindex=event.srcElement.sourceIndex;
tid=event.srcElement.id;
name=event.srcElement.name;
val="";
switch(tname.toLowerCase())
{
case "input":
   val=event.srcElement.value;
   typ=event.srcElement.type
   if (typ.toLowerCase()=="button"){
   event.srcElement.disabled='true';
   }
   if (typ.toLowerCase()=="submit"){
   event.srcElement.disabled='true';
   }
   if (typ.toLowerCase()=="image"){
   event.srcElement.disabled='true';
   }
   if (typ.toLowerCase()=="reset"){
   event.srcElement.disabled='true';
   }
innerhtml=val;
  break;   
case "a":
   event.srcElement.onclick="";
   link = "\nLink = "+event.srcElement.href
innerhtml=event.srcElement.innerHTML+link;
   event.srcElement.href="javascript:Void(0)";
  break;
case "select":
   val=event.srcElement.value;
innerhtml=val;
  break;
default:
innerhtml=event.srcElement.innerHTML
}
}
    document.body.onmousedown = whichElement
)
instructions=
(
1`) Enter a title
2`) Click Get Window
3`) Click the location on the browser window you need info on
4`) Click Get Dom
)
Gui, Add, Text, x6 y10 w130 h20 , Enter the Page Title
Gui, Add, Edit, x6 y30 w210 h20 vWintitle,
Gui, Add, Text, x6 y50 w310 h60 , % instructions
Gui, Add, Button, x216 y30 w90 h20 gGetwin, Get Window
Gui, Add, Button, x6 y110 w90 h20 gGetDom, Get Dom
Gui, Add, Edit, x6 y130 w310 h90 vDom,

Gui, Show, h225 w320, DOM Extractor
Return

GuiClose:
ExitApp

Getwin:
Gui,Submit,NoHide
COM_Init()
parentWindow:=IE7_Get(Wintitle)
IE7_ExecuteJS(parentWindow, clickinfo)

return
GetDom:
tname:=IE7_ExecuteJS(parentWindow, "","tname")
tindex:=IE7_ExecuteJS(parentWindow, "","tindex")
tid:=IE7_ExecuteJS(parentWindow, "","tid")
name:=IE7_ExecuteJS(parentWindow, "","name")
innerhtml:=IE7_ExecuteJS(parentWindow, "","innerhtml")
GuiControl,Text,Dom,% "Dom accessable objects for document`.all collection `nElement type (" . tname . ")`nIndex (" . tindex . ")`nID attribute if any (" . tid . ")`nName attribute if any (" . name . ")`nhtml value = " . innerhtml
return

If any one wants to suggest enhancements to this particular script or one of the previous scripts please let me know
_________________
Read this
Com
Automate IE7 with Tabs
Back to top
View user's profile Send private message
tank



Joined: 21 Dec 2007
Posts: 678

PostPosted: Mon May 19, 2008 4:32 pm    Post subject: Forms and links in a separate window Reply with quote

this is just the javascript that you would use with execute js on a given window
this script will output all forms and relavent dom elements and information to a new html window
it will then list all of the links as well
from an automation standpoint this is nearly every peice of information from an entering data aspect you could ever need
what it doesnt get is form elements not included in a <form></form> tag
Code:

list_elements=
(
var x=document.forms;
win=window.open("blank.htm","forms1");

for (var f=0;f<=x.length-1;f++)  {
 win.document.writeln("<table border=1 cellspacing=0>");
win.document.writeln("<tr><td>form");
  win.document.writeln("</td><td>name");
  win.document.writeln("</td><td>id");
  win.document.writeln("</td><td>action");
win.document.writeln("</td><td>OnSubmit");
 win.document.writeln("<tr><td>");
  win.document.writeln("<tr><td>" + f);
  win.document.writeln("</td><td>&nbsp;");
  win.document.writeln(x[f].name);
  win.document.writeln("</td><td>&nbsp;");
  win.document.writeln(x[f].id);
  win.document.writeln("</td><td>&nbsp;");
  win.document.writeln(x[f].action);
  win.document.writeln("</td><td>&nbsp;");
  win.document.writeln(x[f].OnSubmit);
  win.document.writeln("</td></tr>");

 win.document.writeln("</table>");

 win.document.writeln("<table border=1 cellspacing=0>");
win.document.writeln("<tr><td>Element");
  win.document.writeln("</td><td>name");
  win.document.writeln("</td><td>id");
  win.document.writeln("</td><td>value");
win.document.writeln("</td><td>type");
win.document.writeln("</td><td>onclick");
win.document.writeln("</td><td>onchange");
win.document.writeln("</td><td>innerHTML");
  win.document.writeln("</td></tr>");
var l=x[f].elements
for (var i=0;i<=l.length-1;i++) 
{
win.document.writeln("<tr><td>" + i);
win.document.writeln("</td><td>"+l[i].name);
win.document.writeln("</td><td>"+l[i].id);
win.document.writeln("</td><td>"+l[i].value);
win.document.writeln("</td><td>"+l[i].type);
win.document.writeln("</td><td>"+l[i].onClick);
win.document.writeln("</td><td>"+l[i].onChange);
win.document.writeln("</td><td>"+l[i].innerHTML);
win.document.writeln("</td></tr>");
 }

 win.document.writeln("</table>");
  }


 win.document.writeln("</table>");
 win.document.writeln("<table border=1 cellspacing=0>");
win.document.writeln("<tr><td>All links index");
  win.document.writeln("</td><td>href");
  win.document.writeln("</td><td>target");
  win.document.writeln("</td><td>innerHTML");
  win.document.writeln("</td><td>name");
  win.document.writeln("</td><td>id");
  win.document.writeln("</td><td>class");
  win.document.writeln("</td><td>onclick");
  win.document.writeln("</td></tr>");
var y=document.links;
for (var m=0;m<=y.length-1;m++)  {
  win.document.writeln("<tr><td>" + m);
  win.document.writeln("</td><td>&nbsp;");
  win.document.writeln(y[m].href);
  win.document.writeln("</td><td>&nbsp;");
  win.document.writeln(y[m].target);
  win.document.writeln("</td><td>&nbsp;");
  win.document.writeln(y[m].innerHTML);
  win.document.writeln("</td><td>&nbsp;");
  win.document.writeln(y[m].name);
  win.document.writeln("</td><td>&nbsp;");
  win.document.writeln(y[m].id);
  win.document.writeln("</td><td>&nbsp;");
  win.document.writeln(y[m].className);
  win.document.writeln("</td><td>&nbsp;");
  win.document.writeln(y[m].onclick);
  win.document.writeln("</td></tr>");
}
 win.document.writeln("</table>");
)

_________________
Read this
Com
Automate IE7 with Tabs
Back to top
View user's profile Send private message
Sean



Joined: 12 Feb 2007
Posts: 1338

PostPosted: Sun May 25, 2008 9:21 am    Post subject: Reply with quote

tank already knew this, however, I'm posting it anyway for who is not aware of it.

IE7 supports multi-tab windows, but the conventional WebBrowser control is lacking of a function to differentiate one among them, the HWND function in IWebBrowser2 object always returns the window handle of IEFrame, not the new window class TabWindowClass.

Here is a method to obtain the window handle of TabWindowClass from the IWebBrowser2 object pwb (:if applied to IE6 etc, I think it'll just return the window handle of IEFrame).

Code:
IETabWindow(pwb)
{
   psb  :=   COM_QueryService(pwb,IID_IShellBrowser:="{000214E2-0000-0000-C000-000000000046}")
   DllCall(NumGet(NumGet(1*psb)+12), "Uint", psb, "UintP", hwndTab)
   DllCall(NumGet(NumGet(1*psb)+ 8), "Uint", psb)
   Return   hwndTab
}
Back to top
View user's profile Send private message
tank



Joined: 21 Dec 2007
Posts: 678

PostPosted: Mon May 26, 2008 3:53 am    Post subject: Reply with quote

@ Sean thanks
I considered this but i was trying to be generic thru versions of IE supporting tabbed and non tabbed browsing with the same scripti did notice just now that i took out the comments for the new window vs new tab vs new unfocused tab

But then i spose i shoulodnt have labeled them as IE7 functions instead just calling them IE_ either way its good to know that it works fine without the hwndTab though the hwndTab does give you some other options for action not included in the DOM usage demonstrated

At any rate Sean thank you for posting what i think will be a much needed missing link in the event someone needs it the goal of the whole post here was to help feild the many questions about how to automate web forms and scrape data from browser screens. hopefully the number of views on this post without questions means i might have accomplished this.

Sean wrote:

Here is a method to obtain the window handle of TabWindowClass from the IWebBrowser2 object pwb (:if applied to IE6 etc, I think it'll just return the window handle of IEFrame).


IShellBrowser
http://msdn.microsoft.com/en-us/library/bb775123(VS.85).aspx
IWebBrowser2::HWND Property
http://msdn.microsoft.com/en-us/library/aa752126(VS.85).aspx

I actually "thought" the contrary Now that you mention it it makes some sense i'll have to test Very Happy tho
The IWebBrowser2::HWND Property does seem to confirm your statement


Sean wrote:

the HWND function in IWebBrowser2 object always returns the window handle of IEFrame, not the new window class TabWindowClass.


Yes this of course is perfectly accurate but for My particular needs it was all that was necesary.... In hindsite to make a truly usefull IE automation Wrapper Function Library or WFL Shocked (too far or is a new acronym ok here) it would Probably better to expose the TabWindowClass.
Lets not forget this is all just an implementation of YOUR genious any how Very Happy


also if not entirely obvious to those reading this going from the hTab to the document object
(unless Sean has a better way)
Code:
   
         COM_AtlAxAttachControl(pwb, hTab)
         doc:=COM_Invoke(pwb, "Document")
         parentWindow:=COM_Invoke(doc, "parentWindow")
         COM_Invoke(parentWindow, "execScript","alert('js executed')")
         COM_Release(doc),COM_Release(parentWindow), COM_Release(pwb)

_________________
Read this
Com
Automate IE7 with Tabs
Back to top
View user's profile Send private message
Sean



Joined: 12 Feb 2007
Posts: 1338

PostPosted: Mon May 26, 2008 6:06 am    Post subject: Reply with quote

tank wrote:
Code:
         COM_AtlAxAttachControl(pwb, hTab)
         doc:=COM_Invoke(pwb, "Document")
         parentWindow:=COM_Invoke(doc, "parentWindow")
         COM_Invoke(parentWindow, "execScript","alert('js executed')")
         COM_Release(doc),COM_Release(parentWindow), COM_Release(pwb)

I'm surprised. It looks very interesting. In what process was pwb created? You seem to attach a COM object created in one process to a window created by another process... Am I right? Did ATL handle it well?
Back to top
View user's profile Send private message
tank



Joined: 21 Dec 2007
Posts: 678

PostPosted: Mon May 26, 2008 4:12 pm    Post subject: Reply with quote

Sean wrote:
tank wrote:
Code:
         COM_AtlAxAttachControl(pwb, hTab)
         doc:=COM_Invoke(pwb, "Document")
         parentWindow:=COM_Invoke(doc, "parentWindow")
         COM_Invoke(parentWindow, "execScript","alert('js executed')")
         COM_Release(doc),COM_Release(parentWindow), COM_Release(pwb)

I'm surprised. It looks very interesting. In what process was pwb created? You seem to attach a COM object created in one process to a window created by another process... Am I right? Did ATL handle it well?

As a matter of fact it did handle it well
I tested this both with this method used in browser control here
http://www.autohotkey.com/wiki/index.php?title=Internet_Explorer_Control
Code:

CLSID_WebBrowser := "{8856F961-340A-11D0-A96B-00C04FD705A2}"
IID_IWebBrowser2 := "{D30C1661-CDAF-11D0-8A3E-00C04FC9E26E}"
pwb := CreateObject(CLSID_WebBrowser, IID_IWebBrowser2)

and the method i use in my functions (ok you got me i got the idea from you) Cool

Code:

pwb:=COM_Invoke(COM_Invoke(COM_CreateObject("Shell.Application"), "Windows"), "Item", 0) ; any zero based index of browser windows

Before going any farther i want to make sure every one reading this understands something very well
the windows collections includes windows explorer and internet explorer so if you cant return a documant object its likely because you have a folder view open Sad
this is why my functions loop to match Frame Titles
so assuming the last code above returns a iwebrowser interface they both work with the
COM_AtlAxAttachControl puts the handle and the pwb together well. tho my second method really has no reason to approach the hwnd at all unless you need access to it for other uses ...... Ill not dare those here because lack oif experience using it

as sean pointed out my method takes you straight to the of IEFrame and then to the Document object. For purposes of automating Long jobs in an IE window the DOM is all you need
actually im making a minor statement change the pwb is a IWebBrowser2 Interface and Exposes methods that are implemented by the WebBrowser control (Microsoft ActiveX control) or implemented by an instance of the InternetExplorer application (OLE Automation). For the Microsoft .NET Framework version of this control, see WebBrowser Control (Windows Forms).

Seans function obtains the window handle of TabWindowClass from the IWebBrowser2 object Very Happy

Sean wrote:

IE7 supports multi-tab windows, but the conventional WebBrowser control is lacking of a function to differentiate one among them, the HWND function in IWebBrowser2 object always returns the window handle of IEFrame, not the new window class TabWindowClass


I bring it up to beclear pwb is an interface pointer that exposes methods and porerties avaiable to 2 different (albiet Similar) objects
http://msdn.microsoft.com/en-us/library/aa752127.aspx
the pwb will refer to the browser object in a particular tab in IE7not internet explorer as a whole

No matter which way i go about creating the pwb this approach works fine
I use both apraoches often in my personal and professional endeavors[/quote][/code]
_________________
Read this
Com
Automate IE7 with Tabs
Back to top
View user's profile Send private message
tank



Joined: 21 Dec 2007
Posts: 678

PostPosted: Sat May 31, 2008 2:01 pm    Post subject: Example of Automated Page Nav and Filling out Web Forms Reply with quote

Code:
COM_Init()
run iexplore.exe http://www.autohotkey.com/
WinWait,AutoHotkey,,5
sleep,1000
myPageHandle:=IE7_Get("autohotkey")
;~ MsgBox % myPageHandle
IE7_readyState(myPageHandle) ;  waits for onload event of a webpage even if an onload isnt fired
IE7_Click_Text(myPageHandle,"forum") ; cycles thru the links collection and clicksthe first text match it finds then waits for the page load to complete

IE7_Click_Text(myPageHandle,"search")
IE7_Set_DOM(myPageHandle,"search_keywords","PLEASE HELP!! why is my thingy not working as expected?") ;example of filling out a form
IE7_Button_click(myPageHandle,"search")
IE7_Click_Text(myPageHandle,"PLEASE HELP!! why is my thingy not working as expected?")
MsgBox, 262192, Meet the Robinsons, Please Read the first Post before asking me any questions, 5
IE7_Click_Text(myPageHandle,"search")
IE7_Set_DOM(myPageHandle,"search_keywords","Automation IE7 Navigation and Scripting with Tabs") ;example of filling out a form
IE7_Button_click(myPageHandle,"search") ; click a button labeled search and wait for the page to load
IE7_Click_Text(myPageHandle,"Wait for page to load before execute next command")
MsgBox, 262192, Automation IE7 Navigation and Scripting with Tabs, 5
COM_Term()
ExitApp

the above gives an example of opening a page and clicking links and filling out web forms then clicking buttons
_________________
Read this
Com
Automate IE7 with Tabs
Back to top
View user's profile Send private message
imapow



Joined: 13 Mar 2008
Posts: 162
Location: Trøndelag, Norway

PostPosted: Sun Jun 01, 2008 12:03 am    Post subject: Reply with quote

you shold add another pool answer "i use firefox but its a good idea"
_________________
-._.-¨¯¨-._.-IM@PΩW-._.-¨¯¨-._.-


Last edited by imapow on Sun Jun 01, 2008 10:34 am; edited 1 time in total
Back to top
View user's profile Send private message
tank



Joined: 21 Dec 2007
Posts: 678

PostPosted: Sun Jun 01, 2008 4:24 am    Post subject: Reply with quote

imapow wrote:
you sold add another pool answer "i use firefox but its a good idea"

huh
_________________
Read this
Com
Automate IE7 with Tabs
Back to top
View user's profile Send private message
imapow



Joined: 13 Mar 2008
Posts: 162
Location: Trøndelag, Norway

PostPosted: Sun Jun 01, 2008 10:33 am    Post subject: Reply with quote

tank wrote:
huh

?
_________________
-._.-¨¯¨-._.-IM@PΩW-._.-¨¯¨-._.-
Back to top
View user's profile Send private message
Display posts from previous:   
Post new topic   Reply to topic    AutoHotkey Community Forum Index -> Scripts & Functions All times are GMT
Goto page 1, 2, 3, 4, 5, 6  Next
Page 1 of 6

 
Jump to:  
You can post new topics in this forum
You can reply to topics in this forum


Powered by phpBB © 2001, 2005 phpBB Group