C#WebBrowser控件:window.external访问子对象
作者:互联网
将对象分配给WebBrowser控件的ObjectForScripting属性时,JavaScript可以使用windows.external.[method_name]调用此对象的方法.这没有问题.
但是,当我有这样的JavaScript函数(访问子对象)时,如何设计C#对象:window.external.app.testfunction();
我使用分配给ObjectForScripting属性的以下C#对象对其进行了测试:
[ComVisible(true)]
public class TestObject
{
public App app = new App();
}
public class App
{
public void testfunction()
{
}
}
但是,不幸的是,这不起作用,并导致JavaScript错误显示“期望功能”.
关于C#对象必须看起来像该JavaScript命令有效的任何想法?
谢谢你的提示
安德烈亚斯
解决方法:
我建议您使用基于InterfaceIsIDispatch的接口将对象模型从C#公开给JavaScript:
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace WindowsFormsApplication
{
[ComVisible(true)]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface IApp
{
void testFunction();
}
[ComVisible(true)]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface ITestObject
{
IApp App { get; }
}
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(ITestObject))]
public class TestObject: ITestObject
{
readonly App _app = new App();
public IApp App
{
get { return _app; }
}
}
[ComVisible(true)]
public class App : IApp
{
public void testFunction()
{
MessageBox.Show("Hello!");
}
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.webBrowser1.ObjectForScripting = new TestObject();
this.webBrowser1.DocumentCompleted += webBrowser1_DocumentCompleted;
this.webBrowser1.Navigate("about:blank");
}
void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
this.webBrowser1.Navigate("javascript:external.App.testFunction()");
}
}
}
标签:webbrowser-control,javascript,c,window-external 来源: https://codeday.me/bug/20191121/2054403.html