先上码:
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace localindex
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private WebBrowser webBrowser1;
private void Form1_Load(object sender, EventArgs e)
{
webBrowser1 = new WebBrowser();
webBrowser1.Dock = DockStyle.Fill;
this.Controls.Add(webBrowser1);
webBrowser1.AllowWebBrowserDrop = false;
webBrowser1.IsWebBrowserContextMenuEnabled = false;
webBrowser1.WebBrowserShortcutsEnabled = false;
webBrowser1.ObjectForScripting = new ScriptEvent();
webBrowser1.ScriptErrorsSuppressed = true; //出错的情况下,是否禁用脚本调试提示框
webBrowser1.DocumentText =
"<html><head><script>" +
"function test(message) { alert(message); }" +
"</script></head><body><button " +
"οnclick=\"window.external.Test1('called from script code')\">" +
"call client code from script code</button>" +
"</body></html>";
}
[ComVisible(true)]
public class ScriptEvent
{
public void Test(string message)
{
MessageBox.Show(message, "啊啊啊啊啊");
}
}
}
}
这里说一下
webBrowser1.ScriptErrorsSuppressed = true;
如果设置成false,假如脚本对象找不到,后者执行出错,那么会弹出提示框,比如把Test函数改成Test1,:
另外,需要注意,注册脚本ScriptEvent,需要com交互可见性处理
ComVisible(true)