c# - 单击 WebBrowser 控件中 iframe 中的按钮

标签 c# winforms iframe webbrowser-control

我正在使用 C#,赢得应用程序,试图单击在我的网络浏览器的 iframe 中找到的按钮。

HTML:

<iframe frameborder="0" scrolling="no" id="EditorIFrmae" name="EditorIFrmae" width="100%" height="700" style="z-index: 0; height: 852px;" src="X"></iframe>

在 iframe 代码中:

<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>

我的代码:

HtmlElementCollection linkit = this.webBrowser1.Document.GetElementsByTagName("div");
            foreach (HtmlElement foundit in linkit)
            {
                if (foundit.GetAttribute("id").Equals("SB_Content_PagePreview"))
                {
                    foundit.InvokeMember("Click");
                }
            }

我怎样才能点击按钮?

最佳答案

您可以使用 Document.Window.Frames[] 获取框架,该框架接受框架的 id(string) 或 index(int)。

您还应该考虑,您应该等到 DocumentCompleted 事件引发,然后再完成您的工作。当页面中有一些 iframe 时,DocumentCompleted 事件不止一次触发,使用下面的代码通过检查 eventarg 的 url 我们确保这是 main 的 DocumentCompleted 事件我们需要的页面,然后您可以启用一个标志来表明文档已完成,并在此处或其他地方找到您想要的框架和元素。

代码在哪里:

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");
        }
    }
}

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>

test2.html 内容:

<html>
<head>
    <title>IFRAME</title>
</head>
<body>
   <button id="buttonid" onclick="alert('Clicked')">Click Me</button> 
</body>
</html>

截图:

enter image description here

关于c# - 单击 WebBrowser 控件中 iframe 中的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32933513/

相关文章:

c# - 可编辑的 WPF ListView

c# - 如何在 devexpress GridControl 中添加行,就像我们在普通 datagridview 中添加行一样。 (WinForms C#)

vb.net - 设计模式错误 - "Resource has no property named ' myResource'"

html - 我网页上两个元素之间的 CSS 对齐

javascript - 新建iframe并同步加载内容

c# - 为什么 CLR 的 jmp 指令无法验证?

c# - 子级完全初始化后如何执行基类中的方法?

c# - 如何在使用 Pechkin 生成的 PDF 中进行分页

c# - 运行时本地化

javascript - 什么 CSP 子 iframe 从其父级继承?