### Start Example as CommonJS Module Source: https://github.com/ghostery/adblocker/blob/master/packages/adblocker-electron-example/README.md Execute this command to run the Electron adblocker example using CommonJS module format. ```sh yarn start:commonjs ``` -------------------------------- ### Start Example as ESM Module Source: https://github.com/ghostery/adblocker/blob/master/packages/adblocker-electron-example/README.md Use this command to run the Electron adblocker example with ECMAScript Modules (ESM). ```sh yarn start:esm ``` -------------------------------- ### Install Dependencies and Build Project Source: https://github.com/ghostery/adblocker/blob/master/README.md Commands to enable corepack, install dependencies, build the project, and run tests. Assumes the repository has been forked and cloned. ```bash corepack enable yarn install --immutable yarn build yarn test ``` -------------------------------- ### Install Python Dependencies and Run Jupyter Notebook Source: https://github.com/ghostery/adblocker/blob/master/bench/comparison/README.md Set up your Python environment by installing the required packages and launching the Jupyter Notebook server to analyze benchmark results. ```sh pip install -r requirements.txt jupyter notebook ``` -------------------------------- ### Initialize with Pre-built Configurations Source: https://github.com/ghostery/adblocker/blob/master/packages/adblocker-puppeteer/README.md Provides examples for initializing the blocker using ready-made configurations for ads only or ads and tracking. ```APIDOC ## Initialize with Pre-built Configurations Use convenient methods to initialize the blocker with common filter sets. ### Methods - `PuppeteerBlocker.fromPrebuiltAdsOnly(fetch)` - `PuppeteerBlocker.fromPrebuiltAdsAndTracking(fetch)` ### Parameters - `fetch`: A function that fetches resources, typically `cross-fetch`. ### Examples ```javascript import { PuppeteerBlocker } from '@ghostery/adblocker-puppeteer'; import fetch from 'cross-fetch'; // required 'fetch' // Ads only let blockerAdsOnly = await PuppeteerBlocker.fromPrebuiltAdsOnly(fetch); // Ads and tracking let blockerAdsAndTracking = await PuppeteerBlocker.fromPrebuiltAdsAndTracking(fetch); ``` ``` -------------------------------- ### Build Project with Yarn Source: https://github.com/ghostery/adblocker/blob/master/packages/adblocker-electron-example/README.md Use this command to build the project. Ensure you have Yarn installed and the project dependencies are set up. ```sh yarn build ``` -------------------------------- ### Initialize WebExtensionBlocker with Polyfill Source: https://github.com/ghostery/adblocker/blob/master/packages/adblocker-webextension/README.md When using Chromium-based browsers, a polyfill like webextension-polyfill is required. This example shows how to integrate it. ```javascript import { browser } from 'webextension-polyfill'; import { WebExtensionBlocker } from '@ghostery/adblocker-webextension'; WebExtensionBlocker.fromPrebuiltAdsAndTracking().then((blocker) => { blocker.enableBlockingInBrowser(browser); }); ``` -------------------------------- ### Safe Global Environment Setup Source: https://github.com/ghostery/adblocker/blob/master/packages/adblocker/assets/ublock-origin/resources.txt Initializes a safe global environment with essential utilities and browser APIs. Handles logging and communication via BroadcastChannel. ```javascript if(typeof scriptletGlobals==="undefined")var scriptletGlobals={};(function(){function e(){if(scriptletGlobals.safeSelf)return scriptletGlobals.safeSelf; const e=globalThis; const t={ Array_from:Array.from, Error:e.Error, Function_toStringFn:e.Function.prototype.toString, Function_toString:e=>t.Function_toStringFn.call(e), Math_floor:Math.floor, Math_max:Math.max, Math_min:Math.min, Math_random:Math.random, Object:Object, Object_defineProperty:Object.defineProperty.bind(Object), Object_defineProperties:Object.defineProperties.bind(Object), Object_fromEntries:Object.fromEntries.bind(Object), Object_getOwnPropertyDescriptor:Object.getOwnPropertyDescriptor.bind(Object), RegExp:e.RegExp, RegExp_test:e.RegExp.prototype.test, RegExp_exec:e.RegExp.prototype.exec, Request_clone:e.Request.prototype.clone, String_fromCharCode:String.fromCharCode, XMLHttpRequest:e.XMLHttpRequest, addEventListener:e.EventTarget.prototype.addEventListener, removeEventListener:e.EventTarget.prototype.removeEventListener, fetch:e.fetch, JSON:e.JSON, JSON_parseFn:e.JSON.parse, JSON_stringifyFn:e.JSON.stringify, JSON_parse:(...e)=>t.JSON_parseFn.call(t.JSON,...e), JSON_stringify:(...e)=>t.JSON_stringifyFn.call(t.JSON,...e), log:console.log.bind(console), logLevel:0, makeLogPrefix(...e){return this.sendToLogger&&`[${e.join(" \u205d ")}]`||""}, uboLog(...e){if(this.sendToLogger===void 0)return;if(e===void 0||e[0]==="")return;return this.sendToLogger("info",...e)}, uboErr(...e){if(this.sendToLogger===void 0)return;if(e===void 0||e[0]==="")return;return this.sendToLogger("error",...e)}, escapeRegexChars(e){return e.replace(/[.*+?^${}()|[\\]/g,"\\$&”)} initPattern(e,t={}){if(e==="")return{matchAll:true}; const r=t.canNegate!==true||e.startsWith("!")===false; if(r===false)e=e.slice(1); const n=/^\/(.+)\/([gimsu]*)$/.exec(e); if(n!==null)return{re:new this.RegExp(n[1],n[2]||t.flags),expect:r}; if(t.flags!==void 0)return{re:new this.RegExp(this.escapeRegexChars(e),t.flags),expect:r}; return{pattern:e,expect:r}}, testPattern(e,t){if(e.matchAll)return true; if(e.re)return this.RegExp_test.call(e.re,t)===e.expect; return t.includes(e.pattern)===e.expect}, patternToRegex(e,t=void 0,r=false){if(e==="")return/^/; const n=/^\/(.+)\/([gimsu]*)$/.exec(e); if(n===null){const n=this.escapeRegexChars(e); return new RegExp(r?`^${n}$`:n,t)} try{return new RegExp(n[1],n[2]||void 0)}catch(e){} return/^/}, getExtraArgs(e,t=0){const r=e.slice(t).reduce(((e,t,r,n)=>{if((r&1)===0){const t=n[r+1];const o=/^\d+$/.test(t)?parseInt(t,10):t; e.push([n[r],o])} return e}),[]); return this.Object_fromEntries(r)}, onIdle(t,r){if(e.requestIdleCallback)return e.requestIdleCallback(t,r); return e.requestAnimationFrame(t)}, offIdle(t){if(e.requestIdleCallback)return e.cancelIdleCallback(t); return e.cancelAnimationFrame(t)}} ; scriptletGlobals.safeSelf=t; if(scriptletGlobals.bcSecret===void 0)return t; const r=new e.BroadcastChannel(scriptletGlobals.bcSecret); let n=[]; t.logLevel=scriptletGlobals.logLevel||1; t.sendToLogger=(e,...t)=>{if(t.length===0)return; const o=`[${document.location.hostname||document.location.href}]${t.join(" ")}`; if(n===void 0)return r.postMessage({what:"messageToLogger",type:e,text:o}); n.push({type:e,text:o})} ; r.onmessage=e=>{ const o=e.data; switch(o){ case"iamready!":if(n===void 0)break; n.forEach((({type:e,text:t})=>r.postMessage({what:"messageToLogger",type:e,text:t}))) ;n=void 0; break; case"setScriptletLogLevelToOne":t.logLevel=1; break; case"setScriptletLogLevelToTwo":t.logLevel=2; break; } } ; r.postMessage("areyouready?"); return t } function t(t){ const r=e(); const n=e=>{ const t=[]; let n=0; do{ const e=r.Math_random().toString(36).slice(2); t.push(e); n+=e.length } while(n{ const n=scriptletGlobals.warOrigin; const o=t.slice(4); const s=[n,"/",o]; const i=scriptletGlobals.warSecret; if(i!==void 0)s.push("?secret=",i); const a=new r.XMLHttpRequest; a.responseType="text"; a.onloadend=t=>{ e(t.target.responseText||"") }; a.open("GET",s.join("")); a.send() })); return Promise.resolve("") } t(...["{{1}}","{{2}}","{{3}}","{{4}}","{{5}}","{{6}}","{{7}}","{{8}}","{{9}}","{{10}}"].filter(((e,t)=>e!=="{{"+(t+1)+"}}")).map((e=>decodeURIComponent(e))))})(); ``` -------------------------------- ### Initialize Scriptlet Globals and Setup Source: https://github.com/ghostery/adblocker/blob/master/packages/adblocker/assets/ublock-origin/resources.txt Sets up global variables and a BroadcastChannel for communication. It defines a safe global object with essential browser APIs and utility functions for scriptlet execution. ```javascript if(typeof scriptletGlobals==="undefined")var scriptletGlobals={};(function(){function e(){if(scriptletGlobals.safeSelf)return scriptletGlobals.safeSelf;const e=globalThis;const t={Array_from:Array.from,Error:e.Error,Function_toStringFn:e.Function.prototype.toString,Function_toString:e=>t.Function_toStringFn.call(e),Math_floor:Math.floor,Math_max:Math.max,Math_min:Math.min,Math_random:Math.random,Object:Object,Object_defineProperty:Object.defineProperty.bind(Object),Object_defineProperties:Object.defineProperties.bind(Object),Object_fromEntries:Object.fromEntries.bind(Object),Object_getOwnPropertyDescriptor:Object.getOwnPropertyDescriptor.bind(Object),RegExp:e.RegExp,RegExp_test:e.RegExp.prototype.test,RegExp_exec:e.RegExp.prototype.exec,Request_clone:e.Request.prototype.clone,String_fromCharCode:String.fromCharCode,XMLHttpRequest:e.XMLHttpRequest,addEventListener:e.EventTarget.prototype.addEventListener,removeEventListener:e.EventTarget.prototype.removeEventListener,fetch:e.fetch,JSON:e.JSON,JSON_parseFn:e.JSON.parse,JSON_stringifyFn:e.JSON.stringify,JSON_parse:(...e)=>t.JSON_parseFn.call(t.JSON,...e),JSON_stringify:(...e)=>t.JSON_stringifyFn.call(t.JSON,...e),log:console.log.bind(console),logLevel:0,makeLogPrefix(...e){return this.sendToLogger&&`[${e.join( ``` -------------------------------- ### WebExtension Ad Blocking Setup Source: https://github.com/ghostery/adblocker/blob/master/README.md Use this snippet in your background script to enable ad and tracker blocking in browser extensions. It initializes the blocker from pre-built filter lists. ```javascript import { WebExtensionBlocker } from '@ghostery/adblocker-webextension'; WebExtensionBlocker.fromPrebuiltAdsAndTracking().then((blocker) => { blocker.enableBlockingInBrowser(browser); }); ``` -------------------------------- ### Start Adblocker Playwright as CommonJS Source: https://github.com/ghostery/adblocker/blob/master/packages/adblocker-playwright-example/README.md Use this command to start the adblocker-playwright package using the CommonJS module system. ```sh $ yarn start:commonjs ``` -------------------------------- ### Start Adblocker Playwright as ESM Source: https://github.com/ghostery/adblocker/blob/master/packages/adblocker-playwright-example/README.md Use this command to start the adblocker-playwright package using the ECMAScript Modules (ESM) system. ```sh $ yarn start:esm ``` -------------------------------- ### Install Property Trap Source: https://github.com/ghostery/adblocker/blob/master/packages/adblocker/assets/ublock-origin/resources.txt Installs a trap for property access on a given object. This is used to intercept and potentially modify property reads and writes, especially for scriptlet injection. ```javascript Object_defineProperty(e,"name",{value:o});return new Proxy(e,{defineProperty(e,t){if(t!=="toString")return Reflect.defineProperty(...arguments);return true},deleteProperty(e,t){if(t!=="toString")return Reflect.deleteProperty(...arguments);return true},get(e,t){if(t==="toString")return function(){return`function ${o}() { [native code] }`}.bind(null);return Reflect.get(...arguments)}})};if(o==="")return;const u=document.currentScript;let l=e(n,r,a);if(r==="noopFunc"||r==="trueFunc"||r==="falseFunc")l=i(l);let f=false;const p=function(e){if(n)return false;if(f)return true;f=e!==void 0&&e!==null&&l!==void 0&&l!==null&&typeof e!==typeof l;if(f)s.uboLog(c,`Aborted because value set to ${e}`);return f};const d=function(e,t,r,n){if(n.init(r?e[t]:l)===false)return;const o=s.Object_getOwnPropertyDescriptor(e,t);let i,a;if(o instanceof s.Object){e[t]=l;if(o.get instanceof Function)i=o.get;if(o.set instanceof Function)a=o.set}try{s.Object_defineProperty(e,t,{configurable:r,get(){if(i!==void 0)i();return n.getter()},set(e){if(a!==void 0)a(e);n.setter(e)}});s.uboLog(c,"Trap installed")}catch(e){s.uboErr(c,e)}};const g=function(e,t){const r=t.indexOf(".");if(r===-1){d(e,t,false,{v:void 0,init:function(e){if(p(e))return false;this.v=e;return true},getter:function(){if(document.currentScript===u)return this.v;s.uboLog(c,"Property read");return l},setter:function(e){if(p(e)===false)return;l=e}});return}const n=t.slice(0,r);const o=e[n];t=t.slice(r+1);if(o instanceof s.Object||typeof o==="object"&&o!==null){g(o,t);return}d(e,n,true,{v:void 0,init:function(e){this.v=e;return true},getter:function(){return this.v},setter:function(e){this.v=e;if(e instanceof s.Object)g(e,t)}})};g(window,t)}r((()=>{u(o,i)}),a.runAt)}n(...["{{1}}","{{2}}","{{3}}","{{4}}","{{5}}","{{6}}","{{7}}","{{8}}","{{9}}","{{10}}"].filter(((e,t)=>e!=="{{"+(t+1)+"}}")).map((e=>decodeURIComponent(e))))})(); ``` -------------------------------- ### Initialize Electron Adblocker with Prebuilt Ads and Tracking Source: https://github.com/ghostery/adblocker/blob/master/packages/adblocker-electron/README.md Initialize the blocker using pre-built lists for both ads and tracking. Requires the 'cross-fetch' library. ```javascript import { ElectronBlocker } from '@ghostery/adblocker-electron'; import fetch from 'cross-fetch'; // required 'fetch' blocker = await ElectronBlocker.fromPrebuiltAdsAndTracking(fetch); // ads and tracking ``` -------------------------------- ### Get Element Data Source: https://github.com/ghostery/adblocker/blob/master/packages/adblocker/test/data/customs.txt Retrieves the data associated with the UI element. ```javascript t.ui.Element.prototype.getData=function(){return this.data} ``` -------------------------------- ### Initialize Electron Adblocker with Prebuilt Lists Source: https://github.com/ghostery/adblocker/blob/master/packages/adblocker-electron/README.md Use this method to initialize the blocker with pre-built lists for ads and tracking. Requires the 'cross-fetch' library. ```javascript import { ElectronBlocker } from '@ghostery/adblocker-electron'; import fetch from 'cross-fetch'; // required 'fetch' ElectronBlocker.fromPrebuiltAdsAndTracking(fetch).then((blocker) => { blocker.enableBlockingInSession(session.defaultSession); }); ``` -------------------------------- ### Get Element ID Source: https://github.com/ghostery/adblocker/blob/master/packages/adblocker/test/data/customs.txt Retrieves the ID of the UI element, generating one if it doesn't exist. ```javascript t.ui.Element.prototype.getElementId=function(){return null===this.elementId&&this.setElementId(t.ui.generateElementId())\,this.elementId} ``` -------------------------------- ### Initialize Electron Adblocker with Prebuilt Ads Only Source: https://github.com/ghostery/adblocker/blob/master/packages/adblocker-electron/README.md Initialize the blocker using only pre-built lists for ads. Requires the 'cross-fetch' library. ```javascript import { ElectronBlocker } from '@ghostery/adblocker-electron'; import fetch from 'cross-fetch'; // required 'fetch' let blocker = await ElectronBlocker.fromPrebuiltAdsOnly(fetch); // ads only ``` -------------------------------- ### Get Cookie by Name Source: https://github.com/ghostery/adblocker/blob/master/packages/adblocker/assets/ublock-origin/resources.txt Retrieves the value of a specific cookie by its name. If the cookie is not found, it returns undefined. ```javascript function e(e=""){for(const t of document.cookie.split(/\s*;\s*/)){const r=t.indexOf("=");if(r===-1)continue;if(t.slice(0,r)!==e)continue;return t.slice(r+1).trim()}} ``` -------------------------------- ### Initialize WebExtensionBlocker from Local Filters Source: https://github.com/ghostery/adblocker/blob/master/packages/adblocker-webextension/README.md Create a blocker instance by parsing local filter lists from a file. Ensure the file path is correct. ```javascript import { WebExtensionBlocker } from '@ghostery/adblocker-webextension'; const blocker = WebExtensionBlocker.parse(fs.readFileSync('easylist.txt', 'utf-8')); ``` -------------------------------- ### Modem Initialization String Source: https://github.com/ghostery/adblocker/blob/master/packages/adblocker/test/data/blns.txt This string is an AT command, potentially triggering issues in systems that process modem commands. ```text +++ATH0 ``` -------------------------------- ### Initialize Scriptlet Environment Source: https://github.com/ghostery/adblocker/blob/master/packages/adblocker/assets/ublock-origin/resources.txt Sets up the scriptlet environment, including safe global objects, logging, and event listeners. It handles initialization patterns and communication with the main process. ```javascript if(typeof scriptletGlobals==="undefined")var scriptletGlobals={}; (function(){ function e(){if(scriptletGlobals.safeSelf)return scriptletGlobals.safeSelf; const e=globalThis; const t={ Array_from:Array.from, Error:e.Error, Function_toStringFn:e.Function.prototype.toString, Function_toString:(e)=>t.Function_toStringFn.call(e), Math_floor:Math.floor, Math_max:Math.max, Math_min:Math.min, Math_random:Math.random, Object:Object, Object_defineProperty:Object.defineProperty.bind(Object), Object_defineProperties:Object.defineProperties.bind(Object), Object_fromEntries:Object.fromEntries.bind(Object), Object_getOwnPropertyDescriptor:Object.getOwnPropertyDescriptor.bind(Object), RegExp:e.RegExp, RegExp_test:e.RegExp.prototype.test, RegExp_exec:e.RegExp.prototype.exec, Request_clone:e.Request.prototype.clone, String_fromCharCode:String.fromCharCode, XMLHttpRequest:e.XMLHttpRequest, addEventListener:e.EventTarget.prototype.addEventListener, removeEventListener:e.EventTarget.prototype.removeEventListener, fetch:e.fetch, JSON:e.JSON, JSON_parseFn:e.JSON.parse, JSON_stringifyFn:e.JSON.stringify, JSON_parse:(...e)=>t.JSON_parseFn.call(t.JSON,...e), JSON_stringify:(...e)=>t.JSON_stringifyFn.call(t.JSON,...e), log:console.log.bind(console), logLevel:0, makeLogPrefix(...e){ return this.sendToLogger&&`[${e.join(" ⁝ ")}]`||"" }, uboLog(...e){ if(this.sendToLogger===void 0)return; if(e===void 0||e[0]==="")return; return this.sendToLogger("info",...e) }, uboErr(...e){ if(this.sendToLogger===void 0)return; if(e===void 0||e[0]==="")return; return this.sendToLogger("error",...e) }, escapeRegexChars(e){ return e.replace(/[.*+?^${}()|[\\]/g,"\\$& ") }, initPattern(e,t={}){ if(e==="")return{matchAll:true}; const r=t.canNegate!==true||e.startsWith("!")===false; if(r===false)e=e.slice(1); const n=/^\/(.+)\/([gimsu]*)$/.exec(e); if(n!==null)return{re:new this.RegExp(n[1],n[2]||t.flags),expect:r}; if(t.flags!==void 0)return{re:new this.RegExp(this.escapeRegexChars(e),t.flags),expect:r}; return{pattern:e,expect:r} }, testPattern(e,t){ if(e.matchAll)return true; if(e.re)return this.RegExp_test.call(e.re,t)===e.expect; return t.includes(e.pattern)===e.expect }, patternToRegex(e,t=void 0,r=false){ if(e==="")return /^/; const n=/^\/(.+)\/([gimsu]*)$/.exec(e); if(n===null){ const n=this.escapeRegexChars(e); return new RegExp(r?`^${n}$`:n,t) } try{ return new RegExp(n[1],n[2]||void 0) }catch(e){} return /^/; }, getExtraArgs(e,t=0){ const r=e.slice(t).reduce(((e,t,r,n)=>{ if((r&1)===0){ const t=n[r+1]; const o=/^\d+$/.test(t)?parseInt(t,10):t; e.push([n[r],o]) } return e }),[]); return this.Object_fromEntries(r) }, onIdle(t,r){ if(e.requestIdleCallback)return e.requestIdleCallback(t,r); return e.requestAnimationFrame(t) }, offIdle(t){ if(e.requestIdleCallback)return e.cancelIdleCallback(t); return e.cancelAnimationFrame(t) } }; scriptletGlobals.safeSelf=t; if(scriptletGlobals.bcSecret===void 0)return t; const r=new e.BroadcastChannel(scriptletGlobals.bcSecret); let n=[]; t.logLevel=scriptletGlobals.logLevel||1; t.sendToLogger=(e,...t)=>{ if(t.length===0)return; const o=`[${document.location.hostname||document.location.href}]${t.join(" ")}`; if(n===void 0)return r.postMessage({what:"messageToLogger",type:e,text:o}); n.push({type:e,text:o}) }; r.onmessage=e=>{ const o=e.data; switch(o){ case"iamready!": if(n===void 0)break; n.forEach((({type:e,text:t})=>r.postMessage({what:"messageToLogger",type:e,text:t}))) n=void 0; break; case"setScriptletLogLevelToOne": t.logLevel=1; break; case"setScriptletLogLevelToTwo": t.logLevel=2; break; } }; r.postMessage("areyouready?"); return t } function t(){ const t=e(); return t.String_fromCharCode(Date.now()%26+97)+t.Math_floor(t.Math_random()*982451653+982451653).toString(36) } function r(){ const e=t(); const r=self.onerror; self.onerror=function(t,...n){ if(typeof t==="string"&&t.includes(e))return true; if(r instanceof Function)return r.call(this,t,...n) }.bind(); return e } function n(t=""){ if(typeof t!=="string")return; if(t==="")return; const n=e(); const o=n.makeLogPrefix("abort-on-property-write",t); const s=r(); let i=window; for(;;){ const e=t.indexOf("."); if(e===-1)break; i=i[t.slice(0,e)]; if(i instanceof Object===false)return; t=t.slice(e+1) } delete i[t]; Object.defineProperty(i,t,{ set:function(){ n.uboLog(o,"Aborted"); throw new ReferenceError(s) } }) } n(...["{{1}}","{{2}}","{{3}}","{{4}}","{{5}}","{{6}}","{{7}}","{{8}}","{{9}}","{{10}}"].filter(((e,t)=>e!=="{{"+(t+1)+"}}")).map((e=>decodeURIComponent(e))))})(); ``` -------------------------------- ### Get All Cookies Source: https://github.com/ghostery/adblocker/blob/master/packages/adblocker/assets/ublock-origin/resources.txt This snippet is intended to retrieve all cookies. The provided code is a placeholder and requires further implementation to list all cookies. ```javascript get-all-cookies.fn application/javascript ``` -------------------------------- ### MultilineTextInputWidget Get Input Element Source: https://github.com/ghostery/adblocker/blob/master/packages/adblocker/test/data/customs.txt Returns the DOM element used for the input in a MultilineTextInputWidget, which is a textarea element. This is used for creating the widget. ```javascript t.ui.MultilineTextInputWidget.prototype.getInputElement=function(){return e("