Windows Forms WebBrowser control and iframes

2019-02-13 18:11发布

问题:

I am trying to create a piece of software to more or less automate form-fillings on a webpage - and I have decided to use the WebBrowser control in System.Windows.Forms. This works great and I can easily manipulate the DOM through webbrowser.Document and so forth. However unfortunately the site that I am doing automation on has a file upload which is ran inside an iframe - and this is where I am stuck, I simply cannot work out how to be able to manipulate elements inside the DOM of the iframe.

Ideally what I'd like to do is something like:

HtmlElement iframe = browser.Document.GetElementById("iframe_id");
iframe.InnerDocument.GetElementById("file_upload_input").SetAttribute("value", "myfile.txt");

And then submit the form inside the iframe of course - however there is no InnerDocument attribute on HtmlElement as far as I can see, nor no type that I have found that I can cast HtmlElement to so that I can access the inner DOM.

How this is done?

回答1:

Try using the "frames" collection instead. From MSDN:

The iframe element functions as a document within a document, or like a floating frame. The frames collection provides access to the contents of an iframe. Use the frames collection to read or write to elements contained in an iframe. For example, the syntax for accessing the backgroundColor style of the body object in an iframe is:

sColor = document.frames("sFrameName").document.body.style.backgroundColor;