WPF 中的 WebBrowser 仍在新 window 中打开 link

WebBrowser in WPF still opening link in new window

我想创建 "In-Browser" 导航,只要单击 link 就会弹出一个新的 window (IE),我希望它取消并在我的浏览器上导航反而。我搜索并遵循了一些指南,但我无法阻止 window 在其浏览器上导航。以下是我正在做的事情:-

Link example.

XAML:-

<WebBrowser Name="HostWeb" Navigating="HostWeb_Navigating" LoadCompleted="HostWeb_LoadCompleted" DockPanel.Dock="Top"/>

CS:-

using mshtml;
    public partial class MainWindow : Window
    {
        Guid SID_SWebBrowserApp = new Guid("0002DF05-0000-0000-C000-000000000046");
        public MainWindow()
        {
            InitializeComponent();
            HostWeb.Navigate("https://www.booking.com");
        }

    private void HostWeb_Navigating(object sender, NavigatingCancelEventArgs e)
    {
        Task.Factory.StartNew(() =>
        {
            Dispatcher.BeginInvoke(new Action(() =>
            {
                ProgressGrid.Visibility = Visibility.Visible;
                if (e.Uri.OriginalString == "https://www.booking.com/content/terms.html")
                {
                    // Cancel navigation of this URL. This will be load into Generic List to find with LINQ
                    e.Cancel = true;
                }
                else
                {
                    NavigatedURI = e.Uri.OriginalString;
                }
            }), DispatcherPriority.Background);
        });
    }
    private void HostWeb_LoadCompleted(object sender, NavigationEventArgs e)
    {

        Task.Factory.StartNew(() =>
        {
            ProgressGrid.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => { ProgressGrid.Visibility = Visibility.Hidden; }));

            IServiceProvider serviceProvider = (IServiceProvider)HostWeb.Document;
            Guid serviceGuid = SID_SWebBrowserApp;
            Guid iid = typeof(SHDocVw.IWebBrowser2).GUID;
            SHDocVw.IWebBrowser2 myWebBrowser2 = (SHDocVw.IWebBrowser2)serviceProvider.QueryService(ref serviceGuid, ref iid);
            SHDocVw.DWebBrowserEvents_Event wbEvents = (SHDocVw.DWebBrowserEvents_Event)myWebBrowser2;
            wbEvents.NewWindow += new SHDocVw.DWebBrowserEvents_NewWindowEventHandler(OnWebBrowserNewWindow);
        });
    }

    void OnWebBrowserNewWindow(string URL, int Flags, string TargetFrameName, ref object PostData, string Headers, ref bool Processed)
    {
        Processed = true;
        HostWeb.Navigate(URL);
    }

    private void BrowseBack_CanExecute(object sender, CanExecuteRoutedEventArgs e)
    {
        e.CanExecute = ((HostWeb != null) && (HostWeb.CanGoBack));
    }
    private void BrowseBack_Executed(object sender, ExecutedRoutedEventArgs e)
    {
        HostWeb.GoBack();
    }
    private void BrowseForward_CanExecute(object sender, CanExecuteRoutedEventArgs e)
    {
        e.CanExecute = ((HostWeb != null) && (HostWeb.CanGoForward));
    }
    private void BrowseForward_Executed(object sender, ExecutedRoutedEventArgs e)
    {
        HostWeb.GoForward();
    }
    private void GoToHome_Click(object sender, RoutedEventArgs e)
    {
        HostWeb.Navigate("https://www.booking.com");
    }
}
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("6d5140c1-7436-11ce-8034-00aa006009fa")]
internal interface IServiceProvider
{
   [return: MarshalAs(UnmanagedType.IUnknown)]
   object QueryService(ref Guid guidService, ref Guid riid);
}

第二种方法是我无法完成它,因为HostWeb.ActiveXInstance;在 SHDocVw 上不存在:-

Link example.

using SHDocVw;

public MainWindow()
{
    InitializeComponent();
    WebBrowser_V1 axBrowser = (WebBrowser_V1)HostWeb.ActiveXInstance;
    axBrowser.NewWindow += AxBrowser_NewWindow;
    HostWeb.Navigate("https://www.booking.com");
}

private void HostWeb_LoadCompleted(object sender, NavigationEventArgs e)
{

    Task.Factory.StartNew(() =>
    {
        ProgressGrid.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => { ProgressGrid.Visibility = Visibility.Hidden; }));

        HTMLDocument htmlDoc = (HTMLDocument)HostWeb.Document;
        IHTMLElementCollection htmlElementCollection = htmlDoc.getElementsByTagName("A");

        //Set All Anchore Target As _self For Stop Opening New Window......
        foreach (IHTMLElement curElement in htmlElementCollection)
        {
            string targetAtt = curElement.getAttribute("target");
            if (targetAtt == "_blank" || targetAtt == "_top" || targetAtt == "_parent" || targetAtt == "Array")
            {
                curElement.removeAttribute("target");
                curElement.setAttribute("target", "_self");
            }
        }
    });
}
void AxBrowser_NewWindow(string URL, int Flags, string TargetFrameName, ref object PostData, string Headers, ref bool Processed)
{
    // cancel the PopUp event  
    Processed = true;
    // send the popup URL to the WebBrowser control  
    HostWeb.Navigate(URL);
}

给出 Booking.com 网络示例,如何防止打开新标签/新 window 在它弹出 并通过当前浏览器导航之前(在当前页面打开新的 tab/window)?

附加: 鉴于 booking.com 页面有 4 个主菜单 [住宿、航班、租车、机场出租车],当点击任何一个时,它将弹出并且不会触发 HostWeb_Navigating 事件。

请参考this TechNet article

您添加对 COM->Microsoft Internet 控件的引用并处理 LoadCompleted 事件:

static readonly Guid SID_SWebBrowserApp = new Guid("0002DF05-0000-0000-C000-000000000046");

[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("6d5140c1-7436-11ce-8034-00aa006009fa")]
internal interface IServiceProvider
{
    [return: MarshalAs(UnmanagedType.IUnknown)]
    object QueryService(ref Guid guidService, ref Guid riid);
}

private void WebBrowser_LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
    IServiceProvider serviceProvider = (IServiceProvider)webBrowser.Document;
    Guid serviceGuid = SID_SWebBrowserApp;
    Guid iid = typeof(SHDocVw.IWebBrowser2).GUID;
    SHDocVw.IWebBrowser2 myWebBrowser2 = (SHDocVw.IWebBrowser2)serviceProvider.QueryService(ref serviceGuid, ref iid);
    SHDocVw.DWebBrowserEvents_Event wbEvents = (SHDocVw.DWebBrowserEvents_Event)myWebBrowser2;
    wbEvents.NewWindow += new SHDocVw.DWebBrowserEvents_NewWindowEventHandler(OnWebBrowserNewWindow);
}

private void OnWebBrowserNewWindow(string URL, int Flags, string TargetFrameName, ref object PostData, string Headers,
    ref bool Processed)
{
    Processed = true;
    webBrowser.Navigate(URL);
}

XAML:

<WebBrowser x:Name="webBrowser" Source="http://booking.com" LoadCompleted="WebBrowser_LoadCompleted" />