2016-11-12 32 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请求发送到其他域。