隔江千里
此示例展示了从 javascript 到 C# 通信的两种不同方式。第一种方法是使用(哈顿方法)消息泵。第二种方法是使用javascript 更改location当前文档并使用C# 处理和取消导航。示例 HTML:<html><body></body><script type='text/javascript'> /* Begin (Hatton) method of communicating from javascript to C# */ alert('javascript : about call message C# (Hatton) method'); event = document.createEvent('MessageEvent'); var origin = window.location.protocol + '//' + window.location.host; event.initMessageEvent ('callMe', true, true, 'some data', origin, 1234, window, null); document.dispatchEvent (event); alert('javascript : message sent to C# (Hatton) method'); /* End (Hatton) method of communicating from javascript to C# */ /* Begin javascript changing location.href method */ alert('javascript : about call message C# location changed method'); location.href='http://somehost//someevent.php?somedata'; alert('javascript : message sent to C# location changed method'); /* End javascript changing location.href method */</script></html>Example.cs 代码:using System;using System.IO;using System.Windows.Forms;using Gecko; namespace Example6{ static class Example6 { private static GeckoWebBrowser _browser; [STAThread] static void Main() { // Don't use XULRunnerLocator.GetXULRunnerLocation() in production software. string firefox14Path = XULRunnerLocator.GetXULRunnerLocation(); Xpcom.Initialize(firefox14Path); var form = new Form(); _browser = new GeckoWebBrowser { Dock = DockStyle.Fill }; _browser.Navigating += InstallCustomEventListener; _browser.Navigating += ListenForFakeNavigationMessages; _browser.Navigate("file://" + Path.Combine(Environment.CurrentDirectory, "Example6.html")); form.Controls.Add(_browser); Application.Run(form); } #region Hatton method static void InstallCustomEventListener(object sender, GeckoNavigatingEventArgs e) { _browser.Navigating -= InstallCustomEventListener; _browser.AddMessageEventListener("callMe", ((string p) => MessageBox.Show(String.Format("C# : Got Message '{0}' from javascript", p)))); } #endregion #region location changed method static void ListenForFakeNavigationMessages(object sender, GeckoNavigatingEventArgs e) { const string id = "http://somehost//someevent.php?"; var uri = e.Uri.AbsoluteUri; if (uri.Contains(id)) { MessageBox.Show(String.Format("C# : Got Message '{0}' from javascscript", uri.Substring(id.Length))); // This is a fake navigating event - cancel it. e.Cancel = true; } } #endregion }}