Getting HTML body content in WinForms WebBrowser after body onload event executes

后端 未结 1 986
面向向阳花
面向向阳花 2020-11-29 12:44

I have a WebBrowser control in WinForms whose URL property is set to an external webpage. I also have an event handler for the DocumentCompleted event. Inside this handler,

相关标签:
1条回答
  • 2020-11-29 13:00

    Here is how it can be done, I've put some comments inline:

    private void Form1_Load(object sender, EventArgs e)
    {
        bool complete = false;
        this.webBrowser1.DocumentCompleted += delegate
        {
            if (complete)
                return;
            complete = true;
            // DocumentCompleted is fired before window.onload and body.onload
            this.webBrowser1.Document.Window.AttachEventHandler("onload", delegate
            {
                // Defer this to make sure all possible onload event handlers got fired
                System.Threading.SynchronizationContext.Current.Post(delegate 
                {
                    // try webBrowser1.Document.GetElementById("id") here
                    MessageBox.Show("window.onload was fired, can access DOM!");
                }, null);
            });
        };
    
        this.webBrowser1.Navigate("http://www.example.com");
    }
    

    Updated, it's 2019 and this answer is surprisingly still getting attention, so I'd like to note that my recommended way of doing with modern C# would be using async/await, like this.

    0 讨论(0)
提交回复
热议问题