CefSharp webpage element click

Andrew picture Andrew · Aug 4, 2018 · Viewed 11.6k times · Source

I'm trying to do simple click on some page element(like a btn or link).

I have wrote 2 functions for clicking via xpath and via CSS selectors.

Both of those functions perfectly works in browser's developer console, but partially does'nt work in CEF.

  • code perfectly click's in simple links from Developer Console and from Cef
  • code perfectly click's on exact button from Developer Console but doesn't do click from CEF. It's just ignore it for some reason...

How can this be? Js code is absolutely the same!...

    public void Click(string xpath)
    {
        var js = "document.evaluate(\"" + xpath + "\", document, null, XPathResult.ANY_TYPE, null).iterateNext().click();";

        EvaluateJavascript(js);
    }

    public void ClickCss(string css)
    {
        var js = "document.querySelector('"+ css + "').click()";

        EvaluateJavascript(js);
    }


    public async Task EvaluateJavascript(string script)
    {
        JavascriptResponse javascriptResponse = await Browser.GetMainFrame().EvaluateScriptAsync(script);

        if (!javascriptResponse.Success)
        {
            throw new JavascriptException(javascriptResponse.Message);
        }
    }

details: enter image description here

enter image description here

used click code:

_browser.ClickCss("#upload-container a");

one more time: same js code perfectly works in browser dev console, but doesn't work in CEF for some reason.

By the way, I have tested JS code in Chrome. So WebEngine is the same in both situations.

PS: Also will work for me simulation of drag-and-drop of some specific file to some specific web-element. But I didn't found any information about this not for Cef, not for Js, not for JQuery... =(

Answer

Andrew picture Andrew · Aug 4, 2018

The problem was in security limitations of JS code.

Solution of the problem is:

  1. Get coordinates of a button/link with JS code
  2. Simulate click action on it with CEF:

    public void MouseClick(int x, int y)
    {
        Browser.GetBrowser().GetHost().SendMouseClickEvent(x, y, MouseButtonType.Left, false, 1, CefEventFlags.None);
        Thread.Sleep(15);
        Browser.GetBrowser().GetHost().SendMouseClickEvent(x, y, MouseButtonType.Left, true, 1, CefEventFlags.None);
    }