Webbrowser to ChefSharp Update - vb.net

I'm trying to switch from the normal Webbrowser control (IE) at vb.net to CefSharp (ChromiunWebBrowser).
In the WebBrowser Control (IE), for example, I would have implemented a button click like this
Public Sub SetWebbrowserTagIDClick(ByVal TagName As String, ByVal TagID As String, ByVal Attribute As String, ByVal AttributeValue As String)
Dim ElementListe As HtmlElementCollection = Nothing
ElementListe = Mainform.WebBrowser1.Document.GetElementById(TagID).GetElementsByTagName(TagName)
For Each Element As HtmlElement In ElementListe
If InStr(Element.GetAttribute(Attribute).ToString, AttributeValue) > 0 Then
Element.InvokeMember("Click")
Exit For
End If
Next
End Sub
Is there a way to implement it in cefSharp in the same way or do I always have to go through Javascript?
In the web browser it didn't matter if I only addressed a class name. In cefSharp, isn't it difficult?
Warm greetings from Germany

Related

The WebBrowser control won't work with Proxies from a text file

I'm not that great with visual basic so sorry about that, but I have a basic understanding of java, and a few other programming languages so I'm not completely new.
I want to make a program that connects to a website with a proxy loaded from a text file, but when I debug it, it gives me a bunch of different error messages, like:
HTTP Error 503. The service is unavailable
The webpage cannot be found
etc.
Here is my code for loading in the proxies into a listbox:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
OpenFileDialog1.ShowDialog()
streamer = IO.File.OpenText(OpenFileDialog1.FileName)
Dim mystring() As String = streamer.ReadToEnd.Split(vbNewLine)
ListBox1.Items.AddRange(mystring)
End Sub
Here's the code for using the proxies:
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Button2.Enabled = False
Button1.Enabled = False
For Each item In ListBox1.Items
UseProxy(item.ToString)
Label4.Text = item
WebBrowser1.Navigate(TextBox3.Text)
pause(10000)
Next
End Sub
And here's useproxy:
Private Sub UseProxy(ByVal strProxy As String)
Const INTERNET_OPTION_PROXY As Integer = 38
Const INTERNET_OPEN_TYPE_PROXY As Integer = 3
Dim struct_IPI As Struct_INTERNET_PROXY_INFO
struct_IPI.dwAccessType = INTERNET_OPEN_TYPE_PROXY
struct_IPI.proxy = Marshal.StringToHGlobalAnsi(strProxy)
struct_IPI.proxyBypass = Marshal.StringToHGlobalAnsi("local")
Dim intptrStruct As IntPtr = Marshal.AllocCoTaskMem(Marshal.SizeOf(struct_IPI))
Marshal.StructureToPtr(struct_IPI, intptrStruct, True)
Dim iReturn As Boolean = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_PROXY, intptrStruct, System.Runtime.InteropServices.Marshal.SizeOf(struct_IPI))
End Sub
I also get an error at the end of the button 2 click sub saying this
Actually sometimes when I close the program, I get an error in visual studio on the end of the button2 click sub (Next)
System.InvalidOperationException: 'List that this enumerator is bound to has been modified. An enumerator can only be used if the list does not change.'
I think this is the most straightforward method to change the System Proxy settings on a System-wide basis.
Sometimes, a per-connection setting is preferable. See the linked documents in this case.
Use the Registry class to set the required value in the Internet Settings Subkey:
Software\Microsoft\Windows\CurrentVersion\Internet Settings
Then, perform a System notification of the change, using InternetSetOption with the INTERNET_OPTION_SETTINGS_CHANGED and INTERNET_OPTION_REFRESH Flags:
(These are flags, but should not be combined in this case)
INTERNET_OPTION_REFRESH must also be called if INTERNET_OPTION_PER_CONNECTION_OPTION is used to modify the settings on a per-connection basis.
Declaration of InternetSetOption and a helper function.
Imports Microsoft.Win32
Imports System.Runtime.InteropServices
Imports System.Security.AccessControl
<SecurityCritical>
<DllImport("wininet.dll", SetLastError:=True, CharSet:=CharSet.Auto)>
Friend Shared Function InternetSetOption(hInternet As IntPtr, dwOption As Integer, lpBuffer As IntPtr, dwBufferLength As Integer) As Boolean
End Function
Friend Const INTERNET_OPTION_SETTINGS_CHANGED As Integer = 39
Friend Const INTERNET_OPTION_REFRESH As Integer = 37
<SecuritySafeCritical>
Private Sub InternetSetProxy(ProxyAddress As String, ProxyPort As Integer, UseProxy As Boolean)
Dim keyName As String = "Software\Microsoft\Windows\CurrentVersion\Internet Settings"
Dim KeyValue As Object = ProxyAddress + ":" + ProxyPort.ToString()
Dim InternetSettingsKey As RegistryKey =
Registry.CurrentUser.OpenSubKey(keyName,
RegistryKeyPermissionCheck.ReadWriteSubTree,
RegistryRights.WriteKey)
InternetSettingsKey.SetValue("ProxyServer", KeyValue, RegistryValueKind.String)
InternetSettingsKey.SetValue("ProxyEnable", If(UseProxy, 1, 0), RegistryValueKind.DWord)
InternetSettingsKey.Close()
InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SETTINGS_CHANGED, IntPtr.Zero, 0)
InternetSetOption(IntPtr.Zero, INTERNET_OPTION_REFRESH, IntPtr.Zero, 0)
InternetSettingsKey.Dispose()
End Sub
You can test it with Internet Explorer.
If you are using Fiddler, call the helper method with these parameters to use it as the default system proxy:
InternetSetProxy("127.0.0.1", 8888, True)
To disable the Proxy setting, just set the UseProxy parameter to False:
InternetSetProxy("127.0.0.1", 8888, False)
Navigate an Internet address as usual:
WebBrowser1.Navigate("https://www.google.com")
A note about the .Net WebBrowser control.
The WebBrowser control uses the current cache (as specified in the Internet Explorer settings) to load visited resources as the pre-defined behavior.
If you enable the Proxy but you can still see the (first) page of a Website, this depends on this default behavior.
If you try to click on a link, this new link will not be reachable, and the message:
The proxy server isn’t responding
will be presented.
This kind of result is not constant, it depends on the cache settings.
Edit:
A way to let the WebBrowser control Navigate one or more Internet addresses, using a different Proxy server for each address:
Add an event handler for the WebBrowser DocumentCompleted event.
When the WebBrowser.Navigate() method is first called, the event handler will cycle through the list of Proxies (read from a ListBox control Items list).
This code supposes that the Proxy list is composed of strings that
include both the address and the port of each Proxy. (e.g.
"127.0.0.1:8888" for Fiddler).
Here, as in the OP example, the Internet Address is the same for all Proxies (a parameter of the WaitDocumentsComplete() method), but of course can be read from another List.
Both the DocumentCompleted Handler and the helper method NavigateNextProxy() are marked as Asynchronous, thus the UI is not blocked throughout the whole process.
This process can be stopped at any time, using the WebBrowser.Stop() method, or setting the ProxyIndex field to a negative value.
If the process is interrupted before its natural completion, it's necessary to explicitly remove the Handler, using:
RemoveHandler WebBrowser1.DocumentCompleted, DocumentCompletedHandler
Event Handler declaration and the Wrapper and Helper functions:
Protected Friend DocumentCompletedHandler As WebBrowserDocumentCompletedEventHandler
Private Sub WaitDocumentsComplete(ByVal Address As String, ByVal TimeOutSeconds As Integer)
DocumentCompletedHandler =
Async Sub(s, e)
If WebBrowser1.ReadyState = WebBrowserReadyState.Complete AndAlso ProxyIndex > -1 Then
If (Not WebBrowser1.IsBusy) Then
Dim ProxyParts() As String = ListBox1.GetItemText(ListBox1.Items(ProxyIndex)).Split(":"c)
Await NavigateNextProxy(Address, ProxyParts(0), CInt(ProxyParts(1)), TimeOutSeconds)
ProxyIndex += 1
If ProxyIndex > ProxyIndexMaxValue Then
ProxyIndex = -1
RemoveHandler WebBrowser1.DocumentCompleted, DocumentCompletedHandler
End If
End If
End If
End Sub
AddHandler WebBrowser1.DocumentCompleted, DocumentCompletedHandler
End Sub
Protected Async Function NavigateNextProxy(Address As String, ByVal ProxyAddr As String, ProxyPort As Integer, TimeOutSeconds As Integer) As Task
InternetSetProxy(ProxyAddr, ProxyPort, True)
Await Task.Delay(TimeSpan.FromSeconds(TimeOutSeconds))
If WebBrowser1.IsBusy Then WebBrowser1.Stop()
WebBrowser1.Navigate(Address)
End Function
From a Button.Click() event, set the Indexes of the first and last Proxy in the List, a Timeout value (in seconds) between each navigation, and call the wrapper method WaitDocumentsComplete(), which will initialize the DocumentCompleted event handler.
To begin the process, initialize the WebBrowser control with WebBrowser1.Navigate("")
It's also important to suppress the WebBrowser script error dialog,
otherwise it will compromise the whole procedure.
Private ProxyIndex As Integer = -1
Private ProxyIndexMaxValue As Integer = 0
Private Sub btnForm2_Click(sender As Object, e As EventArgs) Handles btnForm2.Click
ProxyIndex = 0
ProxyIndexMaxValue = ListBox1.Items.Count - 1
Dim BrowsingTimeoutSeconds As Integer = 3
Dim Address As String = "https://www.google.com"
WaitDocumentsComplete(Address, BrowsingTimeoutSeconds)
WebBrowser1.ScriptErrorsSuppressed = True
WebBrowser1.Navigate("")
End Sub

