Search code examples
c#.netshdocvw

how to click this javascript button?


In the middle of a webpage I am trying to log into I have the following code

   <tr>
   <td colspan="2" align="center"><!--mstheme--><font face="Trebuchet MS, Arial, Helvetica">

       <br>
       <a href="javascript:SubmitAction()">
          <IMG SRC="images/logon.gif" WIDTH="47" HEIGHT="43" NATURALSIZEFLAG="3" BORDER="0">
       </a>


   <!--mstheme--></font></td>

I want to execute the SubmitAction() code, which will take my credentials and log me in. Using the WebBrowser from .NET works fine, because I can use "invokescript". I cannot do this with shdocvw though. How can I click or otherwise make this action occur, especially since the element has no id or tag?

Here's what my function currently looks like:

        private void webBrowser1_DocumentCompleted(object pDisp, ref object URL)
    {
        while (webBrowser.ReadyState < SHDocVw.tagREADYSTATE.READYSTATE_LOADED) { }
        //we are attempting to log in
        if (loggingIn)
        {
            mshtml.HTMLDocumentClass doc = webBrowser.Document as mshtml.HTMLDocumentClass;                
            doc.getElementById("Username").setAttribute("value", "MLAPAGLIA");
            doc.getElementById("Password").setAttribute("value", "PASSWORD");

            mshtml.IHTMLWindow2 win = doc.parentWindow as mshtml.IHTMLWindow2;
            win.execScript("SubmitAction()", "javascript");

            loggingIn = false;
            return;
        }

Solution

  • try (EDIT after comment):

    using SHDocVw;
    using mshtml;
    
    
    SHDocVw.InternetExplorer ie = new SHDocVw.InternetExplorer();
    ie.Visible = true;
    object o = new object();
    ie.Navigate("http://www.google.com", ref o, ref o, ref o, ref o);
    
    while (!(ie.ReadyState >= tagREADYSTATE.READYSTATE_LOADED))
           Application.DoEvents();
    
    var doc = ie.Document;
    
    var win = (IHTMLWindow2)doc.parentWindow;
    // here you call the Javascript
    win.execScript("SubmitAction();", "javascript");
    

    some interesting links: