How to handle popup links in CefSharp

AJDev picture AJDev · May 31, 2015 · Viewed 13.6k times · Source

I am creating a tabbed web browser using CefSharp 39.0.2. Right now, if the user clicks on a link on a website, it will open a new window that has none of my original UI. For example, when you click on an article link on Google News, it opens in a new window, but without any of the browsing controls I have made up. I also looked into the Cef.WinForms.Example program, and it does the same exact thing.

Is it possible to handle this in a different way? I would like for the link to either open in a new tab, or open in a new window (with all the controls there). I have been looking through the GitHub issues, and I could not find anything like this (maybe I was not looking hard enough, because I would think this is what others want to do as well...). I looked through all the events for the browser control, and I could not find any that would seem like they handle it.

Answer

Viktor Chvátal picture Viktor Chvátal · May 31, 2015

ChromiumWebBrowser has a LifeSpanHandler property. To manually control popup windows in Cefsharp, you have to implement your own life span handler object implementing the ILifeSpanHandle interface.

Every time browser wants to open a new window, it will call your life span handler's OnBeforePopup function. Here you can implement your desired behavior. If you return false, browser will pop up a new window. If you return true, browser will ignore pop up action, but you can manually create your new window, new tab, etc...

This is a very simple example of custom life span hander. On popup request, it fires an event called PopupRequest. You can subscribe such event and create new window/tab manually. Then, it returns true that instructs ChromiumWebBrowser not to create its own new window. However, you need to implement creating new window with another ChromiumWebBrowser on your own.

public class SampleLifeSpanHandler: ILifeSpanHandler
{
    public event Action<string> PopupRequest;

    public bool OnBeforePopup(IWebBrowser browser, string sourceUrl, string targetUrl, ref int x, ref int y, ref int width,
        ref int height)
    {
        if (PopupRequest != null)
            PopupRequest(targetUrl);

        return true;
    }

    public void OnBeforeClose(IWebBrowser browser)
    {

    }
}