getelement by class name for clicking

I am creating a windows form in VB.NET with web browser control, but not able to click on the below code.
<input type="Submit" class="btn btnSearch bold include_WidthButton" value="Search">
I can click when it is get element by ID, but not by classname. Please help me so much of googling didn't help me.
This is what I tried:
For Each Element As HtmlElement In WebBrowser1.Document.GetElementsByTagName("btn btnSearch bold include_WidthButton")
If Element.OuterHtml.Contains("btn btnSearch bold include_WidthButton") Then
Element.InvokeMember("click")
End If
Exit For
There is no native function to get a collection of elements by class using the webbrowser document. However you can create your own collection using a function and looping through all elements using the document.all property.
Function ElementsByClass(document As HtmlDocument, classname As String)
Dim coll As New Collection
For Each elem As HtmlElement In document.All
If elem.GetAttribute("className").ToLower.Split(" ").Contains(classname.ToLower) Then
coll.Add(elem)
End If
Next
Return coll
End Function
Use would be like this:
Private Sub UpdatBtn_Click(sender As System.Object, e As System.EventArgs) Handles UpdatBtn.Click
For Each elem As HtmlElement In ElementsByClass(WebBrowser1.Document, "form")
elem.SetAttribute("className", elem.GetAttribute("className") & " form-control")
Next
End Sub
I see you are trying to base your collection off the entire className instead of an individual class so you would need to slightly modify.
This is my solution:
Public Sub clickButton(ByVal web As WebBrowser, ByVal tagname As String, ByVal attr As String, ByVal contains As String, ByVal sleep As Integer)
Try
If (web.Document IsNot Nothing) Then
With web.Document
For Each Elem As HtmlElement In .GetElementsByTagName(tagname)
If (Elem.GetAttribute(attr).Contains(contains)) Then
Elem.InvokeMember("Click")
Thread.Sleep(sleep)
Return
End If
Next
End With
End If
Catch ex As Exception
Show_Error(MODULE_NAME, "clickButton")
End Try
End Sub
use:
clickButton(WebBrowser1, "button", "classname", "btn btnSearch bold include_WidthButton", 2000)

