• 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## 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 { advertising } from '@kit.AdsKit';
46import { hilog } from '@kit.PerformanceAnalysisKit';
47import { common } from '@kit.AbilityKit';
48
49@Entry
50@Component
51export struct ShowAd {
52  private context: common.UIAbilityContext = getContext(this) 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 ('Show Ad')
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', '%{public}s', `show ad catch error: ${err.code} ${err.message}`);
70            }
71          });
72    }
73    .width('100%')
74    .height('100%')
75  }
76}
77```
78
79## 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 { hilog } from '@kit.PerformanceAnalysisKit';
114import { BusinessError } from '@kit.BasicServicesKit';
115import { advertising } from '@kit.AdsKit';
116import { Prompt } from '@kit.ArkUI';
117
118function getAdRequestBody(): void {
119  let adReqParamsListForRequest: Array<advertising.AdRequestParams> = [];
120  const adReqParams: Record<string, Object> = {
121    'adId': 'testu7m3hc4gvm',
122    'adType': 3,
123    'adCount': 2,
124    'adWidth': 100,
125    'adHeight': 100
126  };
127
128  adReqParamsListForRequest.push(adReqParams as advertising.AdRequestParams);
129  const adOption: Record<string, Object> = {
130    // Set the maximum ad content rating. The following values are available: w: ages 3+, all audiences; PI: ages 7+, audiences under parental instruction; J: ages 12+, teenagers; A: ages 16+/18+, adults.
131    'adContentClassification': 'A',
132    // 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.
133    'nonPersonalizedAd': 0,
134    // 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.
135    'tagForChildProtection': 1,
136    // 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.
137    'tagForUnderAgeOfPromise': -1
138  };
139  advertising.getAdRequestBody(adReqParamsListForRequest, adOption as advertising.AdOptions).then((data) => {
140    hilog.info(0x0000, 'testTag', '%{public}s', `succeeded in getting AdRequestBody by promise: ${data}`);
141    Prompt.showToast({
142      message: data,
143      duration: 1000
144    });
145  }).catch((error: BusinessError) => {
146    hilog.error(0x0000, 'testTag', '%{public}s',
147      `getAdRequestBody failed, code: ${error.code}, message: ${error.message}`);
148    Prompt.showToast({
149      message: error.code.toString() + ',' + error.message,
150      duration: 1000
151    });
152  })
153}
154```
155
156## parseAdResponse<sup>12+</sup>
157
158parseAdResponse(adResponse: string, listener: MultiSlotsAdLoadListener, context: common.UIAbilityContext): void
159
160Parses and processes the ad response body. (This API is available only for some preset applications.)
161
162**System capability**: SystemCapability.Advertising.Ads
163
164**Parameters**
165
166| Name       | Type                                                                                          | Mandatory| Description              |
167|------------|----------------------------------------------------------------------------------------------|----|------------------|
168| adResponse | string                                                                                       | Yes | Ad request parameters.         |
169| listener   | [MultiSlotsAdLoadListener](#multislotsadloadlistener)                                        | Yes | Ad request callback.       |
170| context    | common.[UIAbilityContext](../apis-ability-kit/js-apis-inner-application-uiAbilityContext.md) | Yes | UIAbility context.|
171
172**Error codes**
173
174For details about the following error codes, see [Ads Service Framework Error Codes](errorcode-ads.md).
175
176| ID   | Error Message                                                                                                                                                   |
177|----------|---------------------------------------------------------------------------------------------------------------------------------------------------------|
178| 401      | Invalid input parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. |
179| 801      | Device not supported.                                                                                                                                   |
180| 21800001 | System internal error.                                                                                                                                  |
181| 21800005 | Failed to parse the ad response.                                                                                                                        |
182
183**Example**
184
185For details about how to obtain the context, see [Obtaining the Context of UIAbility](../apis-ability-kit/js-apis-inner-application-uiAbilityContext.md).
186
187```ts
188import { common } from '@kit.AbilityKit';
189import { advertising } from '@kit.AdsKit';
190import { hilog } from '@kit.PerformanceAnalysisKit';
191
192function parseAdResponse(adResponse: string, context: common.UIAbilityContext): void {
193  // Listen for the ad parsing callback.
194  const multiSlotsAdLoaderListener: advertising.MultiSlotsAdLoadListener = {
195    // Called when ad parsing fails.
196    onAdLoadFailure: (errorCode: number, errorMsg: string) => {
197      hilog.error(0x0000, 'testTag', '%{public}s',
198        `request multi ads errorCode is: ${errorCode}, errorMsg is: ${errorMsg}`);
199    },
200    // Called when ad parsing is successful.
201    onAdLoadSuccess: (ads: Map<string, Array<advertising.Advertisement>>) => {
202      hilog.info(0x0000, 'testTag', '%{public}s', 'succeeded in requesting multi ads!');
203      // Save the parsed ad content as an array for display.
204      let returnAds: Array<advertising.Advertisement> = [];
205      ads.forEach((adsArray) => returnAds.push(...adsArray));
206    }
207  };
208  // Call the API to parse the response body.
209  hilog.info(0x0000, 'testTag', '%{public}s', 'parse ad response!');
210  advertising.parseAdResponse(adResponse, multiSlotsAdLoaderListener, context);
211}
212```
213
214## registerWebAdInterface<sup>12+</sup>
215
216registerWebAdInterface(controller: web_webview.WebviewController, context: common.UIAbilityContext): void
217
218Injects an ad JavaScript object to the **Web** component. (This API is available only for some preset applications.)
219
220**Atomic service API**: This API can be used in atomic services since API version 12.
221
222**System capability**: SystemCapability.Advertising.Ads
223
224**Parameters**
225
226| Name       | Type                                                                                          | Mandatory| Description              |
227|------------|----------------------------------------------------------------------------------------------|----|------------------|
228| controller | web_webview.[WebviewController](../apis-arkweb/js-apis-webview.md#webviewcontroller)         | Yes | Controller of the **Web** component.       |
229| context    | common.[UIAbilityContext](../apis-ability-kit/js-apis-inner-application-uiAbilityContext.md) | Yes | UIAbility context.|
230
231**Error codes**
232
233For details about the following error codes, see [Ads Service Framework Error Codes](errorcode-ads.md).
234
235| ID   | Error Message                                                                                 |
236|----------|---------------------------------------------------------------------------------------|
237| 401      | Invalid input parameter. Possible causes: 1.Mandatory parameters are left unspecified |
238| 21800001 | System internal error.                                                                |
239
240**Example**
241
242```ts
243import { webview } from '@kit.ArkWeb';
244import { common } from '@kit.AbilityKit';
245import { advertising } from '@kit.AdsKit';
246import { hilog } from '@kit.PerformanceAnalysisKit';
247
248@Entry
249@Component
250struct Index {
251  private webController: webview.WebviewController = new webview.WebviewController();
252  private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
253
254  build() {
255    Column() {
256      Button('Inject Ad Object to Web')
257        .onClick(() => {
258          try {
259            advertising.registerWebAdInterface(this.webController, this.context);
260          } catch (err) {
261            hilog.error(0x0000, 'testTag', '%{public}s',
262              `register web ad interface error: ${err.code}, ${err.message}`);
263          }
264        })
265
266      Web({
267        src: 'www.example.com',
268        controller: this.webController,
269      })
270        .width("100%")
271        .height("100%")
272    }
273  }
274}
275```
276
277## registerWebAdInterface<sup>16+</sup>
278
279registerWebAdInterface(controller: web_webview.WebviewController, context: common.UIAbilityContext, needRefresh: boolean): void
280
281Injects an ad JavaScript object to the **Web** component. (This API is available only for some preset applications.)
282
283**Atomic service API**: This API can be used in atomic services since API version 16.
284
285**System capability**: SystemCapability.Advertising.Ads
286
287**Parameters**
288
289| Name        | Type                                                                                          | Mandatory| Description                            |
290|-------------|----------------------------------------------------------------------------------------------|----|--------------------------------|
291| controller  | web_webview.[WebviewController](../apis-arkweb/js-apis-webview.md#webviewcontroller)         | Yes | Controller of the **Web** component.                     |
292| context     | common.[UIAbilityContext](../apis-ability-kit/js-apis-inner-application-uiAbilityContext.md) | Yes | UIAbility context.              |
293| 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.)|
294
295**Error codes**
296
297For details about the following error codes, see [Ads Service Framework Error Codes](errorcode-ads.md).
298
299| ID   | Error Message                                                                                |
300|----------|--------------------------------------------------------------------------------------|
301| 401      | Invalid input parameter. Possible causes: Mandatory parameters are left unspecified. |
302| 21800001 | operation javascriptRegister error.                                                  |
303
304**Example**
305
306```ts
307import { webview } from '@kit.ArkWeb';
308import { common } from '@kit.AbilityKit';
309import { advertising } from '@kit.AdsKit';
310import { hilog } from '@kit.PerformanceAnalysisKit';
311
312@Entry
313@Component
314struct Index {
315  private webController: webview.WebviewController = new webview.WebviewController();
316  private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
317
318  build() {
319    Column() {
320      Button('Inject Ad Object to Web')
321        .onClick(() => {
322          try {
323            advertising.registerWebAdInterface(this.webController, this.context, true);
324          } catch (err) {
325            hilog.error(0x0000, 'testTag', '%{public}s', `register web ad interface error: ${err.code}, ${err.message}`);
326          }
327        })
328
329      Web({
330        src: 'www.example.com',
331        controller: this.webController,
332      })
333        .width("100%")
334        .height("100%")
335    }
336  }
337}
338```
339
340## deleteWebAdInterface<sup>16+</sup>
341
342deleteWebAdInterface(controller: web_webview.WebviewController, needRefresh: boolean): void
343
344Deletes the ad JavaScript object injected through **registerWebAdInterface**. (This API is available only to some preset applications.)
345
346**Atomic service API**: This API can be used in atomic services since API version 16.
347
348**System capability**: SystemCapability.Advertising.Ads
349
350**Parameters**
351
352| Name        | Type                                                                                  | Mandatory| Description                            |
353|-------------|--------------------------------------------------------------------------------------|----|--------------------------------|
354| controller  | web_webview.[WebviewController](../apis-arkweb/js-apis-webview.md#webviewcontroller) | Yes | Controller of the **Web** component.                     |
355| 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.)|
356
357**Error codes**
358
359For details about the following error codes, see [Ads Service Framework Error Codes](errorcode-ads.md).
360
361| ID   | Error Message                                                                                |
362|----------|--------------------------------------------------------------------------------------|
363| 401      | Invalid input parameter. Possible causes: Mandatory parameters are left unspecified. |
364| 21800001 | operation javascriptRegister error.                                                  |
365
366**Example**
367
368```ts
369import { webview } from '@kit.ArkWeb';
370import { common } from '@kit.AbilityKit';
371import { advertising } from '@kit.AdsKit';
372import { hilog } from '@kit.PerformanceAnalysisKit';
373
374@Entry
375@Component
376struct Index {
377  private webController: webview.WebviewController = new webview.WebviewController();
378  private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
379
380  build() {
381    Column() {
382      Button('Delete the ad JavaScript object injected through registerWebAdInterface')
383        .onClick(() => {
384          try {
385            advertising.deleteWebAdInterface(this.webController, true);
386          } catch (err) {
387            hilog.error(0x0000, 'testTag', '%{public}s', `delete web ad interface error: ${err.code}, ${err.message}`);
388          }
389        })
390
391      Web({
392        src: 'www.example.com',
393        controller: this.webController,
394      })
395        .width("100%")
396        .height("100%")
397    }
398  }
399}
400```
401
402## AdLoader
403
404Provides the APIs for loading ads.
405
406**Atomic service API**: This API can be used in atomic services since API version 12.
407
408**System capability**: SystemCapability.Advertising.Ads
409
410### constructor
411
412constructor(context: common.Context)
413
414Constructor.
415
416**Atomic service API**: This API can be used in atomic services since API version 12.
417
418**System capability**: SystemCapability.Advertising.Ads
419
420**Parameters**
421
422| Name    | Type                                                                        | Mandatory| Description                        |
423|---------|----------------------------------------------------------------------------|----|----------------------------|
424| context | common.[Context](../apis-ability-kit/js-apis-inner-application-context.md) | Yes | Context of the ability or application.|
425
426**Example**
427
428For details about how to obtain the context, see [Context](../../application-models/application-context-stage.md#overview).
429
430```ts
431import { advertising } from '@kit.AdsKit';
432import { common } from '@kit.AbilityKit';
433
434function createConstructor(context: common.Context): void {
435  const load: advertising.AdLoader = new advertising.AdLoader(context);
436}
437```
438
439### loadAd
440
441loadAd(adParam: AdRequestParams, adOptions: AdOptions, listener: AdLoadListener): void
442
443Loads an ad.
444
445**Atomic service API**: This API can be used in atomic services since API version 12.
446
447**System capability**: SystemCapability.Advertising.Ads
448
449**Parameters**
450
451| Name      | Type                                 | Mandatory| Description       |
452|-----------|-------------------------------------|----|-----------|
453| adParam   | [AdRequestParams](#adrequestparams) | Yes | Ad request parameters.  |
454| adOptions | [AdOptions](#adoptions)             | Yes | Ad configuration.    |
455| listener  | [AdLoadListener](#adloadlistener)   | Yes | Ad request callback.|
456
457**Error codes**
458
459For details about the following error codes, see [Ads Service Framework Error Codes](errorcode-ads.md).
460
461| ID   | Error Message                                                                                                                                                  |
462|----------|--------------------------------------------------------------------------------------------------------------------------------------------------------|
463| 401      | Invalid input parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. |
464| 801      | Device not supported.                                                                                                                                  |
465| 21800001 | System internal error.                                                                                                                                 |
466| 21800003 | Failed to load the ad request.                                                                                                                         |
467
468**Example**
469
470For details about how to obtain the context, see [Context](../../application-models/application-context-stage.md#overview).
471
472```ts
473import { advertising } from '@kit.AdsKit';
474import { common } from '@kit.AbilityKit';
475import { hilog } from '@kit.PerformanceAnalysisKit';
476
477function requestAd(context: common.Context): void {
478  const adRequestParam: advertising.AdRequestParams = {
479    // Ad type.
480    adType: 3,
481    // Ad ID.
482    adId: "testy63txaom86"
483  };
484  const adOptions: advertising.AdOptions = {
485    // Optional custom parameter, which specifies whether the ad can be downloaded while mobile data is in use. The value 1 means that the ad can be downloaded while mobile data is in use, and 0 means the opposite.
486    allowMobileTraffic: 0,
487    // Set the maximum ad content rating. The following values are available: w: ages 3+, all audiences; PI: ages 7+, audiences under parental instruction; J: ages 12+, teenagers; A: ages 16+/18+, adults.
488    adContentClassification: 'A',
489    // 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.
490    tagForChildProtection: -1,
491    // 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.
492    tagForUnderAgeOfPromise: -1
493  }
494  // Listener for the ad loading status.
495  const adLoaderListener: advertising.AdLoadListener = {
496    // Called when the ad request fails.
497    onAdLoadFailure: (errorCode: number, errorMsg: string) => {
498      hilog.error(0x0000, 'testTag', '%{public}s',
499        `request single ad errorCode is: ${errorCode}, errorMsg is: ${errorMsg}`);
500    },
501    // Called when the ad request is successful.
502    onAdLoadSuccess: (ads: Array<advertising.Advertisement>) => {
503      hilog.info(0x0000, 'testTag', '%{public}s', 'succeed in requesting single ad!');
504      // Save the requested ad content for display.
505      const returnAds = ads;
506    }
507  };
508  // Create an AdLoader object.
509  const load: advertising.AdLoader = new advertising.AdLoader(context);
510  // Load the ad.
511  hilog.info(0x0000, 'testTag', '%{public}s', 'request single ad!');
512  load.loadAd(adRequestParam, adOptions, adLoaderListener);
513}
514```
515
516### loadAdWithMultiSlots
517
518loadAdWithMultiSlots(adParams: AdRequestParams[], adOptions: AdOptions, listener: MultiSlotsAdLoadListener): void
519
520Loads multiple ads.
521
522**Atomic service API**: This API can be used in atomic services since API version 12.
523
524**System capability**: SystemCapability.Advertising.Ads
525
526**Parameters**
527
528| Name      | Type                                                   | Mandatory| Description       |
529|-----------|-------------------------------------------------------|----|-----------|
530| adParams  | [AdRequestParams](#adrequestparams)[]                 | Yes | Ad request parameters.  |
531| adOptions | [AdOptions](#adoptions)                               | Yes | Ad configuration.    |
532| listener  | [MultiSlotsAdLoadListener](#multislotsadloadlistener) | Yes | Ad request callback.|
533
534**Error codes**
535
536For details about the following error codes, see [Ads Service Framework Error Codes](errorcode-ads.md).
537
538| ID   | Error Message                                                                                                                                                  |
539|----------|--------------------------------------------------------------------------------------------------------------------------------------------------------|
540| 401      | Invalid input parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. |
541| 801      | Device not supported.                                                                                                                                  |
542| 21800001 | System internal error.                                                                                                                                 |
543| 21800003 | Failed to load the ad request.                                                                                                                         |
544
545**Example**
546
547For details about how to obtain the context, see [Context](../../application-models/application-context-stage.md#overview).
548
549```ts
550import { advertising } from '@kit.AdsKit';
551import { common } from '@kit.AbilityKit';
552import { hilog } from '@kit.PerformanceAnalysisKit';
553
554function requestMultiAd(context: common.Context): void {
555  const adRequestParamArray: advertising.AdRequestParams[] = [{
556    // Ad type.
557    adType: 3,
558    // Ad ID.
559    adId: "testy63txaom86"
560  } as advertising.AdRequestParams,
561    {
562      // Ad type.
563      adType: 3,
564      // Ad ID.
565      adId: "testy63txaom86"
566    } as advertising.AdRequestParams
567  ];
568  const adOptions: advertising.AdOptions = {
569    // Optional custom parameter, which specifies whether the ad can be downloaded while mobile data is in use. The value 1 means that the ad can be downloaded while mobile data is in use, and 0 means the opposite.
570    allowMobileTraffic: 0,
571    // Set the maximum ad content rating. The following values are available: w: ages 3+, all audiences; PI: ages 7+, audiences under parental instruction; J: ages 12+, teenagers; A: ages 16+/18+, adults.
572    adContentClassification: 'A',
573    // 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.
574    tagForChildProtection: -1,
575    // 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.
576    tagForUnderAgeOfPromise: -1
577  };
578  // Listener for the ad loading status.
579  const multiSlotsAdLoaderListener: advertising.MultiSlotsAdLoadListener = {
580    // Called when the ad request fails.
581    onAdLoadFailure: (errorCode: number, errorMsg: string) => {
582      hilog.error(0x0000, 'testTag', '%{public}s',
583        `request multi ads errorCode is: ${errorCode}, errorMsg is: ${errorMsg}`);
584    },
585    // Called when the ad request is successful.
586    onAdLoadSuccess: (ads: Map<string, Array<advertising.Advertisement>>) => {
587      hilog.info(0x0000, 'testTag', '%{public}s', 'succeed in requesting multi ads!');
588      // Save the requested ad content for display.
589      let returnAds: Array<advertising.Advertisement> = [];
590      ads.forEach((adsArray) => returnAds.push(...adsArray));
591    }
592  };
593  // Create an AdLoader object.
594  const load: advertising.AdLoader = new advertising.AdLoader(context);
595  // Load the ad.
596  hilog.info(0x0000, 'testTag', '%{public}s', 'request multi ads!');
597  load.loadAdWithMultiSlots(adRequestParamArray, adOptions, multiSlotsAdLoaderListener);
598}
599```
600
601## AdLoadListener
602
603Enumerates the callbacks used for the request for loading an ad.
604
605**Atomic service API**: This API can be used in atomic services since API version 12.
606
607**System capability**: SystemCapability.Advertising.Ads
608
609### onAdLoadFailure
610
611onAdLoadFailure(errorCode: number, errorMsg: string): void
612
613Called when an ad request fails.
614
615**Atomic service API**: This API can be used in atomic services since API version 12.
616
617**System capability**: SystemCapability.Advertising.Ads
618
619**Parameters**
620
621| Name      | Type    | Mandatory| Description          |
622|-----------|--------|----|--------------|
623| errorCode | number | Yes | Result code indicating the ad request failure. |
624| errorMsg  | string | Yes | Error message about the ad request failure.|
625
626### onAdLoadSuccess
627
628onAdLoadSuccess(ads: Array&lt;Advertisement&gt;): void
629
630Called when an ad request is successful.
631
632**Atomic service API**: This API can be used in atomic services since API version 12.
633
634**System capability**: SystemCapability.Advertising.Ads
635
636**Parameters**
637
638| Name| Type                                          | Mandatory| Description   |
639|-----|----------------------------------------------|----|-------|
640| ads | Array&lt;[Advertisement](#advertisement)&gt; | Yes | Ad data.|
641
642**Example**
643
644```ts
645import { advertising } from '@kit.AdsKit';
646
647let adLoaderListener: advertising.AdLoadListener = {
648  onAdLoadFailure: (errorCode: number, errorMsg: string) => {
649  },
650  onAdLoadSuccess: (ads: Array<advertising.Advertisement>) => {
651  }
652}
653```
654
655## MultiSlotsAdLoadListener
656
657Enumerates the callbacks used for the request for loading multiple ads.
658
659**Atomic service API**: This API can be used in atomic services since API version 12.
660
661**System capability**: SystemCapability.Advertising.Ads
662
663### onAdLoadFailure
664
665onAdLoadFailure(errorCode: number, errorMsg: string): void
666
667Called when a request for loading multiple ads fails.
668
669**Atomic service API**: This API can be used in atomic services since API version 12.
670
671**System capability**: SystemCapability.Advertising.Ads
672
673**Parameters**
674
675| Name      | Type    | Mandatory| Description          |
676|-----------|--------|----|--------------|
677| errorCode | number | Yes | Result code indicating the ad request failure. |
678| errorMsg  | string | Yes | Error message about the ad request failure.|
679
680### onAdLoadSuccess
681
682onAdLoadSuccess(adsMap: Map&lt;string, Array&lt;Advertisement&gt;&gt;): void
683
684Called when a request for loading multiple ads is successful.
685
686**Atomic service API**: This API can be used in atomic services since API version 12.
687
688**System capability**: SystemCapability.Advertising.Ads
689
690**Parameters**
691
692| Name   | Type                                                             | Mandatory| Description   |
693|--------|-----------------------------------------------------------------|----|-------|
694| adsMap | Map&lt;string, Array&lt;[Advertisement](#advertisement)&gt;&gt; | Yes | Ad data.|
695
696**Example**
697
698```ts
699import { advertising } from '@kit.AdsKit';
700
701let adLoaderListener: advertising.MultiSlotsAdLoadListener = {
702  onAdLoadFailure: (errorCode: number, errorMsg: string) => {
703  },
704  onAdLoadSuccess: (adsMap: Map<string, Array<advertising.Advertisement>>) => {
705  }
706}
707```
708
709## AdInteractionListener
710
711Defines the ad status change callback.
712
713**Atomic service API**: This API can be used in atomic services since API version 12.
714
715**System capability**: SystemCapability.Advertising.Ads
716
717### onStatusChanged
718
719onStatusChanged(status: string, ad: Advertisement, data: string)
720
721Called when the ad display status changes.
722
723**Atomic service API**: This API can be used in atomic services since API version 12.
724
725**System capability**: SystemCapability.Advertising.Ads
726
727**Parameters**
728
729| Name   | Type                             | Mandatory| Description                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
730|--------|---------------------------------|----|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
731| 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**.|
732| ad     | [Advertisement](#advertisement) | Yes | Content of the ad.                                                                                                                                                                                                                                                                                                                                                                                                                                            |
733| data   | string                          | Yes | Extended information.                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
734
735**Example**
736
737```ts
738import { advertising } from '@kit.AdsKit';
739
740let adInteractionListener: advertising.AdInteractionListener = {
741  onStatusChanged: (status: string, ad: advertising.Advertisement, data: string) => {
742
743  }
744}
745```
746
747## AdOptions
748
749Defines the ad configuration.
750
751**Atomic service API**: This API can be used in atomic services since API version 12.
752
753**System capability**: SystemCapability.Advertising.Ads
754
755| Name                     | Type                                      | Read-Only| Optional| Description                                                                                                                                                                                                                                                                                                                                                                                                      |
756|-------------------------|------------------------------------------|----|----|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
757| 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>                                                                                                                                                                                                                                                                                                            |
758| 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.                                                                                                                                                                                                                                                                                                    |
759| 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.                                                                                                                                                                                                                                                                                                                                |
760| [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.|
761
762## AdRequestParams
763
764Defines the ad request parameters.
765
766**Atomic service API**: This API can be used in atomic services since API version 12.
767
768**System capability**: SystemCapability.Advertising.Ads
769
770| Name             | Type                                      | Read-Only| Optional| Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
771|-----------------|------------------------------------------|----|----|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
772| adId            | string                                   | No | No | Ad ID<br>- This parameter is optional for **getAdRequestBody**.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
773| 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.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
774| adCount         | number                                   | No | Yes | Number of ads requested. If this parameter is left blank, the service logic prevails.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
775| 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.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
776| 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.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
777| adSearchKeyword | string                                   | No | Yes | Ad keyword. If this parameter is left blank, "" is used by default.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
778| [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 (,).|
779
780## AdDisplayOptions
781
782Defines the ad display parameters.
783
784**Atomic service API**: This API can be used in atomic services since API version 12.
785
786**System capability**: SystemCapability.Advertising.Ads
787
788| Name                   | Type                                      | Read-Only| Optional| Description                                                                                                                                                    |
789|-----------------------|------------------------------------------|----|----|--------------------------------------------------------------------------------------------------------------------------------------------------------|
790| 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.                                                                                         |
791| 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.                                                                                       |
792| 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.                                                   |
793| 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.                                                                                        |
794| 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.                         |
795| [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.|
796
797## Advertisement
798
799type Advertisement = _Advertisement
800
801Defines the requested ad content.
802
803**Atomic service API**: This API can be used in atomic services since API version 12.
804
805**System capability**: SystemCapability.Advertising.Ads
806
807| Type                                                          | Description               |
808|--------------------------------------------------------------|-------------------|
809| [_Advertisement](js-apis-inner-advertising-advertisement.md) | Advertisement object.|
810