How to make CefSharp WinForms control Scroll page to Link

柔情痞子 提交于 2021-02-19 06:39:06

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/34970190/how-to-make-cefsharp-winforms-control-scroll-page-to-link

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!