Imran Khan
Imran Khan

Reputation: 61

How to get CefSharp DevTools Element Selector's output in .NET C#?

I have Embeded CefSharp in my WinForms. Now I am trying to find a mechanism to somehow let user use Dev Tools' Element Selector ( without showing that builtin dev tools windows) and on user's click on element I want to get the HTML in my .NET code.

Can I do this and any help on how to ?

Thanks,

Khan

Upvotes: 5

Views: 7029

Answers (2)

Eric Bynum
Eric Bynum

Reputation: 730

This old question came up as the top google result and it was not easy to find a good solution, so hopefully this helps anyone else having to mess with cefsharp. You can add an "Inspect" context-menu option by implementing IContextMenuHandler.

public class DevToolsMenuHandler : IContextMenuHandler
{
    public void OnBeforeContextMenu(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IContextMenuParams parameters,
        IMenuModel model)
    {
        model.AddItem(CefMenuCommand.CustomFirst, "Inspect");
    }

    public bool OnContextMenuCommand(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IContextMenuParams parameters,
        CefMenuCommand commandId, CefEventFlags eventFlags)
    {
        if (commandId != CefMenuCommand.CustomFirst) return false;

        browser.ShowDevTools(null, parameters.XCoord, parameters.YCoord);
        return true;
    }

    public void OnContextMenuDismissed(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame)
    {
    }

    public bool RunContextMenu(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IContextMenuParams parameters,
        IMenuModel model, IRunContextMenuCallback callback)
    {
        return false;
    }
}

Then assign your custom menu handler to your CEF browser instance like so:

CefBrowser.MenuHandler = new DevToolsMenuHandler();

Upvotes: 3

jornh
jornh

Reputation: 1369

Hope I understood your requirements right; "you want to let the user see a highlight of the currently hovered element, then pick it by mouse-click"? Then I would take another route than hooking into the Dev Tools inspector feature.

  1. I think it is easier to replicate it with a snippet of your own JavaScript like in this other question: highlight a DOM element on mouse over, like inspect does. There is even a JSFiddle demo of one of the suggested ways of coding it.

  2. You then "only" need to detect which element the user clicks and send it to the .NET side.

  3. See the CefSharp FAQ for help on calling between .NET and JS (or the opposite).

If the route you want to take for some reason really is to use the DevTools Inspector I would start to look at:

Upvotes: 3

Related Questions