本文介绍了CefSharp网页元素点击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图对某些页面元素(例如btn或链接)进行简单单击。

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

我编写了2个用于通过xpath和CSS单击的函数

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

这两个功能在浏览器的开发人员控制台中都可以正常使用,但在CEF中部分无效。

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


  • 从开发者控制台和Cef的简单链接中完美单击代码

  • 完全单击精确代码从开发者控制台单击按钮,但不会从CEF中单击。只是出于某种原因而忽略了它...

这怎么可能? js代码绝对相同!...

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:

已使用点击代码:

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

又一次:相同的js代码在浏览器开发者控制台中完美运行,但在CEF中不起作用出于某些原因。

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

顺便说一句,我已经在Chrome中测试了JS代码。因此,WebEngine在这两种情况下都是相同的。

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

PS:这对我来说也可以用于将某些特定文件拖放到某些特定Web元素的模拟。但是我没有找到关于Cef,Js,JQuery的任何信息... =(

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... =(

推荐答案

问题出在JS代码的安全限制中。

The problem was in security limitations of JS code.

问题的解决方案是:


  1. 使用JS代码获取按钮/链接的坐标

  2. 使用CEF模拟对其的单击操作:

  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);
}


这篇关于CefSharp网页元素点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-04 16:00