1# @ohos.advertising (Ads Service Framework) 2 3 4The advertising module provides APIs for requesting and displaying ads. 5 6 7> **NOTE** 8> 9> 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. 10 11 12## Modules to Import 13 14```ts 15import { advertising } from '@kit.AdsKit'; 16``` 17## AdLoader 18 19Provides the APIs for loading ads. 20 21**Atomic service API**: This API can be used in atomic services since API version 12. 22 23**System capability**: SystemCapability.Advertising.Ads 24 25### constructor 26 27constructor(context: common.Context); 28 29Constructor. 30 31**Atomic service API**: This API can be used in atomic services since API version 12. 32 33**System capability**: SystemCapability.Advertising.Ads 34 35**Parameters** 36 37| Name| Type| Mandatory| Description| 38| -------- | -------- | -------- | -------- | 39| context | common.[Context](../apis-ability-kit/js-apis-inner-application-context.md) | Yes| Context of the ability or application.| 40 41**Example** 42 43For details about how to obtain the context, see [Context](../../application-models/application-context-stage.md#overview). 44 45```ts 46import { advertising } from '@kit.AdsKit'; 47import { common } from '@kit.AbilityKit'; 48 49function createConstructor(context: common.Context): void { 50 const load: advertising.AdLoader = new advertising.AdLoader(context); 51} 52``` 53 54 55### loadAd 56 57loadAd(adParam: AdRequestParams, adOptions: AdOptions, listener: AdLoadListener): void 58 59Loads an ad. 60 61**Atomic service API**: This API can be used in atomic services since API version 12. 62 63**System capability**: SystemCapability.Advertising.Ads 64 65**Parameters** 66 67| Name| Type| Mandatory| Description| 68| -------- | -------- | -------- | -------- | 69| adParam | [AdRequestParams](#adrequestparams) | Yes| Ad request parameters.| 70| adOptions | [AdOptions](#adoptions) | Yes| Ad configuration.| 71| listener | [AdLoadListener](#adloadlistener) | Yes| Ad request callback.| 72 73**Error codes** 74 75For details about the following error codes, see [Ads Service Framework Error Codes](errorcode-ads.md). 76 77| ID| Error Message| 78| -------- | -------- | 79| 401 | Invalid input parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 80| 801 | Device not supported. | 81| 21800001 | System internal error. | 82| 21800003 | Failed to load the ad request. | 83 84 85**Example** 86 87For details about how to obtain the context, see [Context](../../application-models/application-context-stage.md#overview). 88 89```ts 90import { advertising } from '@kit.AdsKit'; 91import { common } from '@kit.AbilityKit'; 92import { hilog } from '@kit.PerformanceAnalysisKit'; 93 94function requestAd(context: common.Context): void { 95 const adRequestParam: advertising.AdRequestParams = { 96 // Ad type. 97 adType: 3, 98 // Ad ID. 99 adId: "testy63txaom86" 100 }; 101 const adOptions: advertising.AdOptions = { 102 // 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. 103 allowMobileTraffic: 0, 104 // 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. 105 adContentClassification: 'A', 106 // 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. 107 tagForChildProtection: -1, 108 // 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. 109 tagForUnderAgeOfPromise: -1 110 } 111 // Listener for the ad loading status. 112 const adLoaderListener: advertising.AdLoadListener = { 113 // Called when the ad request fails. 114 onAdLoadFailure: (errorCode: number, errorMsg: string) => { 115 hilog.error(0x0000, 'testTag', '%{public}s', 116 `request single ad errorCode is: ${errorCode}, errorMsg is: ${errorMsg}`); 117 }, 118 // Called when the ad request is successful. 119 onAdLoadSuccess: (ads: Array<advertising.Advertisement>) => { 120 hilog.info(0x0000, 'testTag', '%{public}s', 'succeed in requesting single ad!'); 121 // Save the requested ad content for display. 122 const returnAds = ads; 123 } 124 }; 125 // Create an AdLoader object. 126 const load: advertising.AdLoader = new advertising.AdLoader(context); 127 // Load the ad. 128 hilog.info(0x0000, 'testTag', '%{public}s', 'request single ad!'); 129 load.loadAd(adRequestParam, adOptions, adLoaderListener); 130} 131``` 132 133 134### loadAdWithMultiSlots 135 136loadAdWithMultiSlots(adParams: AdRequestParams[], adOptions: AdOptions, listener: MultiSlotsAdLoadListener): void 137 138Loads multiple ads. 139 140**Atomic service API**: This API can be used in atomic services since API version 12. 141 142**System capability**: SystemCapability.Advertising.Ads 143 144**Parameters** 145 146| Name| Type| Mandatory| Description| 147| -------- | -------- | -------- | -------- | 148| adParams | [AdRequestParams](#adrequestparams)[] | Yes| Ad request parameters.| 149| adOptions | [AdOptions](#adoptions) | Yes| Ad configuration.| 150| listener | [MultiSlotsAdLoadListener](#multislotsadloadlistener) | Yes| Ad request callback.| 151 152**Error codes** 153 154For details about the following error codes, see [Ads Service Framework Error Codes](errorcode-ads.md). 155 156| ID| Error Message| 157| -------- | -------- | 158| 401 | Invalid input parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 159| 801 | Device not supported. | 160| 21800001 | System internal error. | 161| 21800003 | Failed to load the ad request. | 162 163**Example** 164 165For details about how to obtain the context, see [Context](../../application-models/application-context-stage.md#overview). 166 167```ts 168import { advertising } from '@kit.AdsKit'; 169import { common } from '@kit.AbilityKit'; 170import { hilog } from '@kit.PerformanceAnalysisKit'; 171 172function requestMultiAd(context: common.Context): void { 173 const adRequestParamArray: advertising.AdRequestParams[] = [{ 174 // Ad type. 175 adType: 3, 176 // Ad ID. 177 adId: "testy63txaom86" 178 } as advertising.AdRequestParams, 179 { 180 // Ad type. 181 adType: 3, 182 // Ad ID. 183 adId: "testy63txaom86" 184 } as advertising.AdRequestParams 185 ]; 186 const adOptions: advertising.AdOptions = { 187 // 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. 188 allowMobileTraffic: 0, 189 // 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. 190 adContentClassification: 'A', 191 // 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. 192 tagForChildProtection: -1, 193 // 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. 194 tagForUnderAgeOfPromise: -1 195 }; 196 // Listener for the ad loading status. 197 const multiSlotsAdLoaderListener: advertising.MultiSlotsAdLoadListener = { 198 // Called when the ad request fails. 199 onAdLoadFailure: (errorCode: number, errorMsg: string) => { 200 hilog.error(0x0000, 'testTag', '%{public}s', 201 `request multi ads errorCode is: ${errorCode}, errorMsg is: ${errorMsg}`); 202 }, 203 // Called when the ad request is successful. 204 onAdLoadSuccess: (ads: Map<string, Array<advertising.Advertisement>>) => { 205 hilog.info(0x0000, 'testTag', '%{public}s', 'succeed in requesting multi ads!'); 206 // Save the requested ad content for display. 207 let returnAds: Array<advertising.Advertisement> = []; 208 ads.forEach((adsArray) => returnAds.push(...adsArray)); 209 } 210 }; 211 // Create an AdLoader object. 212 const load: advertising.AdLoader = new advertising.AdLoader(context); 213 // Load the ad. 214 hilog.info(0x0000, 'testTag', '%{public}s', 'request multi ads!'); 215 load.loadAdWithMultiSlots(adRequestParamArray, adOptions, multiSlotsAdLoaderListener); 216} 217``` 218 219 220## showAd 221 222showAd(ad: Advertisement, options: AdDisplayOptions, context?: common.UIAbilityContext): void 223 224Shows a full-screen ad. 225 226**Atomic service API**: This API can be used in atomic services since API version 12. 227 228**System capability**: SystemCapability.Advertising.Ads 229 230**Parameters** 231 232 233| Name| Type| Mandatory| Description| 234| -------- | -------- | -------- | -------- | 235| ad | [Advertisement](#advertisement) | Yes| Ad object.| 236| options | [AdDisplayOptions](#addisplayoptions) | Yes| Ad display parameters.| 237| 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.| 238 239 240**Error codes** 241 242 243For details about the following error codes, see [Ads Service Framework Error Codes](errorcode-ads.md). 244 245 246| ID| Error Message| 247| -------- | -------- | 248| 401 | Invalid input parameter. Possible causes: 1. Mandatory parameters are left unspecified.| 249| 21800001 | System internal error. | 250| 21800004 | Failed to display the ad. | 251 252 253**Example** 254 255```ts 256import { advertising } from '@kit.AdsKit'; 257import { hilog } from '@kit.PerformanceAnalysisKit'; 258import { common } from '@kit.AbilityKit'; 259 260@Entry 261@Component 262export struct ShowAd { 263 private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext; 264 // Requested ad content. 265 private ad?: advertising.Advertisement; 266 // Ad display parameters. 267 private adDisplayOptions: advertising.AdDisplayOptions = { 268 // Whether to mute the ad. By default, the ad is not muted. 269 mute: false 270 } 271 272 build() { 273 Column() { 274 Button ('Show Ad') 275 .onClick(() => { 276 try { 277 // Show the ad. 278 advertising.showAd(this.ad, this.adDisplayOptions, this.context); 279 } catch (err) { 280 hilog.error(0x0000, 'testTag', '%{public}s', `show ad catch error: ${err.code} ${err.message}`); 281 } 282 }); 283 } 284 .width('100%') 285 .height('100%') 286 } 287} 288``` 289 290 291## AdOptions 292 293Defines the ad configuration. 294 295**Atomic service API**: This API can be used in atomic services since API version 12. 296 297**System capability**: SystemCapability.Advertising.Ads 298 299 300| Name| Type| Mandatory| Description| 301| -------- | -------- | -------- | -------- | 302| tagForChildProtection | number | No| 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. The default value is **-1**.| 303| adContentClassification | string | No| 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. The default value is "".| 304| nonPersonalizedAd | number | No| Whether to request only non-personalized ads.<br>- **0**: request for personalized and non-personalized ads.<br>- **1**: request for only non-personalized ads. If this parameter is left blank, the service logic prevails.| 305| [key: string] | number \| boolean \| string \| undefined | No| 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 value **1** means that ads can be downloaded while mobile data is in use, and **0** means the opposite.<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.| 306 307 308## AdRequestParams 309 310Defines the ad request parameters. 311 312**Atomic service API**: This API can be used in atomic services since API version 12. 313 314**System capability**: SystemCapability.Advertising.Ads 315 316 317| Name| Type| Mandatory| Description| 318| -------- | -------- | -------- | -------- | 319| adId | string | Yes| Ad ID| 320| adType | number | No| 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.| 321| adCount | number | No| Number of ads requested. If this parameter is left blank, the service logic prevails.| 322| adWidth | number | No| Ad width. The value must be greater than 0. If this parameter is left blank, the service logic prevails.| 323| adHeight | number | No| Ad height. The value must be greater than 0. If this parameter is left blank, the service logic prevails.| 324| adSearchKeyword | string | No| Ad keyword. If this parameter is left blank, "" is used by default.| 325| [key: string] | number \| boolean \| string \| undefined | No| Custom parameters.| 326 327 328## AdLoadListener 329 330Enumerates the callbacks used for the request for loading an ad. 331 332**Atomic service API**: This API can be used in atomic services since API version 12. 333 334**System capability**: SystemCapability.Advertising.Ads 335 336### onAdLoadFailure 337 338onAdLoadFailure(errorCode: number, errorMsg: string): void 339 340Called when an ad request fails. 341 342**Atomic service API**: This API can be used in atomic services since API version 12. 343 344**System capability**: SystemCapability.Advertising.Ads 345 346| Name| Type| Mandatory| Description| 347| -------- | -------- | -------- | -------- | 348| errorCode | number | Yes| Result code indicating the ad request failure.| 349| errorMsg | string | Yes| Error message about the ad request failure.| 350 351 352### onAdLoadSuccess 353 354onAdLoadSuccess(ads: Array<advertising.Advertisement>): void 355 356Called when an ad request is successful. 357 358**Atomic service API**: This API can be used in atomic services since API version 12. 359 360**System capability**: SystemCapability.Advertising.Ads 361 362| Name| Type| Mandatory| Description| 363| -------- | -------- | -------- | -------- | 364| ads | Array<advertising.[Advertisement](#advertisement)> | Yes| Ad data.| 365 366 367**Example** 368 369```ts 370import { advertising } from '@kit.AdsKit'; 371 372let adLoaderListener: advertising.AdLoadListener = { 373 onAdLoadFailure: (errorCode: number, errorMsg: string) => { 374 }, 375 onAdLoadSuccess: (ads: Array<advertising.Advertisement>) => { 376 } 377} 378 379``` 380 381 382## MultiSlotsAdLoadListener 383 384Enumerates the callbacks used for the request for loading multiple ads. 385 386**Atomic service API**: This API can be used in atomic services since API version 12. 387 388**System capability**: SystemCapability.Advertising.Ads 389 390### onAdLoadFailure 391 392onAdLoadFailure(errorCode: number, errorMsg: string): void 393 394Called when a request for loading multiple ads fails. 395 396**Atomic service API**: This API can be used in atomic services since API version 12. 397 398**System capability**: SystemCapability.Advertising.Ads 399 400| Name| Type| Mandatory| Description| 401| -------- | -------- | -------- | -------- | 402| errorCode | number | Yes| Result code indicating the ad request failure.| 403| errorMsg | string | Yes| Error message about the ad request failure.| 404 405 406### onAdLoadSuccess 407 408onAdLoadSuccess(adsMap: Map<string, Array<advertising.Advertisement>>): void 409 410Called when a request for loading multiple ads is successful. 411 412**Atomic service API**: This API can be used in atomic services since API version 12. 413 414**System capability**: SystemCapability.Advertising.Ads 415 416| Name| Type| Mandatory| Description| 417| -------- | -------- | -------- | -------- | 418| adsMap | Map<string, Array<advertising.[Advertisement](#advertisement)>>| Yes| Ad data.| 419 420 421**Example** 422 423```ts 424import { advertising } from '@kit.AdsKit'; 425 426let adLoaderListener: advertising.MultiSlotsAdLoadListener = { 427 onAdLoadFailure: (errorCode: number, errorMsg: string) => { 428 }, 429 onAdLoadSuccess: (adsMap: Map<string, Array<advertising.Advertisement>>) => { 430 } 431} 432``` 433 434 435## Advertisement 436 437 438Defines the requested ad content. 439 440**Atomic service API**: This API can be used in atomic services since API version 12. 441 442**System capability**: SystemCapability.Advertising.Ads 443 444 445| Name| Type| Read-Only| Mandatory| Description| 446| -------- | --------| -------- | -------- | -------- | 447| adType | number | No|Yes| Ad type.| 448| uniqueId | string | No|Yes| Unique ID of the ad.| 449| rewarded | boolean | No|Yes| Whether users get rewarded for watching or clicking the ad.<br>- **true**: Users get rewarded.<br>- **false**: Users do not get rewarded.| 450| shown | boolean | No|Yes| Whether the ad is shown.<br>- **true**: The ad is shown.<br>- **false**: The ad is not shown.| 451| clicked | boolean | No|Yes| Whether the ad is clicked.<br>- **true**: The ad is clicked.<br>- **false**: The ad is not clicked.| 452| rewardVerifyConfig | Map<string, string> | No|Yes| Server verification parameter.<br>{<br>customData: "test",<br>userId: "12345"<br>} | 453| [key: string] | Object | No|Yes| Custom parameters.<br>- **isFullScreen**: The value is of the Boolean type. This parameter is used for splash ads to specify whether such an ad is in full-screen mode. The value **true** means that the ad is in full-screen mode, and **false** means that the ad is in half-screen mode.| 454 455 456## AdDisplayOptions 457 458 459Defines the ad display parameters. 460 461**Atomic service API**: This API can be used in atomic services since API version 12. 462 463**System capability**: SystemCapability.Advertising.Ads 464 465 466| Name| Type| Mandatory| Description| 467| -------- | -------- | -------- | -------- | 468| customData | string | No| 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.| 469| userId | string | No| 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.| 470| useMobileDataReminder | boolean | No| 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. 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.| 471| mute | boolean | No| Whether to mute the ad video.<br>- **true**: The ad video is muted.<br>- **false**: The ad video is not muted. If this parameter is left blank, the default value **true** is used.| 472| audioFocusType | number | No| 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. Currently, the function on which this API depends is not supported, and therefore the default value is not determined.| 473| [key: string] | number \| boolean \| string \| undefined | No| 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.| 474 475 476## AdInteractionListener 477 478 479Defines the ad status change callback. 480 481**Atomic service API**: This API can be used in atomic services since API version 12. 482 483**System capability**: SystemCapability.Advertising.Ads 484 485### onStatusChanged 486 487onStatusChanged(status: string, ad: advertising.[Advertisement](#advertisement), data: string) 488 489Called when the ad display status changes. 490 491**Atomic service API**: This API can be used in atomic services since API version 12. 492 493**System capability**: SystemCapability.Advertising.Ads 494 495| Name| Type| Mandatory| Description| 496| -------- | -------- | -------- | -------- | 497| 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**.| 498| ad | advertising.[Advertisement](#advertisement) | Yes| Content of the ad.| 499| data | string | Yes| Extended information.| 500 501**Example** 502 503```ts 504import { advertising } from '@kit.AdsKit'; 505 506let adInteractionListener: advertising.AdInteractionListener = { 507 onStatusChanged: (status: string, ad: advertising.Advertisement, data: string) => { 508 509 } 510} 511``` 512 513## getAdRequestBody<sup>12+</sup> 514getAdRequestBody(adParams: AdRequestParams[], adOptions: AdOptions): Promise<string> 515 516Obtains the body of an ad request. This API uses a promise to return the result. 517 518**System capability**: SystemCapability.Advertising.Ads 519 520**Parameters** 521| Name| Type| Mandatory| Description| 522| -------- | -------- | -------- | -------- | 523| adParams | [AdRequestParams[]](#adrequestparams) | Yes| Ad request parameters.| 524| adOptions | [AdOptions](#adoptions) | Yes| Ad configuration.| 525 526**Return value** 527 528| Type| Description| 529| -------- | -------- | 530| Promise<string> | Promise used to return the ad data of the string type.| 531 532**Error codes** 533 534For details about the following error codes, see [Ads Service Framework Error Codes](errorcode-ads.md). 535 536| ID| Error Message | 537| -------- | -------------------------------- | 538| 401 | Invalid input parameter. Possible causes: 1.Mandatory parameters are left unspecified | 539| 801 | Device not supported. | 540| 21800001 | System internal error. | 541 542**Example** 543 544```ts 545import { hilog } from '@kit.PerformanceAnalysisKit'; 546import { BusinessError } from '@kit.BasicServicesKit'; 547import { advertising } from '@kit.AdsKit'; 548import { Prompt } from '@kit.ArkUI'; 549 550function getAdRequestBody(): void { 551 let adReqParamsListForRequest: Array<advertising.AdRequestParams> = []; 552 const adReqParams: Record<string, Object> = { 553 'adId': 'testu7m3hc4gvm', 554 'adType': 3, 555 'adCount': 2, 556 'adWidth': 100, 557 'adHeight': 100 558 }; 559 560 adReqParamsListForRequest.push(adReqParams as advertising.AdRequestParams); 561 const adOption: Record<string, Object> = { 562 // 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. 563 'adContentClassification': 'A', 564 // 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. 565 'nonPersonalizedAd': 0, 566 // 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. 567 'tagForChildProtection': 1, 568 // 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. 569 'tagForUnderAgeOfPromise': -1 570 }; 571 advertising.getAdRequestBody(adReqParamsListForRequest, adOption as advertising.AdOptions).then((data) => { 572 hilog.info(0x0000, 'testTag', '%{public}s', `succeeded in getting AdRequestBody by promise: ${data}`); 573 Prompt.showToast({ 574 message: data, 575 duration: 1000 576 }); 577 }).catch((error: BusinessError) => { 578 hilog.error(0x0000, 'testTag', '%{public}s', 579 `getAdRequestBody failed, code: ${error.code}, message: ${error.message}`); 580 Prompt.showToast({ 581 message: error.code.toString() + ',' + error.message, 582 duration: 1000 583 }); 584 }) 585} 586``` 587 588## parseAdResponse<sup>12+</sup> 589 590parseAdResponse(adResponse: string, listener: MultiSlotsAdLoadListener, context: common.UIAbilityContext): void 591 592Parses the body of an ad response. 593 594**System capability**: SystemCapability.Advertising.Ads 595 596**Parameters** 597 598| Name| Type | Mandatory| Description | 599| ---------- | ------------------------------------------------------------ | ---- | ----------------------- | 600| adResponse | string | Yes | Ad request parameters. | 601| listener | [MultiSlotsAdLoadListener](#multislotsadloadlistener) | Yes | Ad request callback. | 602| context | common.[UIAbilityContext](../apis-ability-kit/js-apis-inner-application-uiAbilityContext.md) | Yes | UIAbility context.| 603 604**Error codes** 605 606For details about the following error codes, see [Ads Service Framework Error Codes](errorcode-ads.md). 607 608| ID| Error Message | 609| -------- | -------------------------------- | 610| 401 | Invalid input parameter. Possible causes: 1.Mandatory parameters are left unspecified | 611| 801 | Device not supported. | 612| 21800001 | System internal error. | 613| 21800005 | Failed to parse the ad response. | 614 615**Example** 616 617For details about how to obtain the context, see [Obtaining the Context of UIAbility](../apis-ability-kit/js-apis-inner-application-uiAbilityContext.md). 618 619```ts 620import { common } from '@kit.AbilityKit'; 621import { advertising } from '@kit.AdsKit'; 622import { hilog } from '@kit.PerformanceAnalysisKit'; 623 624function parseAdResponse(adResponse: string, context: common.UIAbilityContext): void { 625 // Listen for the ad parsing callback. 626 const multiSlotsAdLoaderListener: advertising.MultiSlotsAdLoadListener = { 627 // Called when ad parsing fails. 628 onAdLoadFailure: (errorCode: number, errorMsg: string) => { 629 hilog.error(0x0000, 'testTag', '%{public}s', 630 `request multi ads errorCode is: ${errorCode}, errorMsg is: ${errorMsg}`); 631 }, 632 // Called when ad parsing is successful. 633 onAdLoadSuccess: (ads: Map<string, Array<advertising.Advertisement>>) => { 634 hilog.info(0x0000, 'testTag', '%{public}s', 'succeeded in requesting multi ads!'); 635 // Save the parsed ad content as an array for display. 636 let returnAds: Array<advertising.Advertisement> = []; 637 ads.forEach((adsArray) => returnAds.push(...adsArray)); 638 } 639 }; 640 // Call the API to parse the response body. 641 hilog.info(0x0000, 'testTag', '%{public}s', 'parse ad response!'); 642 advertising.parseAdResponse(adResponse, multiSlotsAdLoaderListener, context); 643} 644``` 645 646## registerWebAdInterface<sup>12+</sup> 647 648registerWebAdInterface(controller: web_webview.WebviewController, context: common.UIAbilityContext): void 649 650Injects an ad JavaScript object to the **Web** component. 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**Parameters** 657 658 659| Name| Type| Mandatory| Description| 660| -------- | -------- | -------- | -------- | 661| controller | web_webview.[WebviewController](../apis-arkweb/js-apis-webview.md#webviewcontroller) | Yes| Controller of the **Web** component.| 662| context | common.[UIAbilityContext](../apis-ability-kit/js-apis-inner-application-uiAbilityContext.md) | Yes| UIAbility context.| 663 664 665**Error codes** 666 667 668For details about the following error codes, see [Ads Service Framework Error Codes](errorcode-ads.md). 669 670 671| ID| Error Message| 672| -------- | -------- | 673| 401 | Invalid input parameter. Possible causes: 1.Mandatory parameters are left unspecified | 674| 21800001 | System internal error. | 675 676 677**Example** 678 679```ts 680import { webview } from '@kit.ArkWeb'; 681import { common } from '@kit.AbilityKit'; 682import { advertising } from '@kit.AdsKit'; 683import { hilog } from '@kit.PerformanceAnalysisKit'; 684 685@Entry 686@Component 687struct Index { 688 private webController: webview.WebviewController = new webview.WebviewController(); 689 private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext; 690 691 build() { 692 Column() { 693 Button('Inject Ad Object to Web') 694 .onClick(() => { 695 try { 696 advertising.registerWebAdInterface(this.webController, this.context); 697 } catch (err) { 698 hilog.error(0x0000, 'testTag', '%{public}s', 699 `register web ad interface error: ${err.code}, ${err.message}`); 700 } 701 }) 702 703 Web({ 704 src: 'www.example.com', 705 controller: this.webController, 706 }) 707 .width("100%") 708 .height("100%") 709 } 710 } 711} 712``` 713