wpf webbrowser注入javascript

            HTMLDocument dom = (HTMLDocument)web.Document;

           // web.InvokeScript("window.οnlοad=function(){alert('hello')}");

            dom.parentWindow.execScript("window.onload = function () { window.external.WebClick(this); }"); //向页面注入javascript语句

其中window.external.WebClick(this)实现网页javascript调用后台代码

    [ComVisible(true)]
    public class HtmlBridge
    {
        
        public void WebClick(object source)
        {
            HTMLWindow2 htmlWindow = (HTMLWindow2)source;
            //MessageBox.Show("Received: " + source);
            foreach (IHTMLElement archor in htmlWindow.document.links)
            {
                archor.setAttribute("target", "_self");
            }

            //将所有的FORM的提交目标,指向本窗体
            foreach (IHTMLElement form in htmlWindow.document.forms)
            {
                form.setAttribute("target", "_self");
            }
        }
    }


关联过程

web.ObjectForScripting = new HtmlBridge();


其中web为webbrowser实例


WPF(Windows Presentation Foundation)中的WebBrowser控件允许开发者在WPF应用程序中嵌入网页浏览器功能。以下是使用WebBrowser控件的基本步骤: 1. 在你的WPF项目中引入WebBrowser控件。首先确保你的项目已经添加了System.Windows.Forms和Microsoft.WebBrowser的引用。这可以通过右键点击你的项目名称,选择“添加引用”->“程序集”->“框架”中找到并添加。 2. 在XAML中添加WebBrowser控件。你可以在XAML文件中添加WebBrowser控件的声明,如下所示: ```xml <Window x:Class="YourNamespace.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:web="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms" Title="MainWindow" Height="350" Width="525"> <Grid> <web:WebBrowser x:Name="webBrowserControl" /> </Grid> </Window> ``` 3. 在代码后置文件中加载网页。在C#代码中,你可以使用WebBrowser控件的`Navigate`方法来加载特定的URL: ```csharp public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); webBrowserControl.Navigate(new Uri("http://www.example.com")); } } ``` 在这个例子中,`webBrowserControl`是你在XAML中定义的WebBrowser控件的名称,`http://www.example.com`是你希望加载的网页地址。 4. 设置导航事件处理。如果需要处理网页加载的不同阶段,可以添加事件处理程序: ```csharp webBrowserControl.Navigating += new WebBrowserNavigatingEventHandler(WebBrowserControl_Navigating); webBrowserControl.Navigated += new WebBrowserNavigatedEventHandler(WebBrowserControl_Navigated); private void WebBrowserControl_Navigating(object sender, WebBrowserNavigatingEventArgs e) { // 在网页开始加载之前可以执行的操作 } private void WebBrowserControl_Navigated(object sender, WebBrowserNavigatedEventArgs e) { // 在网页加载完成后可以执行的操作 } ``` 5. 运行你的应用程序。编译并运行你的WPF应用程序,你应该能够看到WebBrowser控件加载了指定的网页。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值