Search code examples
javascriptvb.netvisual-studiogetelementbyidcefsharp

Cefsharp webbrowser send input


I want to be able to simulate a click or keyboard input to a web element in my cefsharp (chromium) webbrowser.

Lets say I want to type "stack overflow," for instance, into the google searchbox. I want to be able to simulate that keyboard input into the google search box web element so that the search box says "stack overflow" and it would act as if a human typed "stack overflow."

Research: I have found out ways to do this (untested) in the visual studio web element, but not chromium. For reference, the code I found is browser.Document.GetElementById('web element').InvokeMember("Click") however, I do not know if or how this works.

I have also found the ExecuteScriptAsync function, but I am not sure how to use it. I am pretty sure I need to use executescriptasync, but I am not sure what parameters I would use.

My Setup: I am using visual basic, visual studio, and the cefsharp chromium-based web browser

The Question: To reiterate, I would like to be able to simulate keypresses and mouse clicks on certain web elements in a cefsharp browser.


Solution

  • This is not my answer: I copied it from @shudel, so thank you @shudel However, I wanted to make sure that this question got answered.

    Using ExecuteScriptAsync will execute JavaScript against the Chrome engine, so you would have to send valid JavaScript to this function. The following code shows how you could start a search using DuckDuckGo

    Imports System.Threading
    Imports CefSharp
    Imports CefSharp.WinForms
    
    Public Class Form1
      Private _browser As New ChromiumWebBrowser()
    
    
      Sub New()
        ' This call is required by the designer.
        InitializeComponent()
    
        ' Add any initialization after the InitializeComponent() call.
    _browser.Top = 10
    _browser.Left = 10
    _browser.Width = 600
    _browser.Height = 400
    Controls.Add(_browser)
      End Sub
    
    
      Private Sub Button1_Click(sender As Object, e As EventArgs) Handles 
    Button1.Click
        _browser.Load("https://duckduckgo.com/")
    'for simplicity just wait until page is downloaded, should be handled by LoadingStateChanged
    Thread.Sleep(3000)
        Dim jsScript As String = <js><![CDATA[
        document.all("q").value = "stack overflow";
        document.all("search_button_homepage").click();
                             ]]></js>.Value
    _browser.ExecuteScriptAsync(jsScript)
      End Sub
    
    
    End Class`