WPF WebBrowser suppress script errors

Script Error,An error has occured in the script on this page. Do you want to continue running scripts on this page?

 

 

 

//xaml
<Window x:Class="WpfApp378.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp378"
        mc:Ignorable="d" WindowState="Maximized"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <WebBrowser Source="http://www.tencent.com" x:Name="webBrowser" />
    </Grid>
</Window>



//cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApp378
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            SuppressScriptErrors(webBrowser, true);
        }

        void SuppressScriptErrors(WebBrowser browser, bool hide)
        {
            browser.Navigating += (s, e) =>
            {
                var fiComWebBrowser = typeof(WebBrowser).GetField("_axIWebBrowser2",
                    System.Reflection.BindingFlags.Instance |
                    System.Reflection.BindingFlags.NonPublic);
                if (fiComWebBrowser == null)
                {
                    return;
                }

                object objComBrowser = fiComWebBrowser.GetValue(browser);
                if (objComBrowser == null)
                {
                    return;
                }
                objComBrowser.GetType().InvokeMember("Silent",
                    System.Reflection.BindingFlags.SetProperty,
                    null,
                    objComBrowser, new object[] { hide });
            };
        }
    }
}

 

 

 

 

 

 

 

 

 

 

Copy solution from 

https://blog.csdn.net/weixin_33965305/article/details/86170436?spm=1001.2101.3001.6650.3&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7ERate-3-86170436-blog-106261340.235%5Ev43%5Epc_blog_bottom_relevance_base5&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7ERate-3-86170436-blog-106261340.235%5Ev43%5Epc_blog_bottom_relevance_base5&utm_relevant_index=6

posted @ 2024-09-18 18:29  FredGrit  阅读(8)  评论(0编辑  收藏  举报