wpf - 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 ?
解决方案
我们需要创建一个单独的类并将其用于脚本
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" });
}
}
}
推荐阅读
- javascript - 如何使用 js2xmlparser 添加处理字符串
- oracle - 将带有 ODP.NET Core 的 Oracle Schema 脚手架到辅助项目中会在主项目中创建蓝色箭头“链接”文件
- amazon-web-services - 如何让 docker-machine 与堡垒和私有子网 EC2 一起工作?
- javascript - 在 REACT 中创建一个将 props 传递给组件的方法
- influxdb - 如何在滚动窗口上“检查”(警告)InfluxDB 2.0 中的聚合?
- jquery - Slick.js 没有正确初始化
- taocp - 什么是“gigamem”?
- list - 如何使用地图构建列表?
- select - 根据spss中的前几个字符选择案例?
- device - 安装 NMAP 后:dnet: 无法打开设备 eth0?