C# WebBrowser control: window.external access sub object

后端 未结 1 1369
被撕碎了的回忆
被撕碎了的回忆 2020-12-11 07:24

when assigning an object to the ObjectForScripting property of a WebBrowser control the methods of this object can be called by JavaScript by using window

相关标签:
1条回答
  • 2020-12-11 08:10

    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()");
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题