• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.advertising (Ads Service Framework)
2
3The advertising module provides APIs for requesting and displaying ads.
4
5> **NOTE**
6> The initial APIs of this module are supported since API version 11. Newly added APIs will be marked with a superscript to indicate their earliest API version.
7
8## Modules to Import
9
10```ts
11import { advertising } from '@kit.AdsKit';
12```
13
14## advertising.showAd
15
16showAd(ad: Advertisement, options: AdDisplayOptions, context?: common.UIAbilityContext): void
17
18Shows a full-screen ad.
19
20**Atomic service API**: This API can be used in atomic services since API version 12.
21
22**System capability**: SystemCapability.Advertising.Ads
23
24**Parameters**
25
26| Name    | Type                                                                                          | Mandatory| Description                                                   |
27|---------|----------------------------------------------------------------------------------------------|----|-------------------------------------------------------|
28| ad      | [Advertisement](#advertisement)                                                              | Yes | Ad object.                                                |
29| options | [AdDisplayOptions](#addisplayoptions)                                                        | Yes | Ad display parameters.                                              |
30| context | common.[UIAbilityContext](../apis-ability-kit/js-apis-inner-application-uiAbilityContext.md) | No | Context of the UIAbility. If this parameter is not set, the value is obtained from @ohos.app.ability.common.|
31
32**Error codes**
33
34For details about the following error codes, see [Ads Service Framework Error Codes](errorcode-ads.md).
35
36| ID   | Error Message                                                                                   |
37|----------|-----------------------------------------------------------------------------------------|
38| 401      | Invalid input parameter. Possible causes: 1. Mandatory parameters are left unspecified. |
39| 21800001 | System internal error.                                                                  |
40| 21800004 | Failed to display the ad.                                                               |
41
42**Example**
43
44```ts
45import { common } from '@kit.AbilityKit';
46import { advertising } from '@kit.AdsKit';
47import { hilog } from '@kit.PerformanceAnalysisKit';
48
49@Entry
50@Component
51struct Index {
52  private context: common.UIAbilityContext = this.getUIContext().getHostContext() as common.UIAbilityContext;
53  // Requested ad content.
54  private ad?: advertising.Advertisement;
55  // Ad display parameters.
56  private adDisplayOptions: advertising.AdDisplayOptions = {
57    // Whether to mute the ad. By default, the ad is not muted.
58    mute: false
59  }
60
61  build() {
62    Column() {
63      Button('showAd')
64        .onClick(() => {
65          try {
66            // Show the ad.
67            advertising.showAd(this.ad, this.adDisplayOptions, this.context);
68          } catch (err) {
69            hilog.error(0x0000, 'testTag', `Fail to show ad. Code is ${err.code}, message is ${err.message}`);
70          }
71        });
72    }
73    .width('100%')
74    .height('100%')
75  }
76}
77```
78
79## advertising.getAdRequestBody<sup>12+</sup>
80
81getAdRequestBody(adParams: AdRequestParams[], adOptions: AdOptions): Promise&lt;string&gt;
82
83Obtains the body of an ad request. This API uses a promise to return the result. (This API is available only for some preset applications.)
84
85**System capability**: SystemCapability.Advertising.Ads
86
87**Parameters**
88
89| Name      | Type                                   | Mandatory| Description                             |
90|-----------|---------------------------------------|----|---------------------------------|
91| adParams  | [AdRequestParams[]](#adrequestparams) | Yes | Ad request parameters.<br> - The **adid** parameter is optional.|
92| adOptions | [AdOptions](#adoptions)               | Yes | Ad configuration.                          |
93
94**Return value**
95
96| Type                   | Description                    |
97|-----------------------|------------------------|
98| Promise&lt;string&gt; | Promise used to return the ad data of the string type.|
99
100**Error codes**
101
102For details about the following error codes, see [Ads Service Framework Error Codes](errorcode-ads.md).
103
104| ID   | Error Message                                                                                                                                                   |
105|----------|---------------------------------------------------------------------------------------------------------------------------------------------------------|
106| 401      | Invalid input parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. |
107| 801      | Device not supported.                                                                                                                                   |
108| 21800001 | System internal error.                                                                                                                                  |
109
110**Example**
111
112```ts
113import { advertising } from '@kit.AdsKit';
114import { Prompt } from '@kit.ArkUI';
115import { BusinessError } from '@kit.BasicServicesKit';
116import { hilog } from '@kit.PerformanceAnalysisKit';
117
118function getAdRequestBody(): void {
119  const adRequestParamsArray: advertising.AdRequestParams[] = [];
120  const adRequestParams: advertising.AdRequestParams = {
121    adId: 'testu7m3hc4gvm',
122    adType: 3,
123    adCount: 2,
124    adWidth: 100,
125    adHeight: 100
126  };
127  adRequestParamsArray.push(adRequestParams);
128  const adOptions: advertising.AdOptions = {
129    // Set whether to request only non-personalized ads. 0: to request personalized ads and non-personalized ads; 1: to request only non-personalized ads. If this parameter is left blank, the service logic prevails.
130    nonPersonalizedAd: 0,
131    // Specify whether you want your ad content to be treated as COPPA-compliant. The following values are available: -1 (default value): uncertain; 0: no; 1: yes.
132    tagForChildProtection: -1,
133    // Specify whether you want the ad request to be processed in a way that meets the GDPR for users in the EEA under the age of consent. The following values are available: -1 (default value): uncertain; 0: no; 1: yes.
134    tagForUnderAgeOfPromise: -1,
135    // Maximum ad content rating. **W**: aged 3 and up; **PI**: aged 7 and up, under parental guidance; **J**: teenagers aged 12 and up; **A**: adults aged 16 or 18 and up.
136    adContentClassification: 'A'
137  };
138  advertising.getAdRequestBody(adRequestParamsArray, adOptions).then((data) => {
139    hilog.info(0x0000, 'testTag', `Succeeded in getting ad request body. Data is ${JSON.stringify(data)}`);
140    Prompt.showToast({
141      message: data,
142      duration: 1000
143    });
144  }).catch((error: BusinessError) => {
145    hilog.error(0x0000, 'testTag', `Fail to get ad request body. Code is ${error.code}, message is ${error.message}`);
146    Prompt.showToast({
147      message: error.code.toString() + ',' + error.message,
148      duration: 1000
149    });
150  })
151}
152```
153
154## advertising.parseAdResponse<sup>12+</sup>
155
156parseAdResponse(adResponse: string, listener: MultiSlotsAdLoadListener, context: common.UIAbilityContext): void
157
158Parses and processes the ad response body. (This API is available only for some preset applications.)
159
160**System capability**: SystemCapability.Advertising.Ads
161
162**Parameters**
163
164| Name       | Type                                                                                          | Mandatory| Description              |
165|------------|----------------------------------------------------------------------------------------------|----|------------------|
166| adResponse | string                                                                                       | Yes | Ad request parameters.         |
167| listener   | [MultiSlotsAdLoadListener](#multislotsadloadlistener)                                        | Yes | Ad request callback.       |
168| context    | common.[UIAbilityContext](../apis-ability-kit/js-apis-inner-application-uiAbilityContext.md) | Yes | UIAbility context.|
169
170**Error codes**
171
172For details about the following error codes, see [Ads Service Framework Error Codes](errorcode-ads.md).
173
174| ID   | Error Message                                                                                                                                                   |
175|----------|---------------------------------------------------------------------------------------------------------------------------------------------------------|
176| 401      | Invalid input parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. |
177| 801      | Device not supported.                                                                                                                                   |
178| 21800001 | System internal error.                                                                                                                                  |
179| 21800005 | Failed to parse the ad response.                                                                                                                        |
180
181**Example**
182
183For details about how to obtain the context, see [Obtaining the Context of UIAbility](../apis-ability-kit/js-apis-inner-application-uiAbilityContext.md).
184
185```ts
186import { common } from '@kit.AbilityKit';
187import { advertising } from '@kit.AdsKit';
188import { hilog } from '@kit.PerformanceAnalysisKit';
189
190function parseAdResponse(adResponse: string, context: common.UIAbilityContext): void {
191  // Listen for the ad parsing callback.
192  const multiSlotsAdLoaderListener: advertising.MultiSlotsAdLoadListener = {
193    // Called when ad parsing fails.
194    onAdLoadFailure: (errorCode: number, errorMsg: string) => {
195      hilog.error(0x0000, 'testTag', `Fail to load multiSlots ad. Code is ${errorCode}, message is ${errorMsg}`);
196    },
197    // Called when ad parsing is successful.
198    onAdLoadSuccess: (ads: Map<string, Array<advertising.Advertisement>>) => {
199      hilog.info(0x0000, 'testTag', 'Succeed in loading multiSlots ad');
200      // Save the parsed ad content as an array for display.
201      const returnAds: Array<advertising.Advertisement> = [];
202      ads.forEach((adsArray) => returnAds.push(...adsArray));
203    }
204  };
205  // Call the API to parse the response body.
206  hilog.info(0x0000, 'testTag', 'Start to parse ad response');
207  advertising.parseAdResponse(adResponse, multiSlotsAdLoaderListener, context);
208}
209```
210
211## advertising.registerWebAdInterface<sup>12+</sup>
212
213registerWebAdInterface(controller: web_webview.WebviewController, context: common.UIAbilityContext): void
214
215Injects an ad JavaScript object to the **Web** component. (This API is available only for some preset applications.)
216
217**Atomic service API**: This API can be used in atomic services since API version 12.
218
219**System capability**: SystemCapability.Advertising.Ads
220
221**Parameters**
222
223| Name       | Type                                                                                          | Mandatory| Description              |
224|------------|----------------------------------------------------------------------------------------------|----|------------------|
225| controller | web_webview.[WebviewController](../apis-arkweb/js-apis-webview.md#webviewcontroller)         | Yes | Controller of the **Web** component.       |
226| context    | common.[UIAbilityContext](../apis-ability-kit/js-apis-inner-application-uiAbilityContext.md) | Yes | UIAbility context.|
227
228**Error codes**
229
230For details about the following error codes, see [Ads Service Framework Error Codes](errorcode-ads.md).
231
232| ID   | Error Message                                                                                 |
233|----------|---------------------------------------------------------------------------------------|
234| 401      | Invalid input parameter. Possible causes: 1.Mandatory parameters are left unspecified |
235| 21800001 | System internal error.                                                                |
236
237**Example**
238
239```ts
240import { common } from '@kit.AbilityKit';
241import { advertising } from '@kit.AdsKit';
242import { webview } from '@kit.ArkWeb';
243import { hilog } from '@kit.PerformanceAnalysisKit';
244
245@Entry
246@Component
247struct Index {
248  private webController: webview.WebviewController = new webview.WebviewController();
249  private context: common.UIAbilityContext = this.getUIContext().getHostContext() as common.UIAbilityContext;
250
251  build() {
252    Column() {
253      Button('registerWebAdInterface')
254        .onClick(() => {
255          try {
256            advertising.registerWebAdInterface(this.webController, this.context);
257          } catch (err) {
258            hilog.error(0x0000, 'testTag', `Fail to register web ad interface. Code is ${err.code}, message is ${err.message}`);
259          }
260        })
261
262      Web({
263        src: 'www.example.com',
264        controller: this.webController
265      })
266        .width("100%")
267        .height("100%")
268    }
269  }
270}
271```
272
273## advertising.registerWebAdInterface<sup>16+</sup>
274
275registerWebAdInterface(controller: web_webview.WebviewController, context: common.UIAbilityContext, needRefresh: boolean): void
276
277Injects an ad JavaScript object to the **Web** component. (This API is available only for some preset applications.)
278
279**Atomic service API**: This API can be used in atomic services since API version 16.
280
281**System capability**: SystemCapability.Advertising.Ads
282
283**Parameters**
284
285| Name        | Type                                                                                          | Mandatory| Description                            |
286|-------------|----------------------------------------------------------------------------------------------|----|--------------------------------|
287| controller  | web_webview.[WebviewController](../apis-arkweb/js-apis-webview.md#webviewcontroller)         | Yes | Controller of the **Web** component.                     |
288| context     | common.[UIAbilityContext](../apis-ability-kit/js-apis-inner-application-uiAbilityContext.md) | Yes | UIAbility context.              |
289| needRefresh | boolean                                                                                      | Yes | Whether a page needs to be refreshed. (The value **true** means that a page needs to be refreshed; the value **false** means the opposite.)|
290
291**Error codes**
292
293For details about the following error codes, see [Ads Service Framework Error Codes](errorcode-ads.md).
294
295| ID   | Error Message                                                                                |
296|----------|--------------------------------------------------------------------------------------|
297| 401      | Invalid input parameter. Possible causes: Mandatory parameters are left unspecified. |
298| 21800001 | operation javascriptRegister error.                                                  |
299
300**Example**
301
302```ts
303import { common } from '@kit.AbilityKit';
304import { advertising } from '@kit.AdsKit';
305import { webview } from '@kit.ArkWeb';
306import { hilog } from '@kit.PerformanceAnalysisKit';
307
308@Entry
309@Component
310struct Index {
311  private webController: webview.WebviewController = new webview.WebviewController();
312  private context: common.UIAbilityContext = this.getUIContext().getHostContext() as common.UIAbilityContext;
313
314  build() {
315    Column() {
316      Button('registerWebAdInterface')
317        .onClick(() => {
318          try {
319            advertising.registerWebAdInterface(this.webController, this.context, true);
320          } catch (err) {
321            hilog.error(0x0000, 'testTag', `Fail to register web ad interface. Code is ${err.code}, message is ${err.message}`);
322          }
323        })
324
325      Web({
326        src: 'www.example.com',
327        controller: this.webController
328      })
329        .width("100%")
330        .height("100%")
331    }
332  }
333}
334```
335
336## advertising.deleteWebAdInterface<sup>16+</sup>
337
338deleteWebAdInterface(controller: web_webview.WebviewController, needRefresh: boolean): void
339
340Deletes the ad JavaScript object injected through **registerWebAdInterface**. (This API is available only to some preset applications.)
341
342**Atomic service API**: This API can be used in atomic services since API version 16.
343
344**System capability**: SystemCapability.Advertising.Ads
345
346**Parameters**
347
348| Name        | Type                                                                                  | Mandatory| Description                            |
349|-------------|--------------------------------------------------------------------------------------|----|--------------------------------|
350| controller  | web_webview.[WebviewController](../apis-arkweb/js-apis-webview.md#webviewcontroller) | Yes | Controller of the **Web** component.                     |
351| needRefresh | boolean                                                                              | Yes | Whether a page needs to be refreshed. (The value **true** means that a page needs to be refreshed; the value **false** means the opposite.)|
352
353**Error codes**
354
355For details about the following error codes, see [Ads Service Framework Error Codes](errorcode-ads.md).
356
357| ID   | Error Message                                                                                |
358|----------|--------------------------------------------------------------------------------------|
359| 401      | Invalid input parameter. Possible causes: Mandatory parameters are left unspecified. |
360| 21800001 | operation javascriptRegister error.                                                  |
361
362**Example**
363
364```ts
365import { advertising } from '@kit.AdsKit';
366import { webview } from '@kit.ArkWeb';
367import { hilog } from '@kit.PerformanceAnalysisKit';
368
369@Entry
370@Component
371struct Index {
372  private webController: webview.WebviewController = new webview.WebviewController();
373
374  build() {
375    Column() {
376      Button('deleteWebAdInterface')
377        .onClick(() => {
378          try {
379            advertising.deleteWebAdInterface(this.webController, true);
380          } catch (err) {
381            hilog.error(0x0000, 'testTag', `Fail to delete web ad interface. Code is ${err.code}, message is ${err.message}`);
382          }
383        })
384
385      Web({
386        src: 'www.example.com',
387        controller: this.webController,
388      })
389        .width('100%')
390        .height('100%')
391    }
392  }
393}
394```
395
396## AdLoader
397
398Provides the APIs for loading ads.
399
400**Atomic service API**: This API can be used in atomic services since API version 12.
401
402**System capability**: SystemCapability.Advertising.Ads
403
404### constructor
405
406constructor(context: common.Context)
407
408Constructor.
409
410**Atomic service API**: This API can be used in atomic services since API version 12.
411
412**System capability**: SystemCapability.Advertising.Ads
413
414**Parameters**
415
416| Name    | Type                                                                        | Mandatory| Description                        |
417|---------|----------------------------------------------------------------------------|----|----------------------------|
418| context | common.[Context](../apis-ability-kit/js-apis-inner-application-context.md) | Yes | Context of the ability or application.|
419
420**Example**
421
422For details about how to obtain the context, see [Context](../../application-models/application-context-stage.md#overview).
423
424```ts
425import { advertising } from '@kit.AdsKit';
426import { common } from '@kit.AbilityKit';
427
428function createConstructor(context: common.Context): void {
429  const adLoader: advertising.AdLoader = new advertising.AdLoader(context);
430}
431```
432
433### loadAd
434
435loadAd(adParam: AdRequestParams, adOptions: AdOptions, listener: AdLoadListener): void
436
437Loads an ad.
438
439**Atomic service API**: This API can be used in atomic services since API version 12.
440
441**System capability**: SystemCapability.Advertising.Ads
442
443**Parameters**
444
445| Name      | Type                                 | Mandatory| Description       |
446|-----------|-------------------------------------|----|-----------|
447| adParam   | [AdRequestParams](#adrequestparams) | Yes | Ad request parameters.  |
448| adOptions | [AdOptions](#adoptions)             | Yes | Ad configuration.    |
449| listener  | [AdLoadListener](#adloadlistener)   | Yes | Ad request callback.|
450
451**Error codes**
452
453For details about the following error codes, see [Ads Service Framework Error Codes](errorcode-ads.md).
454
455| ID   | Error Message                                                                                                                                                  |
456|----------|--------------------------------------------------------------------------------------------------------------------------------------------------------|
457| 401      | Invalid input parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. |
458| 801      | Device not supported.                                                                                                                                  |
459| 21800001 | System internal error.                                                                                                                                 |
460| 21800003 | Failed to load the ad request.                                                                                                                         |
461
462**Example**
463
464For details about how to obtain the context, see [Context](../../application-models/application-context-stage.md#overview).
465
466```ts
467import { common } from '@kit.AbilityKit';
468import { advertising } from '@kit.AdsKit';
469import { hilog } from '@kit.PerformanceAnalysisKit';
470
471function loadAd(context: common.Context): void {
472  const adRequestParams: advertising.AdRequestParams = {
473    // Ad type.
474    adType: 3,
475    // Ad ID.
476    adId: 'testy63txaom86'
477  };
478  const adOptions: advertising.AdOptions = {
479    // Optional custom parameter, which specifies whether to allow ad asset download using mobile data. The options are 0 (no) and 1 (yes). If this parameter is not set, the advertiser's setting will be used.
480    allowMobileTraffic: 0,
481    // Specify whether you want your ad content to be treated as COPPA-compliant. The following values are available: -1 (default value): uncertain; 0: no; 1: yes.
482    tagForChildProtection: -1,
483    // Specify whether you want the ad request to be processed in a way that meets the GDPR for users in the EEA under the age of consent. The following values are available: -1 (default value): uncertain; 0: no; 1: yes.
484    tagForUnderAgeOfPromise: -1,
485    // Maximum ad content rating. W: aged 3 and up; PI: aged 7 and up, under parental guidance; J: teenagers aged 12 and up; A: adults aged 16 or 18 and up.
486    adContentClassification: 'A'
487  };
488  // Listener for the ad loading status.
489  const adLoaderListener: advertising.AdLoadListener = {
490    // Called when the ad request fails.
491    onAdLoadFailure: (errorCode: number, errorMsg: string) => {
492      hilog.error(0x0000, 'testTag', `Fail to load ad. Code is ${errorCode}, message is ${errorMsg}`);
493    },
494    // Called when the ad request is successful.
495    onAdLoadSuccess: (ads: Array<advertising.Advertisement>) => {
496      hilog.info(0x0000, 'testTag', 'Succeed in loading ad');
497      // Save the requested ad content for display.
498      const returnAds = ads;
499    }
500  };
501  // Create an AdLoader object.
502  const adLoader: advertising.AdLoader = new advertising.AdLoader(context);
503  // Load the ad.
504  hilog.info(0x0000, 'testTag', 'Start to load ad');
505  adLoader.loadAd(adRequestParams, adOptions, adLoaderListener);
506}
507```
508
509### loadAdWithMultiSlots
510
511loadAdWithMultiSlots(adParams: AdRequestParams[], adOptions: AdOptions, listener: MultiSlotsAdLoadListener): void
512
513Loads multiple ads.
514
515**Atomic service API**: This API can be used in atomic services since API version 12.
516
517**System capability**: SystemCapability.Advertising.Ads
518
519**Parameters**
520
521| Name      | Type                                                   | Mandatory| Description       |
522|-----------|-------------------------------------------------------|----|-----------|
523| adParams  | [AdRequestParams](#adrequestparams)[]                 | Yes | Ad request parameters.  |
524| adOptions | [AdOptions](#adoptions)                               | Yes | Ad configuration.    |
525| listener  | [MultiSlotsAdLoadListener](#multislotsadloadlistener) | Yes | Ad request callback.|
526
527**Error codes**
528
529For details about the following error codes, see [Ads Service Framework Error Codes](errorcode-ads.md).
530
531| ID   | Error Message                                                                                                                                                  |
532|----------|--------------------------------------------------------------------------------------------------------------------------------------------------------|
533| 401      | Invalid input parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. |
534| 801      | Device not supported.                                                                                                                                  |
535| 21800001 | System internal error.                                                                                                                                 |
536| 21800003 | Failed to load the ad request.                                                                                                                         |
537
538**Example**
539
540For details about how to obtain the context, see [Context](../../application-models/application-context-stage.md#overview).
541
542```ts
543import { common } from '@kit.AbilityKit';
544import { advertising } from '@kit.AdsKit';
545import { hilog } from '@kit.PerformanceAnalysisKit';
546
547function loadAdWithMultiSlots(context: common.Context): void {
548  const adRequestParamsArray: advertising.AdRequestParams[] = [
549    {
550      // Ad type.
551      adType: 3,
552      // Ad ID.
553      adId: 'testy63txaom86'
554    },
555    {
556      // Ad type.
557      adType: 3,
558      // Ad ID.
559      adId: 'testy63txaom86'
560    }
561  ];
562  const adOptions: advertising.AdOptions = {
563    // Optional custom parameter, which specifies whether to allow ad asset download using mobile data. The options are 0 (no) and 1 (yes). If this parameter is not set, the advertiser's setting will be used.
564    allowMobileTraffic: 0,
565    // Specify whether you want your ad content to be treated as COPPA-compliant. The following values are available: -1 (default value): uncertain; 0: no; 1: yes.
566    tagForChildProtection: -1,
567    // Specify whether you want the ad request to be processed in a way that meets the GDPR for users in the EEA under the age of consent. The following values are available: -1 (default value): uncertain; 0: no; 1: yes.
568    tagForUnderAgeOfPromise: -1,
569    // Maximum ad content rating. W: aged 3 and up; PI: aged 7 and up, under parental guidance; J: teenagers aged 12 and up; A: adults aged 16 or 18 and up.
570    adContentClassification: 'A'
571  };
572  // Listener for the ad loading status.
573  const multiSlotsAdLoaderListener: advertising.MultiSlotsAdLoadListener = {
574    // Called when the ad request fails.
575    onAdLoadFailure: (errorCode: number, errorMsg: string) => {
576      hilog.error(0x0000, 'testTag', `Fail to load multiSlots ad. Code is ${errorCode}, message is ${errorMsg}`);
577    },
578    // Called when the ad request is successful.
579    onAdLoadSuccess: (ads: Map<string, Array<advertising.Advertisement>>) => {
580      hilog.info(0x0000, 'testTag', 'Succeed in loading multiSlots ad');
581      // Save the requested ad content for display.
582      const returnAds: Array<advertising.Advertisement> = [];
583      ads.forEach((adsArray) => returnAds.push(...adsArray));
584    }
585  };
586  // Create an AdLoader object.
587  const adLoader: advertising.AdLoader = new advertising.AdLoader(context);
588  // Load the ad.
589  hilog.info(0x0000, 'testTag', 'Start to load multiSlots ad');
590  adLoader.loadAdWithMultiSlots(adRequestParamsArray, adOptions, multiSlotsAdLoaderListener);
591}
592```
593
594## AdLoadListener
595
596Enumerates the callbacks used for the request for loading an ad.
597
598**Atomic service API**: This API can be used in atomic services since API version 12.
599
600**System capability**: SystemCapability.Advertising.Ads
601
602### onAdLoadFailure
603
604onAdLoadFailure(errorCode: number, errorMsg: string): void
605
606Called when an ad request fails.
607
608**Atomic service API**: This API can be used in atomic services since API version 12.
609
610**System capability**: SystemCapability.Advertising.Ads
611
612**Parameters**
613
614| Name      | Type    | Mandatory| Description          |
615|-----------|--------|----|--------------|
616| errorCode | number | Yes | Result code indicating the ad request failure. |
617| errorMsg  | string | Yes | Error message about the ad request failure.|
618
619### onAdLoadSuccess
620
621onAdLoadSuccess(ads: Array&lt;Advertisement&gt;): void
622
623Called when an ad request is successful.
624
625**Atomic service API**: This API can be used in atomic services since API version 12.
626
627**System capability**: SystemCapability.Advertising.Ads
628
629**Parameters**
630
631| Name| Type                                          | Mandatory| Description   |
632|-----|----------------------------------------------|----|-------|
633| ads | Array&lt;[Advertisement](#advertisement)&gt; | Yes | Ad data.|
634
635**Example**
636
637```ts
638import { advertising } from '@kit.AdsKit';
639
640const adLoaderListener: advertising.AdLoadListener = {
641  onAdLoadFailure: (errorCode: number, errorMsg: string) => {
642  },
643  onAdLoadSuccess: (ads: Array<advertising.Advertisement>) => {
644  }
645}
646```
647
648## MultiSlotsAdLoadListener
649
650Enumerates the callbacks used for the request for loading multiple ads.
651
652**Atomic service API**: This API can be used in atomic services since API version 12.
653
654**System capability**: SystemCapability.Advertising.Ads
655
656### onAdLoadFailure
657
658onAdLoadFailure(errorCode: number, errorMsg: string): void
659
660Called when a request for loading multiple ads fails.
661
662**Atomic service API**: This API can be used in atomic services since API version 12.
663
664**System capability**: SystemCapability.Advertising.Ads
665
666**Parameters**
667
668| Name      | Type    | Mandatory| Description          |
669|-----------|--------|----|--------------|
670| errorCode | number | Yes | Result code indicating the ad request failure. |
671| errorMsg  | string | Yes | Error message about the ad request failure.|
672
673### onAdLoadSuccess
674
675onAdLoadSuccess(adsMap: Map&lt;string, Array&lt;Advertisement&gt;&gt;): void
676
677Called when a request for loading multiple ads is successful.
678
679**Atomic service API**: This API can be used in atomic services since API version 12.
680
681**System capability**: SystemCapability.Advertising.Ads
682
683**Parameters**
684
685| Name   | Type                                                             | Mandatory| Description   |
686|--------|-----------------------------------------------------------------|----|-------|
687| adsMap | Map&lt;string, Array&lt;[Advertisement](#advertisement)&gt;&gt; | Yes | Ad data.|
688
689**Example**
690
691```ts
692import { advertising } from '@kit.AdsKit';
693
694const multiSlotsAdLoadListener: advertising.MultiSlotsAdLoadListener = {
695  onAdLoadFailure: (errorCode: number, errorMsg: string) => {
696  },
697  onAdLoadSuccess: (adsMap: Map<string, Array<advertising.Advertisement>>) => {
698  }
699}
700```
701
702## AdInteractionListener
703
704Defines the ad status change callback.
705
706**Atomic service API**: This API can be used in atomic services since API version 12.
707
708**System capability**: SystemCapability.Advertising.Ads
709
710### onStatusChanged
711
712onStatusChanged(status: string, ad: Advertisement, data: string)
713
714Called when the ad display status changes.
715
716**Atomic service API**: This API can be used in atomic services since API version 12.
717
718**System capability**: SystemCapability.Advertising.Ads
719
720**Parameters**
721
722| Name   | Type                             | Mandatory| Description                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
723|--------|---------------------------------|----|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
724| status | string                          | Yes | **status**: ad display status, which can be<br>**onAdOpen**, **onAdClose**, **onAdClick**, **onVideoPlayBegin**, **onVideoPlayEnd**, **onAdLoad**, **onAdFail**, **onMediaProgress**, **onMediaStart**, **onMediaPause**, **onMediaStop**, **onMediaComplete**, **onMediaError**, **onLandscape**, **onPortrait**, **onAdReward**, **onMediaCountDown**, or **onBackClicked**.|
725| ad     | [Advertisement](#advertisement) | Yes | Content of the ad.                                                                                                                                                                                                                                                                                                                                                                                                                                            |
726| data   | string                          | Yes | Extended information.                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
727
728**Example**
729
730```ts
731import { advertising } from '@kit.AdsKit';
732
733const adInteractionListener: advertising.AdInteractionListener = {
734  onStatusChanged: (status: string, ad: advertising.Advertisement, data: string) => {
735
736  }
737}
738```
739
740## AdOptions
741
742Defines the ad configuration.
743
744**Atomic service API**: This API can be used in atomic services since API version 12.
745
746**System capability**: SystemCapability.Advertising.Ads
747
748| Name                     | Type                                      | Read-Only| Optional| Description                                                                                                                                                                                                                                                                                                                                                                                                      |
749|-------------------------|------------------------------------------|----|----|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
750| tagForChildProtection   | number                                   | No | Yes | Tag for child protection, which specifies whether you want the ad content to be treated as COPPA-compliant.<br>- **-1** (default value): uncertain. You do not want to specify whether the ad content needs to be treated as COPPA-compliant.<br>- **0**: No. You do not want the ad content to be treated as COPPA-compliant.<br>- **1**: Yes. You want the ad content to be treated as COPPA-compliant.<br>                                                                                                                                                                                                                                                                                                            |
751| adContentClassification | string                                   | No | Yes | Maximum ad content rating.<br>- **W**: ages 3+, all audiences.<br>- **PI**: ages 7+, audiences under parental instruction.<br>- **J**: ages 12+, teenagers.<br>- **A**: ages 16+/18+, adults.<br>If this parameter is left blank, the service logic prevails.                                                                                                                                                                                                                                                                                                    |
752| nonPersonalizedAd       | number                                   | No | Yes | Whether to request only non-personalized ads.<br>- **0**: request for personalized and non-personalized ads.<br>- **1**: request for only non-personalized ads.<br>If this parameter is left blank, the service logic prevails.                                                                                                                                                                                                                                                                                                                                |
753| [key: string]           | number \| boolean \| string \| undefined | No | Yes | Custom parameters.<br> - **totalDuration**: The value is of the number type, in seconds. This parameter is mandatory for roll ads and is used to set the total duration of roll ads.<br> - **placementAdCountDownDesc**: The value is of the string type. This parameter is optional for roll ads and is used to set the countdown description of roll ads. This parameter must be encoded using the **encodeURI()** API. If this parameter is set, the countdown description is displayed. Otherwise, only the countdown is displayed.<br> - **allowMobileTraffic**: The value is of the number type. This parameter is optional. It specifies whether ads can be downloaded while mobile data is in use. The options are **0** (no) and **1** (yes). If this parameter is not set, the advertiser's setting will be used.<br> - **tagForUnderAgeOfPromise**: The value is of the number type. This parameter is optional. It specifies whether you want the ad request to be processed in a way that meets the GDPR for users in the EEA under the age of consent. The value **-1** means that you do not specify whether the ad request should be processed in a way that meets the GDPR for users in the EEA under the age of consent. The value **0** means that you do not want the ad request to be processed in a way that meets the GDPR for users in the EEA under the age of consent, and **1** means the opposite.|
754
755## AdRequestParams
756
757Defines the ad request parameters.
758
759**Atomic service API**: This API can be used in atomic services since API version 12.
760
761**System capability**: SystemCapability.Advertising.Ads
762
763| Name             | Type                                      | Read-Only| Optional| Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
764|-----------------|------------------------------------------|----|----|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
765| adId            | string                                   | No | No | Ad ID<br>- This parameter is optional for **getAdRequestBody**.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
766| adType          | number                                   | No | Yes | Type of the requested ad.<br>- **1**: splash ad.<br>- **3**: native ad.<br>- **7**: rewarded ad.<br>- **8**: banner ad.<br>- **12**: interstitial ad.<br>- **60**: roll ad.<br>If this parameter is left blank, the native ad type is used by default.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
767| adCount         | number                                   | No | Yes | Number of ads requested. If this parameter is left blank, the service logic prevails.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
768| adWidth         | number                                   | No | Yes | Expected creative width of ads requested, in vp. This parameter is mandatory for banner ads. If this parameter is left blank, the service logic prevails.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
769| adHeight        | number                                   | No | Yes | Expected creative height of ads requested, in vp. This parameter is mandatory for banner ads. If this parameter is left blank, the service logic prevails.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
770| adSearchKeyword | string                                   | No | Yes | Ad keyword. If this parameter is left blank, "" is used by default.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
771| [key: string]   | number \| boolean \| string \| undefined | No | Yes | Custom parameters.<br>- **isPreload**: A Boolean value used to distinguish common requests from preload requests when roll ads are requested. The value **true** indicates the preload request; the value **false** (default) indicates the common request.  This parameter is valid only for roll ads. For other ad requests, this parameter is not parsed.<br>- **enableDirectReturnVideoAd**: A custom extended parameter of native ads, whose value is of Boolean type. It indicates whether to directly return the ad without waiting for the download of all ad materials. The value **true** means that the ad is loaded online without waiting for the download of all ad materials; the value **false** means that the ad is loaded from the local cache after the ad materials are downloaded. If this parameter is left blank, the configuration on the cloud prevails. This parameter is valid only for native ads. It is not parsed for other ad requests.<br>- **oaid**: A string indicates the Open Anonymous Device Identifier (OAID), which is used to precisely push ads. If this parameter is left blank, personalized ads cannot be obtained. Default value: **""**<br>- **tmax**: A number indicates the maximum timeout (including the network delay) of a transaction. The unit is millisecond.<br>- **cur**: A string indicates the currency supported by the bidding request. Multiple currencies are separated by commas (,). Currently, the following currencies are supported: **CNY**, **USD**, **EUR**, **GBP**, and **JPY**. If this parameter is left blank, the default value **CNY** is used.<br>- **bidFloor**: A number indicates the bid price floor of an ad.<br>- **bidFloorCur**: A string indicates the currency used by the bid price floor of an ad. If **bidFloor** is not empty, then **bidFlorCur** is also not empty. Currently, the following currencies are supported: **CNY**, **USD**, **EUR**, **GBP**, and **JPY**. If this parameter is left blank, the default value **CNY** is used.<br>- **bpkgName**: A string indicates the package name of the application that is forbidden to be displayed in an ad. Multiple application package names are passed and separated by commas (,).|
772
773## AdDisplayOptions
774
775Defines the ad display parameters.
776
777**Atomic service API**: This API can be used in atomic services since API version 12.
778
779**System capability**: SystemCapability.Advertising.Ads
780
781| Name                   | Type                                      | Read-Only| Optional| Description                                                                                                                                                    |
782|-----------------------|------------------------------------------|----|----|--------------------------------------------------------------------------------------------------------------------------------------------------------|
783| customData            | string                                   | No | Yes | Custom media data. It is used by the server to notify the media server that a user should be rewarded for interacting with the ad, so as to avoid spoofing. If this parameter is left blank, no notification is sent.                                                                                         |
784| userId                | string                                   | No | Yes | User ID. It is used by the server to notify the media server that a user should be rewarded for interacting with the ad, so as to avoid spoofing. If this parameter is left blank, no notification is sent.                                                                                       |
785| useMobileDataReminder | boolean                                  | No | Yes | Whether to display a dialog box to notify users when they use mobile data to play videos or download applications.<br>- **true**: A dialog box is displayed.<br>- **false**: No dialog box is displayed.<br>This parameter depends on the mobile data dialog box function. Currently, the complete function is not supported, and therefore the default value is not determined.                                                   |
786| mute                  | boolean                                  | No | Yes | Whether to mute the ad video.<br>- **true**: The ad video is muted.<br>- **false**: The ad video is not muted.<br>If this parameter is left blank, the service logic prevails.                                                                                        |
787| audioFocusType        | number                                   | No | Yes | Type of the scenario where the audio focus is obtained during video playback.<br>- **0**: The focus is obtained when the video is played in mute or non-mute mode.<br>- **1**: The focus is not obtained when the video is played in mute mode.<br>- **2**: The focus is not obtained when the video is played in mute or non-mute mode.<br>Currently, the function on which this API depends is not supported, and therefore the default value is not determined.                         |
788| [key: string]         | number \| boolean \| string \| undefined | No | Yes | Custom parameters.<br>- **refreshTime**: The value is of the number type, in ms. The value is in the range [30000, 120000]. This parameter is optional for the AutoAdComponent module and specifies the interval at which the ads rotate. If this parameter is set, ads are rotated at the interval specified by this parameter. Otherwise, ads are not rotated and only the first ad in the ad response is displayed.|
789
790## Advertisement
791
792type Advertisement = _Advertisement
793
794Defines the requested ad content.
795
796**Atomic service API**: This API can be used in atomic services since API version 12.
797
798**System capability**: SystemCapability.Advertising.Ads
799
800| Type                                                          | Description               |
801|--------------------------------------------------------------|-------------------|
802| [_Advertisement](js-apis-inner-advertising-advertisement.md) | Advertisement object.|
803