C#WebBrowser控件:访问的window.external对象子 [英] C# WebBrowser control: window.external access sub object
问题描述
。 [METHOD_NAME] 。这工作没有问题。
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]
. This works without problems.
不过,我需要怎样时,我有这样的JavaScript函数(访问子对象)来设计这个C#对象: window.external.app.testfunction();
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();
我与分配给下面的C#对象,对其进行了测试 ObjectForScripting
属性:
I tested it with following C# object assigned to the ObjectForScripting
property:
[ComVisible(true)]
public class TestObject
{
public App app = new App();
}
public class App
{
public void testfunction()
{
}
}
但这遗憾的是不工作,导致一个JavaScript错误说的功能预期。
But this unfortunately does not work and leads to a JavaScript error saying "function expected".
C#的对象如何有看起来像这样的JavaScript命令工作?
Any idea on how the C# object has to look like that this JavaScript command is working?
感谢您对任何提示的任何想法。
Thank you for any tips on that
安德烈亚斯
推荐答案
我建议你使用 InterfaceIsIDispatch
基于接口从C#的对象模型公开给JavaScript:
I suggest you use InterfaceIsIDispatch
-based interfaces to expose the object model from C# to 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()");
}
}
}
这篇关于C#WebBrowser控件:访问的window.external对象子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!