How to pre-install adblock to the cefsharp project



http://old-support.getadblock.com/discussions/questions/79056-how-to-pre-install-adblock-to-our-cefsharp-project

This article is created for those who ask for a solution questioned in the linked page above.

I have to say I receive many e mails from around the world so that I will explain the answer acording to my knowledge from these days (... year 2016)

So there is no an easy way to install extensions to CEF. Google make extension apis by its own way. It is built on chromium branch but Google Chrome
made many developments specially for its browser.  Ofcourse you can build your extension manager on chromium project. So for this case better to explore
this link first. In this link you ll see my work about installing adblock by myself. It worked but not as I expected in chrome of google. I kindly shared for you to save some time...


So as a sum up; to have a custom ad blocking system; we put a filter between a method from in chromium wrapper CEF.


We used a simple way;
  CefReturnValue IRequestHandler.OnBeforeResourceLoad(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IRequestCallback callback)
        {
            if (request.Url.Contains("custom://") || request.Url.Contains("chrome-devtools://") || request.Url.StartsWith("https://") || frame.Url =="about:blank" || request.Url == "about:blank" || frame.Url == "" )//|| ExtractDomainNameFromURL_Method2(request.Url) == ExtractDomainNameFromURL_Method2(frame.Url))
                return CefReturnValue.Continue;
          
           
            if (ownerx.bioplusobj.adManager
.isAd(request.Url))
            {
                BrowserView.browser.ExecuteScriptAsync(
"console.error( 'Relam Vevo Adblock tarafından engellendi. " + request.Url + "')");
                blockedUrls.Add(request.Url);
                
return CefReturnValue.Cancel;
            }
    

            
return CefReturnValue.Continue;ü
}

//Admanager
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace CefSharp.Wpf.Example.Controls
{
    
public class AdBlock
    {
        
private static   String TAG = "AdBlock";
    
private static   String BLOCKED_DOMAINS_LIST_FILE_NAME = "hosts.txt";
    
private static   String LOCAL_IP_V4 = "127.0.0.1";
    
private static   String LOCAL_IP_V4_ALT = "0.0.0.0";
    
private static   String LOCAL_IP_V6 = "::1";
    
private static   String LOCALHOST = "localhost";
    
private static   String COMMENT = "#";
    
private static   String TAB = "\t";
    
private static   String SPACE = " ";
    
private static    String EMPTY = "";
   
        
public bool mBlockAds { getset; }//abdlock aktif
      //  private static   Locale mLocale = Locale.getDefault();
        List<string> mBlockedDomainsList =new  List<string>();
        
public List<string>  BlockList { get; }
        
public AdBlock()
        {
            mBlockAds = 
true;

        }
       
 public bool isAd(  String url)
        {
            
if (!mBlockAds || url == null)
            {
                
return false;
            }
            String domain;
            
try
            {
                domain = getDomainName(url);
            }
            
catch (Exception ex)
            {
                Console.WriteLine( 
"URL '" + url + "' is invalid" + ex.Message);
                
return false;
            }
            
bool isOnBlacklist = mBlockedDomainsList.Contains(domain.ToLower(System.Globalization.CultureInfo.CurrentCulture));
            
//if (isOnBlacklist)
            //{
            //    Log.d(TAG, "URL '" + url + "' is an ad");
            //}
            return isOnBlacklist;
        }
        
private static String getDomainName(  String url)  
        {
        
int index = url.IndexOf('/'8);
        
if (index != -1) {
            url = url.Substring(
0, index);
        }
        Uri uri = 
new Uri(url);
            String domain = uri.Host;
        
if (domain == null) {
            
return url;
        }
        
return domain.StartsWith("www.") ? domain.Substring(4) : domain;
    }
        
public void getDomainNamesReady()
        {
            
var executingAssembly = Assembly.GetExecutingAssembly();
            
var path = Path.GetDirectoryName(executingAssembly.Location);
            FileInfo fi = 
new FileInfo(Path.Combine(path, "Pages\\src\\hosts.txt"));
           
           
// string filterText = objReader.ReadToEnd();
            try
            {
                
//noinspection IOResourceOpenedButNotSafelyClosed
                 
                 String line;
                
using (StreamReader reader = new StreamReader(fi.OpenRead(), Encoding.UTF8))
                {
                    
while (reader.Peek() >= 0)
                    {
                        line = reader.ReadLine();
                        
if (!string.IsNullOrEmpty(line) && !line.StartsWith(COMMENT))
                        {
                           
                            line = line.Replace(LOCAL_IP_V4, EMPTY)
                                    .Replace(LOCAL_IP_V4_ALT, EMPTY)
                                    .Replace(LOCAL_IP_V6, EMPTY)
                                    .Replace(TAB, EMPTY);
                            
int comment = line.IndexOf(COMMENT);
                            
if (comment >= 0)
                            {
                                line = line.Substring(
0, comment);
                            }
                            line = line.Trim();
                            
if (!string.IsNullOrEmpty(line) && !line.Equals(LOCALHOST))
                            {
                                
while (line.Contains(SPACE))
                                {
                                    
int space = line.IndexOf(SPACE);
                                    String host = line.Substring(
0, space);
                                    mBlockedDomainsList.Add(host.Trim());
                                    line = line.Substring(space, line.Length).Trim();
                                }
                                mBlockedDomainsList.Add(line.Trim());
                            }
                        }
                    }
                }
                 
            }
            
catch (IOException e)
            {
                Console.WriteLine( 
"(TAG,  Reading blocked domains list from file '"
                        + BLOCKED_DOMAINS_LIST_FILE_NAME + "' failed." + e.Message);
            }
            
            
        }
    }
}


//You can get updated blo
cked list of advertsement list from adblock web site assets. Or just search extensions database in your chrome.
Pages\\src\\hosts.txt"


To sum up I have shared two methods. 1 st one is the ideal but harder. Second one is easier but simpler. 

Comments

Popular posts from this blog

Portekiz Yolculuğum

Empowering Positive Change as a Cultural Influencer in the Workplace