【问题标题】:CefSharp get a part from a Source Code of a selected/active elementCefSharp 从选定/活动元素的源代码中获取一部分
【发布时间】:2020-05-29 10:43:47
【问题描述】:

大家好???并且已经提前感谢了!

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

我达到的是:

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

使用此代码问题似乎解决了????。但我想知道是否有没有计时器的“更好”方法。

【问题讨论】:

标签: javascript c# winforms cefsharp


【解决方案1】:

答案或者说更好的解决方案是(感谢@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());
              }
        ");
    }
}

【讨论】:

    猜你喜欢
    • 2018-03-14
    • 2016-06-23
    • 2015-09-05
    • 2018-05-14
    • 1970-01-01
    • 2018-04-08
    • 1970-01-01
    • 2020-01-22
    • 1970-01-01
    相关资源
    最近更新 更多