Have you ever heard of WebBrowser in .NET Application? If yes, then you know how bad is the
Default WebBrowser in .NET. In Internet we can find many alternative for the .NET's Default WebBrowser. There are many, such as
CefSharp or GeckoFX,....
In this post I will introduce to you GeckoFX and I will show you how to build your first
Gecko Browser program with the
Blocking Feature.
GeckoFX is the open source component to embedding the Gecko rendering engine from
Mozilla Firefox to
.NET application.
To download GeckoFX-Source (current version is
GeckoFX-45) go to the GeckoFX
BitBucket Wikipage
https://bitbucket.org/geckofx/geckofx-45.0/wiki/Home
Or we can use "
NuGet-Package Manager" to install GeckoFX-45 to your project as the picture below:
After that we'll see the Firefox folder and the 2 new Dependencies in the Project Explorer Window:
First we have to declare Gecko namespace
using Gecko;
Just one more setting, select all files from the Firefox folder and select "
Always copy" or "
Copy when newer" to "
Output folder" as below:
Now we can use the GeckoWebbrowser. Just declare the
GeckoWebBrowser variable and
load all the needed dll files as the picture below:
What is function
InitBrowser? It a function to configure the WebBrowser and to add the Browser into the Form
The important Thing to use Blocking feature of GeckoFX is we have to enable HttpActivityObserver, so we set here
UseHttpActivityObserver = true.
After UseHttpActivityObserver is enabled, we need to add a Event-Handler, in this case is
ObserveHttpModifyRequest-Event from GeckoWebBrowser.
When the WebBrowser send any request to any URL the event ObserveHttpModifyRequest will be fired. We can get the
URL of the request by using variable
request and convert it to string with
request.Uri.ToString(). In this example, I
block all the Request that
contain "google.com" in the URL.
Here is the code:
public GeckoWebBrowser webBrowser;
public Form1()
{
InitializeComponent();
Xpcom.Initialize("Firefox"); // Init all Gecko DLL files in the Firefox folder inside the Project
InitBrowser();
}
// Init Browser
void InitBrowser()
{
webBrowser = new GeckoWebBrowser { Dock = DockStyle.Fill, // Fill all the Form
UseHttpActivityObserver = true // This is to enable HttpActivityObserver
};
webBrowser.ObserveHttpModifyRequest += (obj, request) => {
if (!request.Uri.ToString().Contains("google.com")) // if the request URL contains string "google.com"
{
request.Cancel = true; // Cancel the request to the URL
}
};
this.Controls.Add(webBrowser);
}
When you have any question, feel free to leave a commend, I will answer as soon as I can. Have fun coding!
P/S: In this tutorial I installed and use GeckoFX-45
32 bit, so when build the project I have to choose
x32 Platform (It will give
error when you try to compile to
64 bit Application, in case you want to build 64 bit Application, just install
GeckoFx45.64 in the
NuGet-Package Manager)