[英]C# WebBrowser control: window.external access sub object
when assigning an object to the ObjectForScripting
property of a WebBrowser control the methods of this object can be called by JavaScript by using windows.external.[method_name]
. 将对象分配给WebBrowser控件的ObjectForScripting
属性时,JavaScript可以使用windows.external.[method_name]
调用此对象的方法windows.external.[method_name]
。 This works without problems. 这没有问题。
But how I need to design this C# object when I have a JavaScript function like this (accessing a sub object): window.external.app.testfunction();
但是当我有这样的JavaScript函数(访问子对象)时,我需要如何设计这个C#对象: window.external.app.testfunction();
I tested it with following C# object assigned to the ObjectForScripting
property: 我使用分配给ObjectForScripting
属性的以下C#对象测试了它:
[ComVisible(true)]
public class TestObject
{
public App app = new App();
}
public class App
{
public void testfunction()
{
}
}
But this unfortunately does not work and leads to a JavaScript error saying "function expected". 但不幸的是,这不起作用,导致JavaScript错误说“功能预期”。
Any idea on how the C# object has to look like that this JavaScript command is working? 关于C#对象如何看起来像这个JavaScript命令工作的任何想法?
Thank you for any tips on that 感谢您的任何提示
Andreas 安德烈亚斯
I suggest you use InterfaceIsIDispatch
-based interfaces to expose the object model from C# to 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()");
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.