2016-11-12 31 views
0

我已將Web瀏覽器放在我的表單上。我的問題是我如何防止瀏覽器離開域。阻止域名更改@Visual基本Web瀏覽器

例如:google.com已打開。瀏覽器可以重定向到google.com的任何頁面,如google.com/index,但不能離開google.com

回答

0

以下代碼將檢測瀏覽器是否離開域,然後返回到上一頁。

Public Class Form1 
    Private Sub WebBrowser1_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted 
     On Error Resume Next 
     If WebBrowser1.Url.ToString.Substring(0, Len("https://www.google.com")) <> "https://www.google.com" Or Len(WebBrowser1.Url.ToString) <> Len("https://www.google.com") Then 
      WebBrowser1.GoBack() 
     End If 
    End Sub 

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load 
     WebBrowser1.Navigate("https://www.google.com") 
    End Sub 
End Class 
+0

此代碼檢測瀏覽器*是否已經離開域。這並不理想。最好不要讓新頁面加載,而是完全阻止導航到新頁面。請參閱[這個答案](http://stackoverflow.com/a/40563452/240733)的建議如何做到這一點。 – stakx

2

看看在WebBrowser.Navigating event

「的WebBrowser控制導航到一個新的文檔之前發生。」

「您可以處理Navigating事件取消導航[...]。要取消導航,設置傳遞給事件處理程序trueWebBrowserNavigatingEventArgs對象的Cancel性能。您還可以使用這個對象來獲取URL通過WebBrowserNavigatingEventArgs.Url財產的新文件。「

MSDN reference page

所以,你應該能夠訂閱您WebBrowserNavigating事件和處理程序中,檢查事件參數對象ee.Url財產。如果是指另一個域,設置e.CancelTrue中止導航:

AddHandler webBrowser.Navigating, AddressOf EnsureWebBrowserStaysInMyDomain 
'^Note that subscribing a handler method to the `Navigating` event 
' can also be done directly from the Forms Designer, if you prefer. 

… 

Sub EnsureWebBrowserStaysInMyDomain(sender As Object, e As WebBrowserNavigatingEventArgs) 
    If e.Url.Host <> "example.com" Then 
     e.Cancel = True 
     MessageBox.Show(icon:=MessageBoxIcon.Exclamation, 
         text:="You can never leave!", 
         caption:="Hotel California", 
         buttons:=MessageBoxButtons.RetryCancel) ' ;-) 
    End If 
End Sub 

NavigatingNavigated事件是您在Windows窗體中看到往往一個模式的一個例子:一個名爲…ing事件之前事情發生即將發生的;這些讓你有機會放棄這個過程。名爲…ed的事件僅在此後發生。

還要注意,Navigating事件僅針對用戶交互觸發。訪問的網頁可能仍包含來自其他域的圖像,並且運行腳本仍可將HTTP請求發送到其他域。