Search code examples
dotnetbrowser

DotNetBrowser DOM Events


Please help me Here My Code But Not Work

//using DotNetBrowser
{
            document = browser.GetDocument();
            DOMInputElement txtsearch = (DOMInputElement)document.GetElementByClassName("ts1222");
            txtsearch .Value = "book";         
            txtsearch .DispatchEvent(browser.CreateEvent("change"));
}

In this code, the value is placed in the search box, but the search method does not recognize it and nothing is searched. In fact, it is as if no value has been entered.


Solution

  • Why this happens

    It's not clear whether your page uses any JavaScript frameworks. But I will assume that it does.

    In my practice, a very similar behavior was the case with some old Angular versions.

    In these frameworks, an input element can be bound to a JavaScript data model (e.g., ng-model in Angular). When one of them changes, the library automatically synchronizes the data between the input and the model.

    But how does the framework detect the change? Such frameworks are designed for human interaction, not for automation. Therefore, the "change" event alone was never enough.

    Simulate DOM events

    The obvious (but complex) approach is to learn how the JS framework detects a change. And when you have the exact sequence of DOM events it expects, you can generate them artificially. It will work, but remember that it relies on internal logic, which can change anytime.

    Simulate input

    Instead, it's easier to simulate the whole input. Simulating input is a standard feature in libraries of that kind: see SendKeyEvent in CefSharp.

    Judging by your code, you're using DotNetBrowser 1.x. So here's how it's done (taken from this example):

    // Type 'Hello' text in the focused text field.
    KeyParams params = new KeyParams(VirtualKeyCode.VK_H, 'H');
    browser.KeyDown(params);
    browser.KeyUp(params);
    

    In this code snippet, the letter 'H' is perceived by Chromium as real human typing. Therefore, it will generate all the necessary events and JS library will recognize it.

    This version, however, is stuck with Chromium 69, which may cause trouble with the new JS frameworks and browsing the web in general. Consider using one of the 2.x versions; this API is almost unchanged: guide.

    Copy and paste

    Another approach would be to use the clipboard. Simply put your text into the clipboard, and then paste it in the browser.

    browser.ExecuteCommand(EditorCommand.PASTE);