By default in Cefsharp, when you navigate to a webpage that contains links that are launched in a new window (target=_blank), the HTML of that link looks like this:
<a href="https://ourcodeworld.co" target="_blank"> Launch Our Code World in Spanish </a>
So when the user clicks on the link when running in CefSharp, a new window will be launched:
If you control the markup of the page that you are visiting, you may simply remove the
target=_blank attribute from the links, however, the most optimal way to prevent this from happening is through the LifeSpanHandler (considering that your need is to force that every link will be opened in the same initial instance of the browser, in this case,
1. Create a custom LifeSpanHandler class
As the first step to preventing the default behavior from happening, is to create a new class in your project. This class will override the behavior of the LifeSpanHandler class of CefSharp. The content of the class is the following one, you can simply copy its content and add it to your project. The important method in this class is the OnBeforePopup method that is triggered when the user clicks on the links that will show up as Popups, with the given instruction, the new URL will show up now in the same browser (Form1), instead of opening a new one. The other methods (DoClose, OnAfterCreated, OnBeforeClose) need to be declared as well or you will find an exception with the interface:
2. Force CefSharp to use the custom LifeSpanHandler
Once the class has been created and is available in your project, then you only need to set the value of the LifeSpanHandler property of your ChromiumWebBrowser as a new instance of your custom life span handler. This can be achieved during the creation of the browser in your current code, for example:
CefSettings settings = new CefSettings(); // Some settings if you have, here // Initialize cef with the provided settings Cef.Initialize(settings); // Create a browser component ChromiumWebBrowser chromeBrowser = new ChromiumWebBrowser("https://ourcodeworld.co"); // Register your Custom LifeSpanHandler chromeBrowser.LifeSpanHandler = new MyCustomLifeSpanHandler(); // ... // Rest of your code // ...
Initialize your project and try clicking once again in the links that used to launch a new window in your CefSharp component, now they should open in the same window that you are working on instead of a new one.
Happy coding ❤️!