如何使CefSharp WinForms控件滚动页面链接 [英] How to make CefSharp WinForms control Scroll page to Link

查看:192
本文介绍了如何使CefSharp WinForms控件滚动页面链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是在WinForms应用程序中使用CefSharp的情况.我们有两个信息,即页面URL和该页面中的链接URL.我们要加载页面-轻松完成,并让CefSharp显示链接所在页面的区域.也就是说,cefsharp会自动滚动到该链接在DOM内的页面上的正确位置.

最简单的方法是什么?

解决方案

不确定您使用的是哪个版本,我可以使用

我使用 CefSharp最小示例作为构建POC的起点.我将其上传到此处进行检查.

重建项目,启用包还原,因此它应该获取所有必需的包.之后,您可以运行它.在地址栏中输入stackoverflow.com,然后按Enter,然后在视图加载后向下滚动.

So here is the scenario, using CefSharp in a WinForms application. We have two pieces of information a page url and a link url within that page. We want to load the page - easily done, and have CefSharp show the area of the page where the link is located. That is cefsharp automatically scrolls to the right location on the page where that link is within the DOM.

What is the easiest way of doing that?

解决方案

Not sure which version you're using, I was able to solve this using the latest stable version of CefSharp (47.0.0).

First add a handler to the FrameLoadEnd event:

browser.FrameLoadEnd += OnBrowserFrameLoadEnd;

The handler is the following:

private void OnBrowserFrameLoadEnd(object sender, FrameLoadEndEventArgs frameLoadEndEventArgs)
{
    if (frameLoadEndEventArgs.Frame.IsMain && frameLoadEndEventArgs.Url == pageUrl)
    {
        frameLoadEndEventArgs.Browser.MainFrame.ExecuteJavaScriptAsync(
            "(function() { var el = document.querySelector('a[href=\"" + linkUrl +
            "\"]'); if(el) { el.scrollIntoView(); } })();");
    }
}

The two constants are:

private const string pageUrl = "http://stackoverflow.com/";
private const string linkUrl = "http://stackexchange.com/legal";

Whenever we navigate to the site in the pageUrl, we invoke a JavaScript function in the loaded document. It selects the first element which has an href attribute equal to the linkUrl using querySelector. If there is an element like that, then we invoke the scrollIntoView() method on it.

This particular example scrolls the following link into view when you visit stackoverflow.com.

I used the CefSharp Minimal Example as a starting point to build my POC. I uploaded it HERE for inspection.

Rebuild the project, package restore is enabled, so it should get all the necessary packages. After that you can run it. Enter stackoverflow.com into the address bar, hit Enter, and when it's loaded, the view should scroll down.

这篇关于如何使CefSharp WinForms控件滚动页面链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