主要是winform窗体中使用了webBrowser控件,webBrowser中调用javascript操作窗体里面的后台方法,使用下面的两句。
this.webBrowser1.ObjectForScripting = this;
webBrowser1.Url = new Uri(Path.Combine(Application.StartupPath, Version + @"\test.html"));
WebBrowser.ObjectForScripting 属性
.NET Framework 2.0
注意:此属性在 .NET Framework 2.0 版中是新增的。
获取或设置一个对象,该对象可由显示在 WebBrowser 控件中的网页所包含的脚本代码访问。
命名空间:System.Windows.Forms
程序集:System.Windows.Forms(在 system.windows.forms.dll 中)
语法
C#
public Object ObjectForScripting { get; set; }
属性值
可用于脚本代码的对象。
异常
异常类型 | 条件 |
ArgumentException | 设置该属性时指定的值为非公共类型的实例。 - 或 - 设置该属性时指定的值为非 COM 可见的类型的实例。有关更多信息,请参见 Marshal.IsTypeVisibleFromCom。 |
备注
使用该属性启用 WebBrowser 控件承载的网页与包含 WebBrowser 控件的应用程序之间的通信。使用该属性可以将动态 HTML (DHTML) 代码与客户端应用程序代码集成在一起。为该属性指定的对象可作为 window.external 对象(用于主机访问的内置 DOM 对象)用于网页脚本。
可以将此属性设置为希望其公共属性和方法可用于脚本代码的任何 COM 可见的对象。可以通过使用 ComVisibleAttribute 对类进行标记使其成为 COM 可见的类。
若要从客户端应用程序代码调用网页中定义的函数,请使用可从 Document 属性检索的 HtmlDocument 对象的 HtmlDocument.InvokeScript方法。
示例
下面的代码示例演示如何使用 ObjectForScripting 属性。在该示例中,ObjectForScripting 属性被设置为当前窗体。
C#
using System;
using System.Windows.Forms;
using System.Security.Permissions;
[PermissionSet(SecurityAction.Demand, Name="FullTrust")]
[System.Runtime.InteropServices.ComVisibleAttribute(true)]
public class Form1 : Form
{
private WebBrowser webBrowser1 = new WebBrowser();
private Button button1 = new Button();
[STAThread]
public static void Main()
{
Application.EnableVisualStyles();
Application.Run(new Form1());
}
public Form1()
{
button1.Text = "call script code from client code";
button1.Dock = DockStyle.Top;
button1.Click += new EventHandler(button1_Click);
webBrowser1.Dock = DockStyle.Fill;
Controls.Add(webBrowser1);
Controls.Add(button1);
Load += new EventHandler(Form1_Load);
}
private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.AllowWebBrowserDrop = false;
webBrowser1.IsWebBrowserContextMenuEnabled = false;
webBrowser1.WebBrowserShortcutsEnabled = false;
webBrowser1.ObjectForScripting = this;
// Uncomment the following line when you are finished debugging.
//webBrowser1.ScriptErrorsSuppressed = true;
webBrowser1.DocumentText =
"<html><head><script>" +
"function test(message) { alert(message); }" +
"</script></head><body><button " +
"onclick=\"window.external.Test('called from script code')\">" +
"call client code from script code</button>" +
"</body></html>";
}
public void Test(String message)
{
MessageBox.Show(message, "client code");
}
private void button1_Click(object sender, EventArgs e)
{
webBrowser1.Document.InvokeScript("test",
new String[] { "called from client code" });
}
}
注意:
window.external 是外部对象,如你写C# 本地程序放个 webbrowser ,嵌套个网页,
this.webBrowser1.ObjectForScripting = this; 就把当前窗口传递给javascript了
比如窗口中有 个函数叫 Test
public string Test(string jstr) {
//在这里写些操作
}
然后在 html 里面,写 window.external.Test("123");
就传递到,C# 写的本地程序面去了。
龙腾一族至尊龙骑