首页 > 解决方案 > How to call client code from javascript in WebBrowser on WPF?

问题描述

I am trying to call WPF client code from WebBrowser control as given in the example https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.webbrowser.objectforscripting?redirectedfrom=MSDN&view=netframework-4.8#System_Windows_Forms_WebBrowser_ObjectForScripting. The example provided in the link is for Windows forms. I am trying to do similar thing in WPF. However, I am getting following error.

Managed Debugging Assistant 'NonComVisibleBaseClass' : 'A QueryInterface call was made requesting the default IDispatch interface of COM visible managed class 'WpfApp2.MainWindow'. However since this class does not have an explicit default interface and derives from non COM visible class 'System.Windows.Window', the QueryInterface call will fail. This is done to prevent the non COM visible base class from being constrained by the COM versioning rules.'

Is there any way to resolve this? or it just cannot be done in WebBrowser-control and WPF ?

标签: wpfwebbrowser-control

解决方案


我们需要创建一个单独的类并将其用于脚本

using System.Windows;
using System.Security.Permissions;
using System.Windows.Controls;
using System;

namespace WpfApp2
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>

    public partial class MainWindow : Window
    {
        [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
        [System.Runtime.InteropServices.ComVisibleAttribute(true)]
        public class ObjectForScriptingHelper
        {
            public void Test()
            {
                MessageBox.Show("xxxxx");
            }
        }
        public MainWindow()
        {
            InitializeComponent();
            button1.Content  = "call script code from client code";
        }

        private void Form1_Load(object sender, EventArgs e)
        {
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {

            //webBrowser1.AllowWebBrowserDrop = false;
            //webBrowser1.IsWebBrowserContextMenuEnabled = false;
            //webBrowser1.WebBrowserShortcutsEnabled = false;
            webBrowser1.ObjectForScripting = new ObjectForScriptingHelper();

        // Uncomment the following line when you are finished debugging.
        //webBrowser1.ScriptErrorsSuppressed = true;

        webBrowser1.Navigate(@"C:\temp\WpfApp2\WpfApp2\HTMLPage1.html");


        }

        private void Button1_Click_1(object sender, RoutedEventArgs e)
        {

            webBrowser1.InvokeScript("test",
                new String[] { "called from client code" });

        }
    }
}

推荐阅读