Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

winforms - How to handle popup links in CefSharp

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)
    {

    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...