How to develop an edge browser plug-in in c# language

Edge browser plug-ins can be developed using C# language, but some frameworks and tools are required for support. Below are the steps for a basic Edge browser plugin development:

Create a plug-in project: Use Visual Studio to create a Class Library project as the basic project of the plug-in.

Reference the Edge browser API: Using the NuGet package manager, add the Microsoft.Toolkit.Win32.UI.Controls and Microsoft.Toolkit.Win32.UI.Controls.WebView packages to the project, and reference the Microsoft. Web.WebView2.Core and Microsoft.Web.WebView2.WinForms namespaces.

Create the main form: Add a Windows Form form to the project, and add a WebView2 control to it to display the content of the Edge browser. In the form's Load event, initialize the WebView2 control and load the specified URL in it.

using Microsoft.Web.WebView2.Core;
using Microsoft.Web.WebView2.WinForms;

public partial class MainForm : Form
{
    
    
    private WebView2 webView;

    public MainForm()
    {
    
    
        InitializeComponent();
    }

    private async void MainForm_Load(object sender, EventArgs e)
    {
    
    
        CoreWebView2Environment environment = await CoreWebView2Environment.CreateAsync();
        webView = new WebView2();
        webView.Dock = DockStyle.Fill;
        webView.Source = new Uri("https://www.example.com");
        webView.CoreWebView2InitializationCompleted += WebView_CoreWebView2InitializationCompleted;
        Controls.Add(webView);
    }

    private void WebView_CoreWebView2InitializationCompleted(object sender, CoreWebView2InitializationCompletedEventArgs e)
    {
    
    
        // WebView2控件初始化完成后,可以进行其他操作
    }
}

Add plug-in function: Add other controls or menu items in the form to realize the specific functions of the plug-in. For example, a "Filter Ad" menu item can be added to filter the advertisement content in the webpage in the WebView2 control.

private async void FilterAdsToolStripMenuItem_Click(object sender, EventArgs e)
{
    
    
    // 获取当前网页中的所有元素
    string script = "Array.from(document.querySelectorAll('*')).map(e => e.tagName + '#' + e.id + '.' + Array.from(e.classList).join('.')).join(';')";
    string elements = await webView.ExecuteScriptAsync(script);

    // 根据元素的标签名、ID和类名等特征,识别和隐藏广告元素
    string[] elementList = elements.Split(';');
    foreach (string element in elementList)
    {
    
    
        if (IsAdElement(element))
        {
    
    
            string[] parts = element.Split('#', '.', StringSplitOptions.RemoveEmptyEntries);
            string script2 = $"document.querySelector('{
      
      parts[0]}#{
      
      parts[1]}').style.display = 'none';";
            await webView.ExecuteScriptAsync(script2);
        }
    }
}

private bool IsAdElement(string element)
{
    
    
    // 判断元素是否为广告元素
    // ...
    return false;
}

Package the plug-in: Use the packaging tool provided by Visual Studio to package the project into an .msi or .exe file and upload it to the Edge plug-in store or other hosting platforms.
It should be noted that the WebView2 control is required for the development of Edge browser plug-ins in C# language, and the installation and configuration of the WebView2 control may be limited by the system and browser version. Therefore, during the development and testing process, it needs to be adjusted and tested according to the specific situation.

The WebView2 control was developed by Microsoft as part of the Edge browser, but is not open source. The WebView2 control is a Chromium-based WebView technology that can embed the Chromium browser engine in Windows and provides a set of API interfaces for interacting with the WebView control. The WebView2 control supports multiple programming languages, including C++, .NET (including WinForms and WPF), and JavaScript.

Although the WebView2 control is not open source, Microsoft provides rich documents and sample codes, as well as a series of API interfaces and tools, which can help developers quickly build WebView2-based applications and plug-ins. In addition, the WebView2 control also provides some advanced functions, such as the interoperability between JavaScript and .NET, and custom Web resource loaders, etc., which can meet various complex needs.

The following is a sample code for creating an Edge browser plug-in based on the WebView2 control using C# language and WinForms technology, which can filter advertisement content in the browser:

using Microsoft.Web.WebView2.Core;
using Microsoft.Web.WebView2.WinForms;
using System;
using System.Linq;
using System.Windows.Forms;

namespace AdBlockerPlugin
{
    
    
    public partial class MainForm : Form
    {
    
    
        private WebView2 webView;

        public MainForm()
        {
    
    
            InitializeComponent();
        }

        private async void MainForm_Load(object sender, EventArgs e)
        {
    
    
            CoreWebView2Environment environment = await CoreWebView2Environment.CreateAsync();
            webView = new WebView2();
            webView.Dock = DockStyle.Fill;
            webView.Source = new Uri("https://www.example.com");
            webView.CoreWebView2InitializationCompleted += WebView_CoreWebView2InitializationCompleted;
            Controls.Add(webView);
        }

        private async void FilterAdsToolStripMenuItem_Click(object sender, EventArgs e)
        {
    
    
            // 获取当前网页中的所有元素
            string script = "Array.from(document.querySelectorAll('*')).map(e => e.tagName + '#' + e.id + '.' + Array.from(e.classList).join('.')).join(';')";
            string elements = await webView.ExecuteScriptAsync(script);

            // 根据元素的标签名、ID和类名等特征,识别和隐藏广告元素
            string[] elementList = elements.Split(';');
            foreach (string element in elementList)
            {
    
    
                if (IsAdElement(element))
                {
    
    
                    string[] parts = element.Split('#', '.', StringSplitOptions.RemoveEmptyEntries);
                    string script2 = $"document.querySelector('{
      
      parts[0]}#{
      
      parts[1]}').style.display = 'none';";
                    await webView.ExecuteScriptAsync(script2);
                }
            }
        }

        private bool IsAdElement(string element)
        {
    
    
            // 判断元素是否为广告元素
            // ...
            return false;
        }

        private void WebView_CoreWebView2InitializationCompleted(object sender, CoreWebView2InitializationCompletedEventArgs e)
        {
    
    
            // WebView2控件初始化完成后,可以进行其他操作
        }
    }
}

In this example, a WinForms form is created and a WebView2 control is added. In the form's Load event, initialize the WebView2 control and load the specified URL in it. Add a "Filter Ads" menu item to the form. After clicking the menu item, get all the elements in the current web page, and use the IsAdElement method to determine which elements are advertising elements, and then hide these advertising elements through JavaScript code. It should be noted that the code in the IsAdElement method needs to be written according to the specific situation, so as to realize correct advertisement filtering.

Guess you like

Origin blog.csdn.net/zhangzhechun/article/details/131911182