How to open dynamic WebBrowser link address in new window form?

I have found the error at href so please help me
Private Sub WebBrowser1_NewWindow(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles WebBrowser1.NewWindow
Dim thiselement As HtmlElement = WebBrowser1.Document.ActiveElement
Dim targeturl As String = thiselement.GetAttribute("href")
e.Cancel = True
Dim window As New Form1
window.Show()
window.WebBrowser1.Navigate(targeturl)
End Sub
at "href" i have found error like Object reference not set to an instant of object.
my code is in vb.net 2010.
WebBrowser1.Document.ActiveElement is returning Nothing because there is no active element. Therefore when you attempt to use targeturl, you get this error: Object reference not set to an instant of object
Handle the Navigating event. Example:
webBrowser1.Navigating += Function(source, args)
Dim uriClicked = args.Uri
' Create your new form or do whatever you want to do here
End Function

VB.NET WebBrowser Control Programmatically Filling Form After Changing User-Agent (Object reference not set to an instance of an object.)

I'm working on a project where I have a WebBrowser control which needs to have a custom user-agent set, then go to Google and fill out the search box, click the search button, then click a link from the search results. Unfortunately I can't use HTTPWebRequest, it has to be done with the WebBrowser control.
Before I added the code to change the user-agent, everything worked fine. Here's the code that I have:
Imports System.Runtime.InteropServices
Public Class Form1
<DllImport("urlmon.dll", CharSet:=CharSet.Ansi)> _
Private Shared Function UrlMkSetSessionOption(dwOption As Integer, pBuffer As String, dwBufferLength As Integer, dwReserved As Integer) As Integer
End Function
Const URLMON_OPTION_USERAGENT As Integer = &H10000001
Public Sub ChangeUserAgent(Agent As String)
UrlMkSetSessionOption(URLMON_OPTION_USERAGENT, Agent, Agent.Length, 0)
End Sub
Private Sub btnGo_Click(sender As Object, e As EventArgs) Handles btnGo.Click
ChangeUserAgent("Fake User-Agent")
wb.Navigate("http://www.google.com", "_self", Nothing, "User-Agent: Fake User-Agent")
End Sub
Private Sub wb_DocumentCompleted(ByVal sender As Object, ByVal e As WebBrowserDocumentCompletedEventArgs) Handles wb.DocumentCompleted
Dim Source As String = wb.Document.Body.OuterHtml
Dim Uri As String = wb.Document.Url.AbsoluteUri
If Uri = "http://www.google.com/" Then
wb.Document.GetElementById("lst-ib").SetAttribute("value", "browser info")
wb.Document.All("btnK").InvokeMember("click")
End If
If Uri.Contains("http://www.google.com/search?") Then
Dim TheDocument = wb.Document.All
For Each curElement As HtmlElement In TheDocument
Dim ctrlIdentity = curElement.GetAttribute("innerText").ToString
If ctrlIdentity = "BROWSER-INFO" Then
curElement.InvokeMember("click")
End If
Next
End If
End Sub
End Class
The problem lies in the following code:
wb.Document.GetElementById("lst-ib").SetAttribute("value", "browser info")
wb.Document.All("btnK").InvokeMember("click")
I thought the problem might be that the page not being fully loaded (frame issue) but I put the offending code in a timer to test, and got the same error. Any help would be much appreciated.
Do you realize .All("btnK") returns a collection? So, you are doing .InvokeMember("click") on a Collection :). You cannot do that, you can only do .InvokeMember("click") on an element for obvious reasons!
Try this:
wb.Document.All("btnK").Item(0).InvokeMember("click")
The .Item(0) returns the first element in the collection returned by .All("btnK"), and since there will only probably be one item returned, since there is only one on the page, you want to do the InvokeMember on the first item, being .Item(0).
May I ask what it is you are developing?
Since you're a new user, please up-vote and/or accept if this answered your question.

