/**
 * Konichiwa~
 *
 * This is script that is responsible for request blocking.
 * It is a major part of the remove ads functionality.
 */ import { loadSettings } from "./utils" ; let blockListRe = [ ] ; /**
 * As the name says! This function initializes the blocklist
 * by converting the array of string filter to a array of
 * regexes.
 */ function initializeBlockList ( ) { return new Promise ( resolve => { blockListRe = [ ] ; loadSettings ( "adBlockFilters" ) . then ( resp => { if ( resp . adBlockFilters && resp . adBlockFilters . length > 0 ) { for ( let filter of resp . adBlockFilters ) { blockListRe . push ( new RegExp ( filter ) ) ; } } resolve ( ) ; } ) ; } ) ; } /**
 * This is the key part of request blocking. This function basically
 * listens to all the request coming from the browser, regex match them
 * against the block list and cancels them as and when required. This
 * is very much like how other adblockers work, albeit in a much simpler
 * way.
 */ function blockListener ( details ) { for ( let re of blockListRe ) { if ( re . test ( details . url ) ) { return { cancel : true } ; } } } function attachBlockListener ( ) { chrome . webRequest . onBeforeRequest . addListener ( blockListener , { urls : [ "http://*/*" , "https://*/*" , ] , } , [ "blocking" ] ) ; } function removeBlockListener ( ) { if ( chrome . webRequest . onBeforeRequest . hasListener ( blockListener ) ) { chrome . webRequest . onBeforeRequest . removeListener ( blockListener ) ; } } export function updateViaLocal ( filterList ) { return new Promise ( ( resolve , reject ) => { chrome . storage . local . set ( { adBlockFilters : filterList , } ) ; initializeBlockList ( ) . then ( ( ) => resolve ( ) ) ; } ) ; } export function enableAdblocker ( ) { initializeBlockList ( ) . then ( ( ) => attachBlockListener ( ) ) ; } export function disableAdblocker ( ) { removeBlockListener ( ) ; } export function setup ( ) { loadSettings ( "remAds" ) . then ( resp => { if ( resp . remAds ) { enableAdblocker ( ) ; } } ) ; }