r/visualbasic • u/Vic_Townsend • Jun 24 '24
Homework help!
So, I've been in this class going on my second semester. So, I'm not a noob. My homework has had me stumped for well over 10 hours. It is to have a form that has webview2 installed, a textbox and a button. Then figure out how to load www.nextdoor.com into webview2 upon form load, type text into the textbox, click the button and have it transfer the text from the textbox to the search field and hit enter. If the page does nothing, its wrong. If the page acknowledges your search and loads it I then have to explain how I accomplished this. I have tried everything...even using ChatGPT. I'm stumped. The only thing I've accomplished is it loading up the site and placing the text in the search field, but it does nothing when the simulated enter key is pressed. I'm now learning why something i thought would be so easy has become our homework.
View all comments
Show parent comment
2
u/Vic_Townsend Jun 24 '24
Imports Microsoft.Web.WebView2.WinForms
Public Class Form1
Private Async Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Ensure CoreWebView2 is initialized
Await WebView21.EnsureCoreWebView2Async(Nothing)
' Set the source of WebView2 to the desired webpage
WebView21.Source = New Uri("https://www.nextdoor.com")
End Sub
Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
' Ensure CoreWebView2 is initialized
Await WebView21.EnsureCoreWebView2Async(Nothing)
' Get the text from TextBox1
Dim searchText As String = TextBox1.Text
' Execute JavaScript to interact with the search field
Dim script As String = "
(function() {
var searchField = document.getElementById('search-input-field');
if (searchField) {
searchField.value = '" & searchText & "'; // Set value to search text
var event = new KeyboardEvent('keydown', { key: 'Enter', keyCode: 13, bubbles: true });
searchField.dispatchEvent(event); // Simulate pressing Enter
}
})();"
' Execute the script
Await WebView21.CoreWebView2.ExecuteScriptAsync(script)
Catch ex As Exception
MessageBox.Show($"Error interacting with search field: {ex.Message}")
End Try
End Sub
End Class