Form中程序和其webBrower页面中的JavaScript方法相互调用的实现

首先引用命名空间:using System.Security.Permissions;
要加上这两行
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
[System.Runtime.InteropServices.ComVisibleAttribute(true)]
服务器调用js函数:webBrowser1.Document.InvokeScript("functionname", new string[] {'param1','param2'});

js调用服务器函数:window.external.functionname(param);

test.html中的javascript

<script language="javascript" type="text/javascript">
function add(){
alert(window.external.add(4,5));
}
function test(param){
alert(param);
}
</script>

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Threading;
using System.Security.Permissions; 

namespace ShowLanPage
{
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")] [System.Runtime.InteropServices.ComVisibleAttribute(true)]
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.webBrowser1.Url = new System.Uri("http://localhost/test.html", System.UriKind.Absolute);
webBrowser1.ObjectForScripting =this;
}
private void button1_Click(object sender, EventArgs e)
{
this.webBrowser1.Document.InvokeScript("test", new string[] { "HelloWorld" });
}
public int add(int a, int b) 
{
  return a + b;
}
}
}

你可能感兴趣的:(Form中程序和其webBrower页面中的JavaScript方法相互调用的实现)