Search code examples
javascriptvb.netwebbrowser-controlonbeforeunload

WebBrowser Control prevent Next Url navigated


I wonder if there is a anyway to remove the WebBrowser Message

are you sure you want to navigate away from this page

When I try to navigate another url, it happens.

Erro picture

I tried this methods

e.Cancel = False

WebBrowser1.Dispose()

WebBrowser1 = New WebBrowser

WebBrowser1.ScriptErrorsSuppressed = True

WebBrowser1.Navigate(New Uri("https://www.google.com"))

Solution

  • That is coded into the website, so you'd have to inject some Javascript into the page to override the prompt.

    Be careful with this, though. This requires overriding the entire window.onbeforeunload event handler, and some pages might have decided to do more than just display a prompt (perhaps save data or something similar).

    To start with add a reference to mshtml, this is required to be able to set the contents of a script element (credit to Atanas Korchev):

    1. Right-click your project in the Solution Explorer and press Add Reference....

    2. Select the Browse tab and navigate to C:\Windows\System32

    3. Select mshtml.tlb and press OK.

    4. In the Solution Explorer, expand the References node. If you can't expand it or if it doesn't exist, press the Show All Files button in the top of the Solution Explorer.

    5. Select the mshtml reference, go to the Property Window and make sure Embed Interop Types is set to True.

    Now you can use this code:

    Private Sub RemoveOnBeforeUnloadPrompt()
        If WebBrowser1.Document IsNot Nothing AndAlso WebBrowser1.Document.Body IsNot Nothing Then
            'Create a <script> tag.
            Dim ScriptElement As HtmlElement = WebBrowser1.Document.CreateElement("script")
            ScriptElement.SetAttribute("type", "text/javascript")
    
            'Insert code to override the window.onbeforeunload event handler.
            CType(ScriptElement.DomElement, mshtml.IHTMLScriptElement).text = "function __removeOnBeforeUnload() { window.onbeforeunload = function() {}; }"
    
            'Append script to the web page.
            WebBrowser1.Document.Body.AppendChild(ScriptElement)
    
            'Run the script.
            WebBrowser1.Document.InvokeScript("__removeOnBeforeUnload")
        End If
    End Sub
    

    Then, before you navigate to a new page call:

    RemoveOnBeforeUnloadPrompt()