CefSharp 从 selected/active 元素的源代码中获取一部分

CefSharp get a part from a Source Code of a selected/active element

大家好,已经提前谢谢了!

我需要以某种方式只获得加载的网站源代码的一部分(图片点 2) 通过悬停 (如果不可能我也很高兴在元素 (图片点 1) 上单击鼠标)。 我知道这听起来可能很奇怪,因为 DevTool 只需单击 (图片点 3) 就已经非常好用了。 但如果可能的话,我只想读出内部和外部 HTML (我现在需要的) active/selected 的部分。

我达到的是:

int counter = 0;

private async void timer1_Tick(object sender, EventArgs e)
{
        string returnValue = "";

        string script = "(function() { return document.activeElement.outerHTML; })();";

        var task = browser.GetMainFrame().EvaluateScriptAsync(script);

        await task.ContinueWith(t =>
        {
            if (!t.IsFaulted)
            {
                var response = t.Result;

                if (response.Success && response.Result != null)
                {
                    returnValue = response.Result.ToString();
                }
            }
        });

        if (returnValue != "")
        {
            richTextBox1.Invoke(new Action(() => richTextBox1.Text = returnValue));
        }
        else // Just to check if there still happens something:
        {
            counter += 1;
            richTextBox1.Invoke(new Action(() => richTextBox1.Text = counter.ToString() ));
        }
}

有了这段代码,问题似乎就解决了。但是我想知道有没有不用计时器的"better"方法。

答案或者说更好的解决方案是(感谢@amaitland)扔掉那个计时器并改用(在Form_Load或任何你设置一切的地方):

browser.JavascriptMessageReceived += OnBrowserJavascriptMessageReceived;
browser.FrameLoadEnd += Browser_FrameLoadEnd;

并将我的代码放入:

private void OnBrowserJavascriptMessageReceived(object sender, JavascriptMessageReceivedEventArgs e)
{
    // the code
}

同时你还需要:

async void Browser_FrameLoadEnd(object sender, FrameLoadEndEventArgs e)
{ // Does wait till the Website is fully loaded.
    if (e.Frame.IsMain)
    {
        //In the main frame we inject some javascript that's run on mouseUp
        //You can hook any javascript event you like.
        browser.ExecuteScriptAsync(@"
              document.body.onmouseup = function()
              {
                //CefSharp.PostMessage can be used to communicate between the browser
                //and .Net, in this case we pass a simple string,
                //complex objects are supported, passing a reference to Javascript methods
                //is also supported.
                //See https://github.com/cefsharp/CefSharp/issues/2775#issuecomment-498454221 for details
                CefSharp.PostMessage(window.getSelection().toString());
              }
        ");
    }
}