C# 如何在 WebBrowser 实例中的 WPF 和 JavaScript 之间进行通信?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12052992/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 20:13:29  来源:igfitidea点击:

How to communicate between WPF and JavaScript in a WebBrowser instance?

c#javascriptwpfbrowsercommunicate

提问by koalabruder

I have a C#/WPF application with an embedded browser (WebBrowser) with some JavaScript. How can they communicate with each other in both directions? Is it practicable to use the URL?

我有一个带有嵌入式浏览器 (WebBrowser) 和一些 JavaScript 的 C#/WPF 应用程序。它们如何在两个方向上相互通信?使用 URL 是否可行?

JS->WPF: Listen for changes. WPF->JS: Change the URL to javascript:alert('hello');

JS->WPF:监听变化。WPF->JS:将 URL 更改为javascript:alert('hello');

Is there a better way?

有没有更好的办法?

采纳答案by koalabruder

It's important to know that there are two WebBrowser. One for Windows Forms and one for WPF. The link below uses the WPF one. http://www.dotnetfunda.com/articles/article840-working-with-webbrowser-in-wpf.aspx

重要的是要知道有两个 WebBrowser。一种用于 Windows 窗体,一种用于 WPF。下面的链接使用 WPF 之一。 http://www.dotnetfunda.com/articles/article840-working-with-webbrowser-in-wpf.aspx

回答by mlemay

To invoke JavaScript function from C#

从 C# 调用 JavaScript 函数

object result = mWebBrowser.Document.InvokeScript("FunctionName", new String[] { Parameter1 });

// If the function succeed (my function return a boolean)
if (null == result || result.ToString().ToLower() == "false")
{
   // Code
}

Is this what you want? Like this your c# code call your javascript, and it returns a value

这是你想要的吗?像这样你的 c# 代码调用你的 javascript,它返回一个值

My WPF Xaml:

我的 WPF Xaml:

<UserControl x:Class="MediaViewer.WebViewer"
         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:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms">
   <WindowsFormsHost>
      <wf:WebBrowser x:Name="mWebBrowser" />
   </WindowsFormsHost>
</UserControl>