xref: /docs/en/application-dev/web/web-adsblock.md (revision e41f4b71)
1# Enabling Ads Blocking of the Web Component
2
3The **Web** component provides features for blocking advertisement, including the common capabilities such as URL interception and element hiding. You can use [setAdsBlockRules()](../reference/apis-arkweb/js-apis-webview.md#setadsblockrules12) provided by **AdsBlockManager** to set blocking rules in EasyList and use [enableAdsBlock()](../reference/apis-arkweb/js-apis-webview.md#enableadsblock12) of the **Web** component to enable the ads blocking.
4
5## Enabling Ads Blocking
6The following example shows how to select the EasyList rule file using the file picker and how to enable the ads blocking in an application.
7
8```ts
9// xxx.ets
10import { webview } from '@kit.ArkWeb';
11import { picker, fileUri } from '@kit.CoreFileKit';
12
13// This example demonstrates how to click a button to open the EasyList using file picker and set the file in the Web component.
14@Entry
15@Component
16struct WebComponent {
17  main_url: string = 'https://www.example.com';
18  controller: webview.WebviewController = new webview.WebviewController();
19
20  @State input_text: string = 'https://www.example.com';
21
22  build() {
23    Column() {
24      Row() {
25        Flex() {
26          Button({type: ButtonType.Capsule}) {
27            Text("setAdsBlockRules")
28          }
29          .onClick(() => {
30            try {
31              let documentSelectionOptions: ESObject = new picker.DocumentSelectOptions();
32              let documentPicker: ESObject = new picker.DocumentViewPicker();
33              documentPicker.select(documentSelectionOptions).then((documentSelectResult: ESObject) => {
34                if (documentSelectResult && documentSelectResult.length > 0) {
35                  let fileRealPath = new fileUri.FileUri(documentSelectResult[0]);
36                  console.info('DocumentViewPicker.select successfully, uri: ' + fileRealPath);
37                  webview.AdsBlockManager.setAdsBlockRules(fileRealPath.path, true);
38                }
39              })
40            } catch (err) {
41              console.error('DocumentViewPicker.select failed with err:' + err);
42            }
43          })
44        }
45      }
46      Web({ src: this.main_url, controller: this.controller })
47        .onControllerAttached(()=>{
48          this.controller.enableAdsBlock(true);
49        })
50    }
51  }
52}
53```
54
55When the component has a built-in EasyList, the **replace** parameter of [setAdsBlockRules()](../reference/apis-arkweb/js-apis-webview.md#setadsblockrules12) can be used to set the options of the built-in rule. If **replace** is set to **true**, the built-in EasyList is not used. Otherwise, the custom rule and built-in rule work at the same time. If the built-in rule conflicts with the custom rule, you can use set **replace** to **true** to disable the built-in rule.
56
57The custom rule is a global configuration rule for the application that it takes effect for all **Web** components in the application processes. In addition, the rule is persistent that it continues to work when the application is restarted.
58
59## Disabling Ads Blocking on Pages with Specific Domain Names
60When the ads blocking of a **Web** component is enabled, you may want to disable it for some specific pages. In addition to the custom EasyList, you can also use [addAdsBlockDisallowedList()](../reference/apis-arkweb/js-apis-webview.md#addadsblockdisallowedlist12) provided by **AdsBlockManager** to disable the blocking.
61
62```ts
63// xxx.ets
64import { webview } from '@kit.ArkWeb';
65
66// This example demonstrates how to click a button to add an array of domain names to the disallowed list.
67@Entry
68@Component
69struct WebComponent {
70  main_url: string = 'https://www.example.com';
71  text_input_controller: TextInputController = new TextInputController();
72  controller: webview.WebviewController = new webview.WebviewController();
73
74  @State input_text: string = 'https://www.example.com';
75
76  build() {
77    Column() {
78      Row() {
79        Flex() {
80          TextInput({ text: this.input_text, placeholder: this.main_url, controller: this.text_input_controller})
81            .id("input_url")
82            .height(40)
83            .margin(5)
84            .borderColor(Color.Blue)
85            .onChange((value: string) => {
86              this.input_text = value;
87            })
88
89          Button({type: ButtonType.Capsule}) { Text("Go") }
90          .onClick(() => {
91            this.controller.loadUrl(this.input_text);
92          })
93
94          Button({type: ButtonType.Capsule}) { Text("addAdsBlockDisallowedList") }
95          .onClick(() => {
96            let arrDomainSuffixes = new Array<string>();
97            arrDomainSuffixes.push('example.com');
98            arrDomainSuffixes.push('abcdefg.cn');
99            webview.AdsBlockManager.addAdsBlockDisallowedList(arrDomainSuffixes);
100          })
101        }
102      }
103      Web({ src: this.main_url, controller: this.controller })
104        .onControllerAttached(()=>{
105          this.controller.enableAdsBlock(true);
106        })
107    }
108  }
109}
110```
111
112The domain names are set to **DisallowedList** of **AdsBlockManager** through **addAdsBlockDisallowedList()**. When the page is loaded, the system matches the suffix of the web page URL with the domain names in **DisallowedList**. If the matching is successful, ads blocking will be disabled on the page. In addition, [addAdsBlockAllowedList()](../reference/apis-arkweb/js-apis-webview.md#addadsblockallowedlist12) is provided to be used with **DisallowedList()** to set domain names and determine whether to enable ads blocking.
113
114**AdsBlockManager** caches two lists of domain names, including **DisallowedList** and **AllowList**. **DisallowedList** is used to disable ads blocking on web pages, and **AllowList** is used to enable ads blocking disabled by **DisallowedList**. **AllowList** has a higher priority. When a web page is loaded, the system matches the web page URL with **AllowList**. If the matching is successful, the ad blocking is enabled. Otherwise, the system continues to match the web page URL with **DisallowedList**. If the matching is successful, the ads blocking is disabled. If the accessed web page is neither list in **AllowList** nor in **DisallowedList**, the ads blocking for this web page is enabled by default.
115
116For example, if you want to enable ads blocking for the **news.example.com** and **sport.example.com** domain in an application, but need to disable ads blocking for other web pages under the **example.com** domain, you can use **addAdsBlockDisallowedList()** to add the **example.com** domain to **DisallowedList**, and then use **addAdsBlockAllowedList()** to add the **news.example.com** and **sport.example.com** domain to **AllowedList**.
117
118```ts
119// xxx.ets
120import { webview } from '@kit.ArkWeb';
121
122// In the following example, **addAdsBlockAllowedList()** and **addAdsBlockDisallowedList()** are used together to set the ads blocking for web pages.
123@Entry
124@Component
125struct WebComponent {
126  main_url: string = 'https://www.example.com';
127  text_input_controller: TextInputController = new TextInputController();
128  controller: webview.WebviewController = new webview.WebviewController();
129
130  @State input_text: string = 'https://www.example.com';
131
132  build() {
133    Column() {
134      Row() {
135        Flex() {
136          TextInput({ text: this.input_text, placeholder: this.main_url, controller: this.text_input_controller})
137            .id("input_url")
138            .height(40)
139            .margin(5)
140            .borderColor(Color.Blue)
141            .onChange((value: string) => {
142              this.input_text = value;
143            })
144
145          Button({type: ButtonType.Capsule}) { Text("Go") }
146          .onClick(() => {
147            this.controller.loadUrl(this.input_text);
148          })
149
150          Button({type: ButtonType.Capsule}) { Text("addAdsBlockAllowedList") }
151          .onClick(() => {
152            let arrDisallowDomainSuffixes = new Array<string>();
153            arrDisallowDomainSuffixes.push('example.com');
154            webview.AdsBlockManager.addAdsBlockDisallowedList(arrDisallowDomainSuffixes);
155
156            let arrAllowedDomainSuffixes = new Array<string>();
157            arrAllowedDomainSuffixes.push('news.example.com');
158            arrAllowedDomainSuffixes.push('sport.example.com');
159            webview.AdsBlockManager.addAdsBlockAllowedList(arrAllowedDomainSuffixes);
160          })
161        }
162      }
163      Web({ src: this.main_url, controller: this.controller })
164        .onControllerAttached(()=>{
165          this.controller.enableAdsBlock(true);
166        })
167    }
168  }
169}
170```
171
172Note that the **DisallowedList** and **AllowedList** of the **AdsBlockManager** are not persisted. Therefore, the lists are reset to empty when the application is restarted.
173If the ads blocking is not enabled through **enableAdsBlock()**, the preceding APIs do not take effect in the **Web** component.
174
175## Collecting Ads Blocking Information
176When ads blocking is enabled on the **Web** component, if any ad is blocked on the accessed web page, the [onAdsBlocked()](../reference/apis-arkweb/ts-basic-components-web.md#onadsblocked12) callback of the **Web** component notifies the application. You can collect blocking information and statistics as needed.
177
178```ts
179// xxx.ets
180import { webview } from '@kit.ArkWeb';
181
182
183@Entry
184@Component
185struct WebComponent {
186  @State totalAdsBlockCounts: number = 0;
187  controller: webview.WebviewController = new webview.WebviewController();
188
189  build() {
190    Column() {
191      Web({ src: 'https://www.example.com', controller: this.controller })
192        .onAdsBlocked((details: AdsBlockedDetails) => {
193          if (details) {
194            console.log(' Blocked ' + details.adsBlocked.length + ' in ' + details.url);
195            let adList: Array<string> = Array.from(new Set(details.adsBlocked));
196            this.totalAdsBlockCounts += adList.length;
197            console.log('Total blocked counts :' + this.totalAdsBlockCounts);
198          }
199        })
200    }
201  }
202}
203```
204
205To reduce the frequency of notifications and minimize the impact on the page loading process, only the first notification is made when the page is fully loaded. Subsequent blocking events are reported at intervals of 1 second, and no notifications are sent if there is no ad blocked.
206