我正在尝试使用网络浏览器控件使用 C# 来废弃一些页面。
为了获取所有要废弃的信息,我必须单击具有 onclick 事件的 span 元素。
这就是跨度的样子:
<span title="title" class="class" onclick="somefunction(value);"></span>
这是我的代码:
foreach (HtmlElement span in table.GetElementsByTagName("span"))
{
span.InvokeMember("click");
}
它真的很简单,但由于某种原因它什么也没做。我尝试评估代码,得到的结果为空。
知道如何调用该点击吗?
最佳答案
这是一个使用 .NET 4.5 和 WPF 的示例,但任何内容都可以轻松调整以适应 WinForm WebBrowser 控件。 我假设您的 HTML 页面如下所示:
<html>
<head>
<script>
function somefunction(value){
alert("clicked on: " + value);
}
</script>
</head>
<body>
<span title="title" class="class" onclick="somefunction('span_01');">Blah blah blah</span>
<span title="title" class="class" onclick="somefunction('span_02');">Blah blah blah</span>
<span title="title" class="class" onclick="somefunction('span_03');">Blah blah blah</span>
</body>
</html>
并且您有一个包装 WebBrowser 控件的 UserControl(下面的 XAML)
<UserControl x:Class="WebBrowserExample.WebBrowserAdapter"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<WebBrowser x:Name="WebBrowserControl"></WebBrowser>
</Grid>
</UserControl>
然后一个可能的解决方案是向页面注入(inject)一个 Javascript 函数来执行您想要的操作并从 .NET 调用它。 将以下方法添加到 WebBrowserAdapter 类:
void WebBrowserAdapter_Loaded(object sender, RoutedEventArgs e)
{
WebBrowserControl.LoadCompleted += WebBrowserControl_LoadCompleted;
WebBrowserControl.Navigate("http://localhost:9080/console/span.html");
}
void WebBrowserControl_LoadCompleted(object sender, NavigationEventArgs e)
{
IncjectClickOnSpanElementScript();
}
private void IncjectClickOnSpanElementScript()
{
String script =
@" function triggerClicksOnSpan(){
var spans = document.getElementsByTagName('span');
for(var i = 0; i < spans.length; i++){
spans[i].click();
}
}";
InjectScript(script);
WebBrowserControl.InvokeScript("triggerClicksOnSpan");
}
public void InjectScript(String scriptText)
{
HTMLDocument htmlDocument = (HTMLDocument)WebBrowserControl.Document;
var headElements = htmlDocument.getElementsByTagName("head");
if (headElements.length == 0)
{
throw new IndexOutOfRangeException("No element with tag 'head' has been found in the document");
}
var headElement = headElements.item(0);
IHTMLScriptElement script = (IHTMLScriptElement)htmlDocument.createElement("script");
script.text = scriptText;
headElement.AppendChild(script);
}
您需要在项目引用中添加Microsoft.mshtml。 请注意,在这个简化的示例中,每次加载页面时都会注入(inject)脚本。我想您需要调整代码以适应您的需求
关于javascript - webbrowser 不调用跨度上的单击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31430617/