C# webBrowser(wpf/winform) 互调js

Posted 一步一个脚印

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C# webBrowser(wpf/winform) 互调js相关的知识,希望对你有一定的参考价值。

1.winform

[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
[ComVisible(true)]
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.Load += Form1_Load;
}

private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.ObjectForScripting = this;//具体公开的对象,这里可以公开自定义对象
webBrowser1.Navigate(Application.StartupPath + "/dom.html");
}

private void button1_Click(object sender, EventArgs e)
{
webBrowser1.Document.InvokeScript("Run", new object[] { "test" });
}

public void ShowMsg(string msg)
{
MessageBox.Show(msg);
}

}

 

2.wpf


public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.Loaded += MainWindow_Loaded;
}

private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
this.webBrowser1.ObjectForScripting = new OprateBasic();
Uri uri = new Uri(@"pack://application:,,,/dom.html");
Stream source = Application.GetResourceStream(uri).Stream;
webBrowser1.NavigateToStream(source);
}

private void btn1_Click(object sender, RoutedEventArgs e)
{
webBrowser1.InvokeScript("Run", new object[] { "test" });
}
}

[ComVisible(true)] // 将该类设置为com可访问
public class OprateBasic
{
public void ShowMsg(string msg)
{
MessageBox.Show(msg);
}
}

 

dom.html

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<script type="text/javascript" charset="utf-8">
function Run(str) {

window.external.ShowMsg(str);
}
</script>
</body>
</html>

 

以上是关于C# webBrowser(wpf/winform) 互调js的主要内容,如果未能解决你的问题,请参考以下文章

WPF+WinForm系统主页框架Demo(附带一些小功能!)

C# webbrowser cookie

C# WinForm开发系列 - WebBrowser

C# webbrowser怎么判断登录是不是成功?

我如何在 webBrowser 中使用 c# 执行点击事件

如何在 C# 中使用 WebBrowser 控件清除浏览历史记录