Auto Website Login: SetAttribute not working

后端 未结 1 367
野性不改
野性不改 2020-12-12 04:32

I\'m creating a program dashboard and one feature is that the user is automatically logged into a website site using stored credentials in the program (no need to open chrom

相关标签:
1条回答
  • 2020-12-12 04:59

    You don't need any async procedure here. The WebBrowser.DocumentCompleted event is already invoked asynchronously. DoEvents() is equally useless if not disruptive.

    You just need to subscribe to the DocumentCompleted event and call the Navigate method to let the WebBrowser load the remote Html resource.

    When the HtmlDocument is finally loaded, the WebBrowser will signal its completion setting its state to WebBrowserReadyState.Complete.

    About the Html Input Element and Forms:
    here, the code is supposing that there's only one Form in that HtmlDocument.
    It may be so, but it may be not. A Html Document can have more than one Form and each Frame can have its own Document. IFrames will have one each for sure.

    Read the notes in this answer (C# code, but you just need the notes) for more informations on how to handle multiple Frames/IFrames


    Button1 will wire up the DocumentCompleted event and call Navigate().
    When the Document is completed, the code in the event handler will run and perform the LogIn procedure.
    The event handler is then removed, since it has complelted its task and you still need to use the WebBrowser for other purposes.

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Button1.Enabled = False
        WebSiteLogIn()
    End Sub
    
    Private Sub WebSiteLogIn()
        AddHandler WebBrowser1.DocumentCompleted, AddressOf PageWaiter
        WebBrowser1.Navigate("https://thesite.com/#/login")    
    End Sub
    
    Private Sub PageWaiter(ByVal sender As Object, ByVal e As WebBrowserDocumentCompletedEventArgs)
        If WebBrowser1.ReadyState = WebBrowserReadyState.Complete Then
            WebBrowser1.Document.GetElementById("username").SetAttribute("value", "Username")
            WebBrowser1.Document.GetElementById("Password").SetAttribute("value", "Password")
    
            Dim allInputElements = WebBrowser1.Document.Body.All.
                Cast(Of HtmlElement).Where(Function(h) h.TagName.Equals("INPUT")).ToList()
    
            For Each element As HtmlElement In allInputElements
                If element.GetAttribute("type").ToUpper().Equals("SUBMIT") Then
                    element.InvokeMember("click")
                End If
            Next
    
            RemoveHandler WebBrowser1.DocumentCompleted, AddressOf PageWaiter
            Button1.Enabled = True
        End If
    End Sub
    
    0 讨论(0)
提交回复
热议问题