WPF,js调用服务端和服务端调用js单独调用都可以,但是把这2个单独的流程连起来的时候就出错了,服务端调用CS出错了, 错误提示“未知名称” public partial class WebBrowserWindow : Window { public Action webHandler; public Boolean isMove = false; public WebBrowserWindow() { InitializeComponent(); this.webBrowser.ObjectForScripting = new ScriptObject(this); this.webBrowser.LoadCompleted += new System.Windows.Navigation.LoadCompletedEventHandler(webBrowser_LoadCompleted); //Console.WriteLine("webBrowser"+webBrowser.Ver) this.webBrowser.Navigate("file:///C:\test.html"); } void webBrowser_LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e) { if (this.webHandler != null) { this.webHandler(); this.webHandler = null; } } //单独调用可以 private void btn2_Click(object sender, RoutedEventArgs e) { this.webBrowser.InvokeScript("showmsg", new object[] { "{"center":{"lng":12.232,"lat":13.232},"zoom":14}", "{"center2":{"lng":12.232,"lat":13.232},"zoom":14}" }); } public void toClient(string type) { try { webBrowser.InvokeScript("showmsg", new object[] { "{"center":{"lng":12.232,"lat":13.232},"zoom":14}" }); } catch (Exception e) { Console.WriteLine("Error" + e.Message);//提示错误未知名称 } } [ComVisible(true)] public class ScriptObject { private Window instance; public ScriptObject(Window instance) { this.instance = instance; } public void doSomething(string msg) { MessageBox.Show(msg, "receive from", MessageBoxButton.OK, MessageBoxImage.Information); WebBrowserWindow window = new WebBrowserWindow(); window.toClient(""); // 是不是外部调用有问题? Console.WriteLine("end....."); } } }
页面JS: <script type="text/javascript"> (function (window) { var searcher = { showmsg: function (msg1) { alert("msg1:"+msg1); } }; window.searcher = searcher; })(window); function showmsg(msg1) { searcher.showmsg(msg1); } function invekeServer(traits){ window.external.doSomething(""); return false; } </script> |
|
100分 |
似乎没搞清楚Js交互的服务端是哪里。webBrowser不能算是服务端吧
|
服务端是C#应用,webBrowser是C#窗口的一个控件
|
|
问题解决了。 换一种思路,js 调用服务端返回就行了
public string doSomething(string msg) { MessageBox.Show(msg, “receive from”, MessageBoxButton.OK, MessageBoxImage.Information); return “”;
} |