Skip to main content

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

We create fashion - Web site inspiration

Today, I was looking for a nice suit on the website. Something stylish, comfortable, and minimalistic came to mind, and I thought of Mango. When I visited their web pages, I found them very user-friendly. As I admired the well-designed suits and the beautiful website, I wondered about the company and went to their corporate pages. The website started with an intro, decorating a wall with their oldest photos. It felt like someone was there in front of me, telling their story to a newcomer. As time flew by, the quality and size of the photos on the wall increased. When we reach the present, a video covering the entire page plays, showing the inside of the factory and office like a drone, making me forget I was on a web page and feel like I was watching an impressive advertisement. It was very inspiring. The way a company could present itself so beautifully, how the pictures gradually grew, conveying nostalgia throughout and transitioning to the modern and minimalistic essence in just a f...

Apple Pay Türkiye'deyken başka ülkenin kartını eklemek

Apple Pay, Türkiye'deki düzenlemeler nedeniyle kullanılamıyor. Eklerken hata alabilirsiniz. Ancak yurt dışına gidecekseniz ve Wise hesabınız ya da başka bir ülkenin kredi kartını kullanmak istiyorsanız, iPhone'unuzun bölge ayarlarını gideceğiniz ülkeye göre yapmanız gerekmektedir. Bu değişiklikten sonra Apple Pay'e kredi kartı ekleyebilirsiniz. Türkiye'den kredi kartı eklemeye çalıştığınızda "izin verilmiyor" gibi belirgin hatalarla karşılaşabilirsiniz. Geçen ay Londra'da gerçekleşen iş seyahatimde Wise kartımla Apple Pay'i kullandım ve oldukça kullanışlı buldum. Teknolojinin ülkemizde de aktif olmasıyla kart kullanımının daha da kolaylaşacağını düşünüyorum.

MUFG Way

Hey friends, Big news! I've been featured on the MUFG website, and I'm over the moon about it. This piece dives into my role in the IT department at MUFG, my journey in the world of global finance tech, and my involvement in CSR activities. Reflecting on this, I feel a mix of gratitude and excitement. It's been an incredible journey of learning and growth. I'd love for you to read my story and share your thoughts. Check it out here . İstanbul / Photo by Görkem Yıldırım Türkçe/ Harika bir haberim var! MUFG'nin web sitesinde yer aldım ve bu benim için çok heyecan verici. Bu yazıda, MUFG'deki IT departmanındaki rolüm, global finans teknolojisindeki yolculuğum ve CSR faaliyetlerindeki katılımım anlatılıyor. Bunu düşününce, minnettarlık ve heyecan hissediyorum. Öğrenme ve büyüme dolu inanılmaz bir yolculuktu. Hikayemi okuyup düşüncelerinizi paylaşmanızı çok isterim. Buradan bakabilirsiniz.