I'm using C#, win apps, trying to click a button that found in a iframe on my webbrowser.
HTML:
<iframe frameborder="0" scrolling="no" id="EditorIFrmae" name="EditorIFrmae" width="100%" height="700" style="z-index: 0; height: 852px;" src="X"></iframe>
In the iframe code:
<div height="" width="100%" style="position: relative; min-height: 50px;" onclick="javascript:funcEditPage('SB_Content_Page','SB_Content_PagePreview','PAGE5.asp');" class="SB_DivContentPreview" id="SB_Content_PagePreview">
</div>
My code:
HtmlElementCollection linkit = this.webBrowser1.Document.GetElementsByTagName("div");
foreach (HtmlElement foundit in linkit)
{
if (foundit.GetAttribute("id").Equals("SB_Content_PagePreview"))
{
foundit.InvokeMember("Click");
}
}
How am I able to click on the button?
You can get a frame using Document.Window.Frames[]
that accepts id(string) or index(int) of frame.
Also you should consider you should wait until DocumentCompleted
event raise and then do your job. When there are some iframe in a page, DocumentCompleted
event fires more than once and using below code by checking the url of eventarg we make sure that this is the DocumentCompleted
event of main page that we need, then you can enable a flag to say the document is completed and here or somewhere else, find the frame and the element you want.
Where is the code:
public partial class Form1 : Form
{
private void Form1_Load(object sender, EventArgs e)
{
this.webBrowser1.Navigate(@"d:\test.html");
this.webBrowser1.DocumentCompleted += webBrowser1_DocumentCompleted;
}
bool completed = false;
void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (e.Url == webBrowser1.Document.Url)
{
completed = true;
}
}
private void clickToolStripButton_Click(object sender, EventArgs e)
{
if(completed)
{
var frame = webBrowser1.Document.Window.Frames["iframeid"];
var button = frame.Document.GetElementById("buttonid");
button.InvokeMember("click");
}
}
}
Content of test.html:
<html>
<head>
<title>OUTER</title>
</head>
<body>
Some Content <br/>
Some Content <br/>
Some Content <br/>
iframe:
<iframe src="test2.html" id="iframeid"></iframe>
</body>
</html>
Content of test2.html:
<html>
<head>
<title>IFRAME</title>
</head>
<body>
<button id="buttonid" onclick="alert('Clicked')">Click Me</button>
</body>
</html>
Screenshot:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With