Set the focus to a HTML Textbox or Button in a WebBroswer control

I am opening a website in a WebBrowser control using VB.NET 2008. On the fourth page of the website, I want to focus the control by triggering the tab key programmatically. I am using the following code:
If adtxt.Text = "http://aojsl.com/dfassfeed2.php" Then
System.Windows.Forms.SendKeys.Send("{TAB}")
End If
However, my code is unable to trigger the tab key. Does anyone know how to make this work?
Method 1
Private Sub Form_Load()
WebBrowser1.Navigate "http://www.google.com/"
Do
Thread.Sleep(100)
Loop While webBrowser1.IsBusy = True
End Sub
Private Sub Command1_Click()
WebBrowser1.Document.All("q").focus 'Set focus to the search text field
End Sub
Private Sub Command2_Click()
WebBrowser1.Document.All("btnI").focus 'Set focus to the google "I Am feeling lucky button"
End Sub
Method 2
I converted it to VB.Net from this MSDN thread: Focus issues with System.Windows.Controls.WebBrowser
You will need to change the ActiveElement in webBrowser.Document.ActiveElement.Focus() to the textbox or button.
Public Partial Class Form1
Inherits Form
Public Sub New()
InitializeComponent()
Dim host As New WindowsFormsHost()
im webBrowser As New WebBrowser()
host.Child = webBrowser
elementHost1.Child = host
webBrowser.Navigate(New Uri("http://www.google.com"))
Me.Activated += Function() Do
Console.WriteLine(Me.ActiveControl)
If webBrowser.Document <> Nothing Then
If Me.ActiveControl = elementHost1 AndAlso webBrowser.Document.ActiveElement <> Nothing Then
webBrowser.Document.ActiveElement.Focus()
End If
End If
End Function
End Sub
End Class
Method 3
Another way might be to do it in the HTML, eg:
OnLoad="document.myform2.mybutton.focus();">
lets say that the html of youre page is:
<button id="btn">Ok</button><input id="txt">
you can set focus in this way:
If adtxt.Text = "http://aojsl.com/dfassfeed2.php" Then
webbrowser1.document.getelementbyid("btn").focus()
webbrowser1.document.getelementbyid("txt").focus()
End If
Another way:
use the GetElementsByTagName(TagName)
lets say that your html is:
<button>no</button>
<button>no</button>
<button onclick='alert(1);'>--focus me!--</button>
<button>no</button>
Dim Elems As HtmlElementCollection
Dim WebOC As WebBrowser = WebBrowser1
Elems = WebOC.Document.GetElementsByTagName("button")
For Each elem As HtmlElement In Elems
If elem.InnerHtml = "--focus me!--" Then
elem.Focus()
elem.InvokeMember("click")
End If
Next
another one:
Dim num As Integer = 1
Dim elms As HtmlElementCollection
Dim wb As WebBrowser = WebBrowser1
elms = wb.Document.GetElementsByTagName("button")
For Each elem As HtmlElement In elms
If elem.Id = "" Then
elem.Id = "button" & num.ToString
num = num + 1
End If
Next
WebBrowser1.Document.GetElementById("button3").Focus()
To focus the select element by using the focus function in vb.net. For exsample,
Me.WebBrowser1.Document.All.Item("password").Focus()
This will put the focus on the element called password!
Use Me.WebBrowser1.Document.All.Item("YOURelement") to find the correct element and then add .Focus() to focus on the one you want! :D
Do this Me.WebBrowser1.Document.All.Item(textbox1.text).Focus()
make a Textbox and then if you want to Spambot it easy Detects everytime your Typ you Write and Send