WPF WebBrowser navigate to website via url and escape script error warning

Copy from https://www.iditect.com/faq/csharp/wpf-webbrowser-control--how-to-suppress-script-errors.html#:~:text=To%20suppress%20these%20script%20errors%2C%20you%20can%20handle,using%20the%20Cancel%20property%20of%20the%20WebBrowserNavigatingEventArgs%20parameter.

 

 

 

 

 

 

 

 

 

 

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 WpfApp207
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.Loaded += MainWindow_Loaded;
            webBrowser.Navigating += WebBrowser_Navigating;
        }

        private void WebBrowser_Navigating(object sender, NavigatingCancelEventArgs e)
        {
            var webBrowser = (WebBrowser)sender;
            webBrowser.Navigating -= WebBrowser_Navigating; // Unsubscribe temporarily to avoid recursion

            try
            {
                // Execute JavaScript to suppress script errors
                dynamic activeX = webBrowser.GetType().InvokeMember("ActiveXInstance",
                    System.Reflection.BindingFlags.GetProperty | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic,
                    null, webBrowser, new object[] { });

                activeX.Silent = true;
            }
            catch (Exception ex)
            {
                // Handle any exception that may occur while trying to suppress script errors
                // Optionally, log the error for debugging purposes
                System.Diagnostics.Debug.WriteLine("Error suppressing script errors: " + ex.Message);
            }
            finally
            {
                webBrowser.Navigating += WebBrowser_Navigating; // Re-subscribe to the event
            }
        }

        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            string url = "https://www.spacex.com/vehicles/starship/";
            webBrowser.Navigate(url); 
        }
    }
}

 

posted @ 2024-07-12 12:16  FredGrit  阅读(4)  评论(0编辑  收藏  举报