我希望我的浏览器(GeckoFX)在单击我的网页中的按钮时执行.NET功能。我有以下代码:
public Form1()
{
InitializeComponent();
AddMessageEventListener("myFunction", ((string s) => this.showMessage(s)));
browser.LoadHtml
(
@"<!DOCTYPE html>
<html><head>
<meta http-equiv=""Content-Type"" content=""text/html; charset=UTF-8"">
<script type=""text/javascript"">
function fireEvent(name, data)
{
event = document.createEvent('MessageEvent');
event.initMessageEvent(name, false, false, data, null, null, null, null);
document.dispatchEvent(event);
}
</script>
</head>
<body>fdsfsda
<input type=""button"" onclick=""fireEvent('myFunction', 'some data');"" value=""SHOW DATA"" />
</body></html>"
);
}
public void AddMessageEventListener(string eventName, Action<string> action)
{
browser.AddMessageEventListener(eventName, action);
}
private void showMessage(string s)
{
MessageBox.Show(s);
}
但是当运行该代码时,该行
browser.AddMessageEventListener(eventName, action);
给我一个'对象引用未设置为对象的实例'错误。我不明白,因为我已经检查了该行中的所有对象都已初始化。有人可以帮助并告诉我为什么会收到此错误吗?
非常感谢你!
您可以尝试不同的方法。订阅browser.DomClick事件 - 只要点击某些内容就会触发它。从那里,您可以过滤掉无趣的点击,只在单击所需的元素时调用更多代码。
Browser.DomClick += browser_DomClick;
然后
private void browser_DomClick(object sender, DomMouseEventArgs e)
{
var browser = sender as GeckoWebBrowser;
if (sender != null && e != null && e.Target != null)
{
if (e.Button == GeckoMouseButton.Left)
{
HandleLeftClick(e);
}
if (e.Button == GeckoMouseButton.Middle)
{
HandleMiddleClick(e);
}
if (e.Button == GeckoMouseButton.Right)
{
HandleRightClick(e);
}
}
}
尝试在LoadHtml之后添加AddMessageEventListener,如下所示:
browser.LoadHtml(@"<!DOCTYPE html>.....</html>");
AddMessageEventListener("myFunction", ((string s) => this.showMessage(s)));
并在LoadHtml中更改此行:
event = document.createEvent('MessageEvent');
event.initMessageEvent(name, false, false, data, null, null, null, null);
这样:
var event = new MessageEvent(name,{'view': window, 'bubbles': false, 'cancelable': false, 'data': data});
您的新代码如下:
public Form1()
{
InitializeComponent();
browser.LoadHtml
(
@"<!DOCTYPE html>
<html><head>
<meta http-equiv=""Content-Type"" content=""text/html; charset=UTF-8"">
<script type=""text/javascript"">
function fireEvent(name, data)
{
var event = new MessageEvent(name,{'view': window, 'bubbles': false, 'cancelable': false, 'data': data});
document.dispatchEvent(event);
}
</script>
</head>
<body>fdsfsda
<input type=""button"" onclick=""fireEvent('myFunction', 'some data');"" value=""SHOW DATA"" />
</body></html>"
);
AddMessageEventListener("myFunction", ((string s) => this.showMessage(s)));
}
private void showMessage(string s)
{
MessageBox.Show(s);
}