• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Class (AdsBlockManager)
2
3Implements an **AdsBlockManager** instance to set custom ad blocking configurations in the **Web** components and disable the ad blocking feature for specific websites. Each application's **Web** components share an **AdsBlockManager** instance.
4
5> **NOTE**
6>
7> - The initial APIs of this module are supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version.
8>
9> - The initial APIs of this class are supported since API version 12.
10>
11> - You can preview how this component looks on a real device, but not in DevEco Studio Previewer.
12>
13> - Static methods must be used on the user interface (UI) thread.
14
15## Modules to Import
16
17```ts
18import { webview } from '@kit.ArkWeb';
19```
20
21## setAdsBlockRules<sup>12+</sup>
22
23static setAdsBlockRules(rulesFile: string, replace: boolean): void
24
25Sets a custom ad blocking rule file that conforms to the universal EasyList syntax in the **Web** components.
26
27> **NOTE**
28>
29> The ad blocking rules set by this API will be persistently stored after successful internal parsing; you do not need to set them again after the application is restarted.
30
31**System capability**: SystemCapability.Web.Webview.Core
32
33**Parameters**
34
35| Name    | Type  | Mandatory| Description                              |
36| ---------- | ------ | ---- | -------------------------------- |
37| rulesFile | string | Yes  | Path to the rule file that conforms to the universal EasyList syntax. The application needs to have read permission for this file.|
38| replace   | boolean | Yes  | Whether to replace the built-in default rules. The value **true** indicates that the built-in default rules will be forcibly replaced; **false** indicates that the custom rules will work alongside the built-in default rules.|
39
40**Error codes**
41
42> **NOTE**
43>
44> Since API version 18, exception 801 will be thrown when this API is called on a device that does not support ad blocking.
45
46For details about the error codes, see [Webview Error Codes](errorcode-webview.md).
47
48| ID| Error Message                 |
49| -------- | ----------------------- |
50|  401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. |
51|  801 | Capability not supported. |
52
53**Example**
54
55```ts
56// xxx.ets
57import { webview } from '@kit.ArkWeb';
58import { picker, fileUri } from '@kit.CoreFileKit';
59
60// This example demonstrates how to click a button to open an EasyList-compliant rule file through filepicker and set the file in the Web component.
61@Entry
62@Component
63struct WebComponent {
64  controller: webview.WebviewController = new webview.WebviewController();
65
66  build() {
67    Row() {
68      Flex() {
69        Button({ type: ButtonType.Capsule }) {
70          Text("setAdsBlockRules")
71        }
72        .onClick(() => {
73          try {
74            let documentSelectionOptions: ESObject = new picker.DocumentSelectOptions();
75            let documentPicker: ESObject = new picker.DocumentViewPicker();
76            documentPicker.select(documentSelectionOptions).then((documentSelectResult: ESObject) => {
77              if (documentSelectResult && documentSelectResult.length > 0) {
78                let fileRealPath = new fileUri.FileUri(documentSelectResult[0]);
79                console.info('DocumentViewPicker.select successfully, uri: ' + fileRealPath);
80                webview.AdsBlockManager.setAdsBlockRules(fileRealPath.path, true);
81              }
82            })
83          } catch (err) {
84            console.error('DocumentViewPicker.select failed with err:' + err);
85          }
86        })
87      }
88    }
89  }
90}
91```
92
93## addAdsBlockDisallowedList<sup>12+</sup>
94
95static addAdsBlockDisallowedList(domainSuffixes: Array\<string\>): void
96
97Adds an array of domain names to the disallowed list of this **AdsBlockManager** object. When the ad blocking feature is enabled, ad blocking for these websites will be disabled.
98
99> **NOTE**
100>
101> The domain name set by this API is not persistent; they need to be set again after the application is restarted.
102>
103> The ad blocking feature matches website URLs based on the suffix. For example, if the disallowed list contains **'example.com'** or **'www.example.com'**, then ad blocking will be disabled for sites **https://www.example.com** and **https://m.example.com**.
104
105**System capability**: SystemCapability.Web.Webview.Core
106
107**Parameters**
108
109| Name    | Type  | Mandatory| Description                              |
110| ---------- | ------ | ---- | -------------------------------- |
111| domainSuffixes | Array\<string\> | Yes  | Array of domain names, for example, ['example.com', 'abcd.efg.com'].|
112
113**Error codes**
114
115> **NOTE**
116>
117> Since API version 18, exception 801 will be thrown when this API is called on a device that does not support ad blocking.
118
119For details about the error codes, see [Webview Error Codes](errorcode-webview.md).
120
121| ID| Error Message                 |
122| -------- | ----------------------- |
123|  401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. |
124|  801 | Capability not supported. |
125
126**Example**
127
128```ts
129// xxx.ets
130import { webview } from '@kit.ArkWeb';
131
132// This example demonstrates how to click a button to add an array of domain names to the disallowed list.
133@Entry
134@Component
135struct WebComponent {
136  main_url: string = 'https://www.example.com';
137  text_input_controller: TextInputController = new TextInputController();
138  controller: webview.WebviewController = new webview.WebviewController();
139  @State input_text: string = 'https://www.example.com';
140
141  build() {
142    Column() {
143      Row() {
144        Flex() {
145          TextInput({ text: this.input_text, placeholder: this.main_url, controller: this.text_input_controller})
146            .id("input_url")
147            .height(40)
148            .margin(5)
149            .borderColor(Color.Blue)
150            .onChange((value: string) => {
151              this.input_text = value;
152            })
153
154          Button({type: ButtonType.Capsule}) { Text("Go") }
155          .onClick(() => {
156            this.controller.loadUrl(this.input_text);
157          })
158
159          Button({type: ButtonType.Capsule}) { Text("addAdsBlockDisallowedList") }
160          .onClick(() => {
161            let arrDomainSuffixes = new Array<string>();
162            arrDomainSuffixes.push('example.com');
163            arrDomainSuffixes.push('abcdefg.cn');
164            webview.AdsBlockManager.addAdsBlockDisallowedList(arrDomainSuffixes);
165          })
166        }
167      }
168      Web({ src: this.main_url, controller: this.controller })
169        .onControllerAttached(()=>{
170          this.controller.enableAdsBlock(true);
171        })
172    }
173  }
174}
175```
176
177## removeAdsBlockDisallowedList<sup>12+</sup>
178
179static removeAdsBlockDisallowedList(domainSuffixes: Array\<string\>): void
180
181Removes an array of domain names from the disallowed list of this **AdsBlockManager** object.
182
183> **NOTE**
184>
185> The domain name set by this API is not persistent; they need to be set again after the application is restarted. Removing an entry that does not exist does not trigger an exception.
186
187**System capability**: SystemCapability.Web.Webview.Core
188
189**Parameters**
190
191| Name    | Type  | Mandatory| Description                              |
192| ---------- | ------ | ---- | -------------------------------- |
193| domainSuffixes | Array\<string\> | Yes  | Array of domain names, for example, ['example.com', 'abcd.efg.com'].|
194
195**Error codes**
196
197> **NOTE**
198>
199> Since API version 18, exception 801 will be thrown when this API is called on a device that does not support ad blocking.
200
201For details about the error codes, see [Webview Error Codes](errorcode-webview.md).
202
203| ID| Error Message                 |
204| -------- | ----------------------- |
205|  401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. |
206|  801 | Capability not supported. |
207
208**Example**
209
210```ts
211// xxx.ets
212import { webview } from '@kit.ArkWeb';
213
214// This example demonstrates how to click a button to remove an array of domain names from the disallowed list.
215@Entry
216@Component
217struct WebComponent {
218  main_url: string = 'https://www.example.com';
219  text_input_controller: TextInputController = new TextInputController();
220  controller: webview.WebviewController = new webview.WebviewController();
221  @State input_text: string = 'https://www.example.com';
222
223  build() {
224    Column() {
225      Row() {
226        Flex() {
227          TextInput({ text: this.input_text, placeholder: this.main_url, controller: this.text_input_controller})
228            .id("input_url")
229            .height(40)
230            .margin(5)
231            .borderColor(Color.Blue)
232            .onChange((value: string) => {
233              this.input_text = value;
234            })
235
236          Button({type: ButtonType.Capsule}) { Text("Go") }
237          .onClick(() => {
238            this.controller.loadUrl(this.input_text);
239          })
240
241          Button({type: ButtonType.Capsule}) { Text("removeAdsBlockDisallowedList") }
242          .onClick(() => {
243            let arrDomainSuffixes = new Array<string>();
244            arrDomainSuffixes.push('example.com');
245            arrDomainSuffixes.push('abcdefg.cn');
246            webview.AdsBlockManager.removeAdsBlockDisallowedList(arrDomainSuffixes);
247          })
248        }
249      }
250      Web({ src: this.main_url, controller: this.controller })
251        .onControllerAttached(()=>{
252          this.controller.enableAdsBlock(true);
253        })
254    }
255  }
256}
257```
258
259## clearAdsBlockDisallowedList<sup>12+</sup>
260
261static clearAdsBlockDisallowedList(): void
262
263Clears the disallowed list of this **AdsBlockManager** object.
264
265**System capability**: SystemCapability.Web.Webview.Core
266
267**Error codes**
268
269> **NOTE**
270>
271> Since API version 18, exception 801 will be thrown when this API is called on a device that does not support ad blocking.
272
273For details about the error codes, see [Webview Error Codes](errorcode-webview.md).
274
275| ID| Error Message                 |
276| -------- | ----------------------- |
277|  801 | Capability not supported. |
278
279**Example**
280
281```ts
282// xxx.ets
283import { webview } from '@kit.ArkWeb';
284
285@Entry
286@Component
287struct WebComponent {
288  main_url: string = 'https://www.example.com';
289  text_input_controller: TextInputController = new TextInputController();
290  controller: webview.WebviewController = new webview.WebviewController();
291  @State input_text: string = 'https://www.example.com';
292
293  build() {
294    Column() {
295      Row() {
296        Flex() {
297          TextInput({ text: this.input_text, placeholder: this.main_url, controller: this.text_input_controller})
298            .id("input_url")
299            .height(40)
300            .margin(5)
301            .borderColor(Color.Blue)
302            .onChange((value: string) => {
303              this.input_text = value;
304            })
305
306          Button({type: ButtonType.Capsule}) { Text("Go") }
307          .onClick(() => {
308            this.controller.loadUrl(this.input_text);
309          })
310
311          Button({type: ButtonType.Capsule}) { Text("clearAdsBlockDisallowedList") }
312          .onClick(() => {
313            webview.AdsBlockManager.clearAdsBlockDisallowedList();
314          })
315        }
316      }
317      Web({ src: this.main_url, controller: this.controller })
318        .onControllerAttached(()=>{
319          this.controller.enableAdsBlock(true);
320        })
321    }
322  }
323}
324```
325
326## addAdsBlockAllowedList<sup>12+</sup>
327
328static addAdsBlockAllowedList(domainSuffixes: Array\<string\>): void
329
330Adds an array of domain names to the allowed list of this **AdsBlockManager** object. This API is typically used to re-enable ad blocking for certain websites that were previously added to the disallowed list.
331
332> **NOTE**
333>
334> The domain name set by this API is not persistent; they need to be set again after the application is restarted.
335>
336> The priority of the allowed list is higher than that of the disallowed list. For example, if the disallowed list includes **['example.com']**, all pages under the **example.com** domain will have their ad blocking disabled; to re-enable ad blocking for the subdomain **news.example.com**, you can use the **addAdsBlockAllowedList(['news.example.com'])** API.
337
338**System capability**: SystemCapability.Web.Webview.Core
339
340**Parameters**
341
342| Name    | Type  | Mandatory| Description                              |
343| ---------- | ------ | ---- | -------------------------------- |
344| domainSuffixes | Array\<string\> | Yes  | Array of domain names, for example, ['example.com', 'abcd.efg.com'].|
345
346**Error codes**
347
348> **NOTE**
349>
350> Since API version 18, exception 801 will be thrown when this API is called on a device that does not support ad blocking.
351
352For details about the error codes, see [Webview Error Codes](errorcode-webview.md).
353
354| ID| Error Message                 |
355| -------- | ----------------------- |
356|  401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. |
357|  801 | Capability not supported. |
358
359**Example**
360
361```ts
362// xxx.ets
363import { webview } from '@kit.ArkWeb';
364
365// This example demonstrates how to click a button to add an array of domain names to the disallowed list.
366@Entry
367@Component
368struct WebComponent {
369  main_url: string = 'https://www.example.com';
370  text_input_controller: TextInputController = new TextInputController();
371  controller: webview.WebviewController = new webview.WebviewController();
372  @State input_text: string = 'https://www.example.com';
373
374  build() {
375    Column() {
376      Row() {
377        Flex() {
378          TextInput({ text: this.input_text, placeholder: this.main_url, controller: this.text_input_controller})
379            .id("input_url")
380            .height(40)
381            .margin(5)
382            .borderColor(Color.Blue)
383            .onChange((value: string) => {
384              this.input_text = value;
385            })
386
387          Button({type: ButtonType.Capsule}) { Text("Go") }
388          .onClick(() => {
389            this.controller.loadUrl(this.input_text);
390          })
391
392          Button({type: ButtonType.Capsule}) { Text("addAdsBlockAllowedList") }
393          .onClick(() => {
394            let arrDisallowDomainSuffixes = new Array<string>();
395            arrDisallowDomainSuffixes.push('example.com');
396            webview.AdsBlockManager.addAdsBlockDisallowedList(arrDisallowDomainSuffixes);
397
398            let arrAllowedDomainSuffixes = new Array<string>();
399            arrAllowedDomainSuffixes.push('news.example.com');
400            webview.AdsBlockManager.addAdsBlockAllowedList(arrAllowedDomainSuffixes);
401          })
402        }
403      }
404      Web({ src: this.main_url, controller: this.controller })
405        .onControllerAttached(()=>{
406          this.controller.enableAdsBlock(true)
407        })
408    }
409  }
410}
411```
412
413## removeAdsBlockAllowedList<sup>12+</sup>
414
415static removeAdsBlockAllowedList(domainSuffixes: Array\<string\>): void
416
417Removes an array of domain names from the allowed list of this **AdsBlockManager** object.
418
419> **NOTE**
420>
421> The domain name set by this API is not persistent; they need to be set again after the application is restarted. Removing an entry that does not exist does not trigger an exception.
422
423**System capability**: SystemCapability.Web.Webview.Core
424
425**Parameters**
426
427| Name    | Type  | Mandatory| Description                              |
428| ---------- | ------ | ---- | -------------------------------- |
429| domainSuffixes | Array\<string\> | Yes  | Array of domain names, for example, ['example.com', 'abcd.efg.com'].|
430
431**Error codes**
432
433> **NOTE**
434>
435> Since API version 18, exception 801 will be thrown when this API is called on a device that does not support ad blocking.
436
437For details about the error codes, see [Webview Error Codes](errorcode-webview.md).
438
439| ID| Error Message                 |
440| -------- | ----------------------- |
441|  401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. |
442|  801 | Capability not supported. |
443
444**Example**
445
446```ts
447// xxx.ets
448import { webview } from '@kit.ArkWeb';
449
450// This example demonstrates how to click a button to remove an array of domain names from the disallowed list.
451@Entry
452@Component
453struct WebComponent {
454  main_url: string = 'https://www.example.com';
455  text_input_controller: TextInputController = new TextInputController();
456  controller: webview.WebviewController = new webview.WebviewController();
457  @State input_text: string = 'https://www.example.com';
458
459  build() {
460    Column() {
461      Row() {
462        Flex() {
463          TextInput({ text: this.input_text, placeholder: this.main_url, controller: this.text_input_controller})
464            .id("input_url")
465            .height(40)
466            .margin(5)
467            .borderColor(Color.Blue)
468            .onChange((value: string) => {
469              this.input_text = value;
470            })
471
472          Button({type: ButtonType.Capsule}) { Text("Go") }
473          .onClick(() => {
474            this.controller.loadUrl(this.input_text);
475          })
476
477          Button({type: ButtonType.Capsule}) { Text("removeAdsBlockAllowedList") }
478          .onClick(() => {
479            let arrDomainSuffixes = new Array<string>();
480            arrDomainSuffixes.push('example.com');
481            arrDomainSuffixes.push('abcdefg.cn');
482            webview.AdsBlockManager.removeAdsBlockAllowedList(arrDomainSuffixes);
483          })
484        }
485      }
486      Web({ src: this.main_url, controller: this.controller })
487        .onControllerAttached(()=>{
488          this.controller.enableAdsBlock(true);
489        })
490    }
491  }
492}
493```
494
495## clearAdsBlockAllowedList<sup>12+</sup>
496
497static clearAdsBlockAllowedList(): void
498
499Clears the allowed list of this **AdsBlockManager** object.
500
501**System capability**: SystemCapability.Web.Webview.Core
502
503**Error codes**
504
505> **NOTE**
506>
507> Since API version 18, exception 801 will be thrown when this API is called on a device that does not support ad blocking.
508
509For details about the error codes, see [Webview Error Codes](errorcode-webview.md).
510
511| ID| Error Message                 |
512| -------- | ----------------------- |
513|  801 | Capability not supported. |
514
515**Example**
516
517```ts
518// xxx.ets
519import { webview } from '@kit.ArkWeb';
520
521@Entry
522@Component
523struct WebComponent {
524  main_url: string = 'https://www.example.com';
525  text_input_controller: TextInputController = new TextInputController();
526  controller: webview.WebviewController = new webview.WebviewController();
527  @State input_text: string = 'https://www.example.com';
528
529
530  build() {
531    Column() {
532      Row() {
533        Flex() {
534          TextInput({ text: this.input_text, placeholder: this.main_url, controller: this.text_input_controller})
535            .id("input_url")
536            .height(40)
537            .margin(5)
538            .borderColor(Color.Blue)
539            .onChange((value: string) => {
540              this.input_text = value;
541            })
542
543          Button({type: ButtonType.Capsule}) { Text("Go") }
544          .onClick(() => {
545            this.controller.loadUrl(this.input_text);
546          })
547
548          Button({type: ButtonType.Capsule}) { Text("clearAdsBlockAllowedList") }
549          .onClick(() => {
550            webview.AdsBlockManager.clearAdsBlockAllowedList();
551          })
552        }
553      }
554      Web({ src: this.main_url, controller: this.controller })
555      .onControllerAttached(()=>{
556        this.controller.enableAdsBlock(true);
557      })
558    }
559  }
560}
561```
562