How to prevent target blank links from opening in a new window in Cefsharp

By FoxLearn 7/3/2024 2:27:50 AM   27
In CefSharp, which is a .NET wrapper for the Chromium Embedded Framework (CEF), you can control how links with target="_blank" are handled.

By default, links with target="_blank" will open in a new window or tab in most browsers. To prevent this behavior and handle them differently, you can intercept these links and decide how to handle them programmatically.

<a href="https://foxlearn.com" target="_blank">CefSharp</a>

Here’s how to prevent target="_blank" links from opening in a new window/tab in CefSharp.

You can create a custom LifeSpanHandler class

public class CustomLifeSpanHandler : ILifeSpanHandler
{
    // Load new URL in the same frame
    public bool OnBeforePopup(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, string targetUrl, string targetFrameName, WindowOpenDisposition targetDisposition, bool userGesture, IPopupFeatures popupFeatures, IWindowInfo windowInfo, IBrowserSettings browserSettings, ref bool noJavascriptAccess, out IWebBrowser newBrowser)
    {
        browser.MainFrame.LoadUrl(targetUrl);
        newBrowser = null;
        return true;
    }

    public bool DoClose(IWebBrowser chromiumWebBrowser, IBrowser browser)
    {
        // throw new NotImplementedException();
        return true;
    }

    public void OnAfterCreated(IWebBrowser chromiumWebBrowser, IBrowser browser)
    {
        // throw new NotImplementedException();
    }

    public void OnBeforeClose(IWebBrowser chromiumWebBrowser, IBrowser browser)
    {
        // throw new NotImplementedException();
    }
}

Once you have created and included a custom class in your project, you simply assign an instance of this class to the LifeSpanHandler property of your ChromiumWebBrowser object

CefSettings settings = new CefSettings();
// Initialize cef with the provided settings
Cef.Initialize(settings);

// Create a browser component
var chromeBrowser = new ChromiumWebBrowser("https://foxlearn.com");
// Register your Custom LifeSpanHandler
chromeBrowser.LifeSpanHandler = new CustomLifeSpanHandler();

You can intercept link clicks using an event handler and modify the target attribute to control where the link opens.

CefSharp provides an event called OpenNewTab which allows you to intercept requests to open links in a new tab.

chromeBrowser.LifeSpanHandler.OpenNewTab += (sender, e) =>
{
    // Cancel opening in new tab
    e.Cancel = true;

    // Open the URL in the current tab
    browser.Load(e.TargetUrl);
};

This code intercepts the request to open a new tab (e.Cancel = true;) and then loads the URL in the current tab (browser.Load(e.TargetUrl);).

When a link with target="_blank" is clicked, it triggers the OpenNewTab event. You can check if the link has target="_blank" and handle it accordingly.

chromeBrowser.FrameLoadEnd += (sender, e) =>
{
    if (e.Frame.IsMain)
    {
        browser.EvaluateScriptAsync(@"
            var links = document.getElementsByTagName('a');
            for (var i = 0; i < links.length; i++) {
                var link = links[i];
                if (link.target === '_blank') {
                    link.target = '_self';
                }
            }
        ");
    }
};

This script runs after the main frame has finished loading and changes the target attribute of all links (<a> tags) from _blank to _self. This will cause links with target="_blank" to open in the current tab instead of a new tab.

Alternatively, you can modify the default behavior of links with target="_blank" globally by injecting JavaScript into every page you load:

chromeBrowser.FrameLoadEnd += (sender, e) =>
{
    if (e.Frame.IsMain)
    {
        browser.ExecuteScriptAsync(@"
            (function() {
                var targetLinks = document.querySelectorAll('a[target=_blank]');
                Array.prototype.forEach.call(targetLinks, function(link) {
                    link.removeAttribute('target');
                    link.addEventListener('click', function(event) {
                        event.preventDefault();
                        window.open(link.href, '_self');
                    });
                });
            })();
        ");
    }
};

This script removes the target attribute from all links with target="_blank" and attaches a click event listener to them. When clicked, it prevents the default behavior (event.preventDefault()) and opens the link in the current tab (window.open(link.href, '_self')).