目录

AtomicServiceEnhancedWeb Reference

AtomicServiceEnhancedWeb is an advanced web component offering customization to meet specific demands. It shields irrelevant APIs from the ArkWeb component and extends functionality through JavaScript capabilities.

You can preview how this component looks on a real device, but not in DevEco Studio Previewer.

Constraints

To use this component, you must complete the development preparations. For details, see Developing the AtomicServiceEnhancedWeb Component.

Emulator Support

This component can run on Emulator since version 1.0.17.

Required Permissions

ohos.permission.INTERNET, required for accessing online web pages. For details about how to apply for a permission, see Declaring Permissions.

AtomicServiceEnhancedWeb

AtomicServiceEnhancedWeb({
  src: ResourceStr,
  controller: AtomicServiceEnhancedWebControll,
  navPathStack?: NavPathStack,
  mixedMode?: MixedMode,
  darkMode?: WebDarkMode,
  forceDarkAccess?: boolean,
  bgColor?: ResourceColor,
  nestedScroll?: NestedScrollOptions | NestedScrollOptionsExt,
  expandSafeAreaTypes: [SafeAreaType.SYSTEM],
  expandSafeAreaEdges: [SafeAreaEdge.TOP,SafeAreaEdge.BOTTOM],
  onMessage?: Callback<OnMessageEvent>,
  onErrorReceive?: Callback<OnErrorReceiveEvent>,
  onHttpErrorReceive?: Callback<OnHttpErrorReceiveEvent>,
  onPageBegin?: Callback<OnPageBeginEvent>,
  onPageEnd?: Callback<OnPageEndEvent>,
  onControllerAttached?: Callback<void>,
  onLoadIntercept?: Callback<OnLoadInterceptEvent, boolean>,
  onProgressChange?: Callback<OnProgressChangeEvent>,
  onTitleReceive?: Callback<OnTitleReceiveEvent>
})

Since: 1.0.12

Decorator: @Component

Parameters:

Name Type Default Value Mandatory Decorator Type Description
src ResourceStr - Yes - Web page resource address. Accessing network resources requires configuring service domain names in AppGallery Connect, and accessing local resources only supports files within the package ($rawfile). Dynamic updating of the address through state variables (for example, @State) is not supported. The loaded web page supports calling system capabilities through the APIs provided by the JS SDK, with the specifics governed by the JS SDK.
controller AtomicServiceEnhancedWebController - Yes @ObjectLink Used to control the behavior of the AtomicServiceEnhancedWeb component.
navPathStack NavPathStack - No - Information about the navigation stack. When NavDestination serves as the root container of the page, NavPathStack corresponding to the NavDestination container must be passed to handle page routing.
mixedMode MixedMode - No @Prop Whether to enable the loading of HTTP and HTTPS mixed content. By default, this feature is enabled.
darkMode WebDarkMode - No @Prop Web dark mode. By default, web dark mode is disabled.
forceDarkAccess boolean - No @Prop Whether to enable forcible dark mode for the web page. This feature is disabled by default. This API is effective only when web dark mode is enabled.
bgColor ResourceColor - No @Prop Background color of the component.
nestedScroll15+ NestedScrollOptions | NestedScrollOptionsExt - No @Prop Nested scrolling options.
expandSafeAreaTypes Array<SafeAreaType> [] No @Prop

Types of non-safe areas to extend into. If the Metadata configuration item is not added, the hole is not avoided on the page, and the CUTOUT type does not take effect.

Invalid values are treated as the default value.

Since: 1.0.23

expandSafeAreaEdges Array<SafeAreaEdge> [] No @Prop

Edges for expanding the safe area.

Invalid values are treated as the default value.

Since: 1.0.23

onMessage Callback<OnMessageEvent> - No - Callback invoked when the HTML5 page sends a message through the postMessage() API of the JS SDK, and the Web component's corresponding page is returned or destroyed.
onErrorReceive Callback<OnErrorReceiveEvent> - No - Callback triggered when an error occurs during web page loading. For performance reasons, simplify the implementation logic in the callback. This callback is invoked when there is no network connection.
onHttpErrorReceive Callback<OnHttpErrorReceiveEvent> - No - Callback invoked when an HTTP error (the response code is greater than or equal to 400) occurs during web page resource loading.
onPageBegin Callback<OnPageBeginEvent> - No - Callback invoked when the web page starts loading. It is invoked only for the main frame content, and not for the iframe or frameset content.
onPageEnd Callback<OnPageEndEvent> - No - Callback invoked when the web page loading is complete. It is invoked only for the main frame content.
onControllerAttached Callback<void> - No - Callback invoked when a controller is attached to the Web component.
onLoadIntercept OnLoadInterceptCallback - No - Callback invoked when the Web component is about to load the URL. It is used to determine whether to block the loading. By default, the loading is allowed.
onProgressChange Callback<OnProgressChangeEvent> - No - Callback invoked when the web page loading progress changes.
onTitleReceive Callback<OnTitleReceiveEvent> - No - Callback triggered when the document title of the application page is changed. If the <title> element is not set on the page to load, AtomicServiceEnhancedWeb generates a title based on the URL and returns it to the application.

The expandSafeAreaTypes and expandSafeAreaEdges parameters must be used together. If only one of them is used, the setting does not take effect.

AtomicServiceEnhancedWebController

Manages the behavior of the AtomicServiceEnhancedWeb component. An AtomicServiceEnhancedWebController object can control only one AtomicServiceEnhancedWeb component, and the APIs on the AtomicServiceEnhancedWebController can be called only after it has been bound to the target AtomicServiceEnhancedWeb component.

Since: 1.0.12

Decorator type: @Observed

[h2]getUserAgent

getUserAgent(): string

Obtains the default user agent.

Since: 1.0.12

Returns:

Type Description
string Default user agent. For details about the default User-Agent definition and its application scenarios, see Developing User-Agent.

Error codes:

For details about the error codes, see Webview Error Codes.

Error Code Error Message
17100001 Init error. The AtomicServiceEnhancedWebController must be associated with a AtomicServiceEnhancedWeb component.

[h2]getCustomUserAgent

getCustomUserAgent(): string

Obtains the custom user agent.

Since: 1.0.12

Returns:

Type Description
string Information about the custom user agent.

Error codes:

For details about the error codes, see Webview Error Codes.

Error Code Error Message
17100001 Init error. The AtomicServiceEnhancedWebController must be associated with a AtomicServiceEnhancedWeb component.

[h2]setCustomUserAgent

setCustomUserAgent(userAgent: string): void

Sets a custom user agent, which will override the default user agent.

Set the user agent in the onControllerAttached callback to ensure that it takes effect. For details about the setting, see the example.

Avoid setting User-Agent in onLoadIntercept. Otherwise, the setting may fail occasionally.

If a URL is set for the Web component src and User-Agent is not set in the onControllerAttached callback, calling setCustomUserAgent may cause mismatches between the loaded page and the intended User-Agent.

Since: 1.0.12

Parameters:

Name Type Mandatory Description
userAgent string Yes Information about the custom user agent. It is recommended that you obtain the current default user agent through getUserAgent and then customize the obtained user agent.

Error codes:

For details about the error codes, see Webview Error Codes.

Error Code Error Message
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types.
17100001 Init error. The AtomicServiceEnhancedWebController must be associated with a AtomicServiceEnhancedWeb component.

[h2]refresh

refresh(): void

Instruct the AtomicServiceEnhancedWeb component to refresh the web page.

Since: 1.0.12

Error codes:

For details about the error codes, see Webview Error Codes.

Error Code Error Message
17100001 Init error. The AtomicServiceEnhancedWebController must be associated with a AtomicServiceEnhancedWeb component.

[h2]forward

forward(): void

Navigates forward to the next page in the history stack. This API is generally used together with accessForward.

Since: 1.0.12

Error codes:

For details about the error codes, see Webview Error Codes.

Error Code Error Message
17100001 Init error. The AtomicServiceEnhancedWebController must be associated with a AtomicServiceEnhancedWeb component.

[h2]backward

backward(): void

Navigates backward to the previous page in the history stack. This API is generally used together with accessBackward.

Since: 1.0.12

Error codes:

For details about the error codes, see Webview Error Codes.

Error Code Error Message
17100001 Init error. The AtomicServiceEnhancedWebController must be associated with a AtomicServiceEnhancedWeb component.

[h2]accessForward

accessForward(): boolean

Checks whether going to the next page can be performed on this page.

Since: 1.0.12

Returns:

Type Description
boolean true is returned if going to the next page can be performed on the current page; otherwise, false is returned.

Error codes:

For details about the error codes, see Webview Error Codes.

Error Code Error Message
17100001 Init error. The AtomicServiceEnhancedWebController must be associated with a AtomicServiceEnhancedWeb component.

[h2]accessBackward

accessBackward(): boolean

Checks whether going to the previous page can be performed on the current page.

Since: 1.0.12

Returns:

Type Description
boolean Returns true if going to the previous page can be performed on the current page; returns false otherwise.

Error codes:

For details about the error codes, see Webview Error Codes.

Error Code Error Message
17100001 Init error. The AtomicServiceEnhancedWebController must be associated with a AtomicServiceEnhancedWeb component.

[h2]accessStep

accessStep(step: number): boolean

Checks whether this page can navigate forward or backward by the specified number of steps.

Since: 1.0.12

Parameters:

Name Type Mandatory Description
step number Yes Number of steps to navigate. Positive values indicate forward, while negative values indicate backward.

Returns:

Type Description
boolean Whether the page can navigate forward or backward by the specified number of steps.

Error codes:

For details about the error codes, see Webview Error Codes.

Error Code Error Message
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed.
17100001 Init error. The AtomicServiceEnhancedWebController must be associated with a AtomicServiceEnhancedWeb component.

[h2]loadUrl

loadUrl(url: string | Resource, headers?: Array<WebHeader>): void

Loads a specified URL.

Since: 1.0.12

Parameters:

Name Type Mandatory Description
url string | Resource Yes URL to load.
headers Array<WebHeader> No Additional HTTP headers of the URL.

Error codes:

For details about the error codes, see Webview Error Codes.

Error Code Error Message
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed.
17100001 Init error. The AtomicServiceEnhancedWebController must be associated with a AtomicServiceEnhancedWeb component.
17100002 Invalid url.
17100003 Invalid resource path or file type.

WebHeader

Represents the request/response header object returned by the Web component.

Since: 1.0.12

Name Type Readable Writable Description
headerKey string Yes Yes Key of the request or response header.
headerValue string Yes Yes Value of the request or response header.

OnMessageEvent

Represents the callback invoked when the page is navigated back or destroyed.

Since: 1.0.12

Name Type Mandatory Description
data object[] Yes Message list.

OnErrorReceiveEvent

Represents the callback invoked when an error occurs during web page loading.

Since: 1.0.12

Name Type Mandatory Description
request WebResourceRequest Yes Encapsulation of a web page request.
error WebResourceError Yes Encapsulation of a web page resource loading error.

OnHttpErrorReceiveEvent

Represents the callback invoked when an HTTP error occurs during web page resource loading.

Since: 1.0.12

Name Type Mandatory Description
request WebResourceRequest Yes Encapsulation of a web page request.
response WebResourceResponse Yes Encapsulation of a resource response.

OnPageBeginEvent

Represents the callback invoked when the web page loading begins.

Since: 1.0.12

Name Type Mandatory Description
url string Yes URL of the page.

OnPageEndEvent

Represents the callback invoked when the web page loading ends.

Since: 1.0.12

Name Type Mandatory Description
url string Yes URL of the page.

OnLoadInterceptEvent

Represents the event triggered when resource loading is intercepted.

Since: 1.0.12

Name Type Mandatory Description
data WebResourceRequest Yes Encapsulation of a web page request.

OnProgressChangeEvent

Represents the callback invoked when the web page loading progress changes.

Since: 1.0.12

Name Type Mandatory Description
newProgress number Yes New loading progress. The value is an integer ranging from 0 to 100.

OnTitleReceiveEvent

Defines the callback triggered when the document title of the web page changes.

Since: 1.0.12

Name Type Mandatory Description
title string Yes Document title.

OnLoadInterceptCallback

type OnLoadInterceptCallback = (event: OnLoadInterceptEvent) => boolean

Represents the callback invoked when resource loading is intercepted.

Since: 1.0.12

Parameters:

Name Type Mandatory Description
event OnLoadInterceptEvent Yes Event triggered when resource loading is intercepted.

Returns:

Type Description
boolean Whether the resource is intercepted.

APIs

[h2]has.router.pushUrl

pushUrl(options: object): void

Retains the current page and jumps to the target page.

Since: 1.0.12

Parameters:

Name Type Mandatory Description
url string Yes URL of the target page.
params object No Parameters passed to the target page.
mode string No

Routing modes. The options are Standard and Single. The default value is Standard.

- Standard: multi-instance mode. It is the default instance mode. The target page is added to the top of the page stack, regardless of whether a page with the same URL exists in the stack.

- Single: singleton mode. If the URL of the target page already exists in the page stack, the page is moved to the top of the stack. If the URL of the target page does not exist in the page stack, the page is redirected to in multi-instance mode.

callback function No Callback method. Method declaration: (err, res) => void.

Example:

has.router.pushUrl({
  url: 'pages/Index',
  params: { name: 'Peter' },
  mode: 'Single',
  callback: (err, res) => {
  }
});

[h2]has.router.replaceUrl

replaceUrl(options: object): void

Destroys the current page and jumps to the target page.

Since: 1.0.12

Parameters:

Name Type Mandatory Description
url string Yes URL of the target page.
params object No Parameters passed to the target page.
mode string No

Routing modes. The options are Standard and Single. The default value is Standard.

- Standard: multi-instance mode. It is the default instance mode. The target page is added to the top of the page stack, regardless of whether a page with the same URL exists in the stack.

- Single: singleton mode. If the URL of the target page already exists in the page stack, the page is moved to the top of the stack. If the URL of the target page does not exist in the page stack, the page is redirected to in multi-instance mode.

callback function No Callback method. Method declaration: (err, res) => void.

Example:

has.router.replaceUrl({
  url: 'pages/Index',
  params: { name: 'Peter' },
  mode: 'Standard',
  callback: (err, res) => {
  }
});

[h2]has.router.back

back(options: object): void

Returns to the previous page.

Since: 1.0.12

Parameters:

Among the url, index, and delta parameters (in descending order of priority), only one of them takes effect at a time. If none of them is passed in, the previous page is displayed.

Name Type Mandatory Description
url string No URL of the page to return to.
index number No Index of the page to return to. The index is sequentially numbered starting from 1 based on the order in which pages are opened.
delta number No Level of pages to be returned to at a time. If the level exceeds the value allowed by delta, the home page is displayed.
params object No Parameters passed to the page to return to.
callback function No Callback method. Method declaration: (err, res) => void.

Example:

has.router.back({
  delta: 2,
  params: { name: 'Peter' },
  callback: (err, res) => {
  }
});

[h2]has.router.clear

clear(options: object): void

Clears all historical pages but retains the current page.

Since: 1.0.12

Parameters:

Name Type Mandatory Description
callback function No Callback method. Method declaration: (err, res) => void.

Example:

has.router.clear({
  callback: (err, res) => {
  }
});

[h2]has.navPathStack.pushPath

pushPath(options: object): void

Pushes a page to the stack.

Since: 1.0.12

Parameters:

Name Type Mandatory Description
name string Yes Name of the page to be pushed to the stack.
param object No Parameters of the page to be pushed to the stack.
animated boolean No Whether to support transition animation. Default value: true.
onPop function No Callback triggered when the page is popped from the stack. Method declaration: (event: OnPopEvent) => void.
callback function No Callback method. Method declaration: (err, res) => void.

OnPopEvent

Name Type Description
name string Name of the page popped from the stack.
param object Parameters of the page popped from the stack.
result object Pop result.

Example:

has.navPathStack.pushPath({
  name: 'PageOne',
  param: { name: 'Peter' },
  animated: true,
  onPop: event => {
  },
  callback: (err, res) => {
  }
});

[h2]has.navPathStack.replacePath

replacePath(options: object): void

Exits the top page and destroys it.

Since: 1.0.12

Parameters:

Name Type Mandatory Description
name string Yes Name of the page to be pushed to the stack.
param object No Parameters of the page to be pushed to the stack.
animated boolean No Whether to support transition animation. Default value: true.
onPop function No Callback triggered when the page is popped from the stack. Method declaration: (event: OnPopEvent) => void.
callback function No Callback method. Method declaration: (err, res) => void.

OnPopEvent

Name Type Description
name string Name of the page popped from the stack.
param object Parameters of the page popped from the stack.
result object Pop result.

Example:

has.navPathStack.replacePath({
  name: 'PageOne',
  param: { name: 'Peter' },
  animated: true,
  onPop: event => {
  },
  callback: (err, res) => {
  }
});

[h2]has.navPathStack.pop

pop(options: object): void

Navigates back to the previous page.

Since: 1.0.12

Parameters:

Among the name, index, and delta parameters (in descending order of priority), only one of them takes effect at a time. If none of them is passed in, the previous page is displayed.

Name Type Mandatory Description
name string No Name of the page to return to.
index number No Index of the page to return to. The value of index starts from -1, which indicates the navigation root page. Value 0 indicates the first opened subpage of NavDestination, and subsequent values follow the same rule.
delta number No Number of pages to return to.
result object No Page return result.
animated boolean No Whether to support transition animation. Default value: true.
callback function No Callback method. Method declaration: (err, res) => void.

Returns:

Name Type Description
name string Name of the top page after the pop operation.
index number Index of the top page after the pop operation.
param object Parameters of the top page after the pop operation.

Example:

has.navPathStack.pop({
  name: 'PageIndex',
  result: { name: 'Peter' },
  animated: true,
  callback: (err, res) => {
  }
});

[h2]has.navPathStack.clear

clear(options: object): void

Clears all pages in the stack but retains the top page.

Since: 1.0.12

Parameters:

Name Type Mandatory Description
animated boolean No Whether to support transition animation. Default value: true.
callback function No Callback method. Method declaration: (err, res) => void.

Example:

has.navPathStack.clear({
  animated: true,
  callback: (err, res) => {
  }
});

[h2]has.asWeb.postMessage

postMessage(options: object): void

Sends a message. When a page is returned or destroyed, the onMessage() callback is triggered for the AtomicServiceEnhancedWeb component.

Since: 1.0.12

Parameters:

Name Type Mandatory Description
data object Yes Message content.
callback function No Callback method. Method declaration: (err, res) => void.

Example:

has.asWeb.postMessage({
  data: { name: 'Peter' },
  callback: (err, res) => {
  }
});

// ArkTS page.
AtomicServiceEnhancedWeb({
  src: $rawfile("Index.html"),
  onMessage: (event) => {
    console.info('onMessage data: ', event.data);
  }
})

[h2]has.asWeb.getEnv

getEnv(options: object): void

Obtains the current environment information.

Since: 1.0.12

Parameters:

Name Type Mandatory Description
callback function No Callback method. Method declaration: (err, res) => void.

Returns:

Name Type Description
deviceType string Device type.
brand string Device brand.
productModel string Product model.
osFullName string OS version.

Example:

has.asWeb.getEnv({
  callback: (err, res) => {
  }
});

[h2]has.asWeb.checkJsApi

checkJsApi(options: object): void

Checks whether the specified JS APIs are supported.

Since: 1.0.12

Parameters:

Name Type Mandatory Description
jsApiList string[] Yes List of JS APIs.
callback function No Callback method. Method declaration: (err, res) => void.

Returns:

Name Type Description
checkResult Map<string, boolean> JS API check result.

Example:

has.asWeb.checkJsApi({
  jsApiList: ['router.back', 'navPathStack.clear', 'postMessage'],
  callback: (err, res) => {
  }
});

[h2]has.cameraPicker.pick

pick(options: object): void

Takes a photo or records a video.

Since: 1.0.12

Parameters:

Name Type Mandatory Description
mediaTypes string[] Yes Media type. The options are photo and video.
cameraPosition number Yes

Camera position. The options are as follows:

0: unspecified position.

1: rear camera.

2: front camera.

3: folded camera.

saveUri string No URI for saving the result.
videoDuration number No Maximum recording duration.
callback function No Callback method. Method declaration: (err, res) => void.

Returns:

Name Type Description
resultCode number Result code. The value 0 means that the processing is successful, and -1 means that the processing fails.
resultUri string URI of the result. If saveUri is empty, resultUri indicates the public media path. If saveUri is not empty and the application has the write permission on the URI, the value of resultUri is the same as that of saveUri. If saveUri is not empty and the application does not have the write permission on the URI, resultUri cannot be obtained.
mediaType string Returned media type. The options are photo and video.

Example:

has.cameraPicker.pick({
  mediaTypes: ['photo', 'video'],
  cameraPosition: 1,
  saveUri: '',
  videoDuration: 30,
  callback: (err, res) => {
  }
});

[h2]has.photoViewPicker.select

select(options: object): void

Takes or selects a photo.

Since: 1.0.12

Parameters:

Name Type Mandatory Description
mimeType string No Media file type. If this parameter is not specified, the image and video types are used by default. The options are image/*, video/*, and */*.
maxSelectNumber number No Maximum number of media files that can be selected. The default value is 50, and the maximum value is 500.
isPhotoTakingSupported boolean No Whether to support photographing.
isEditSupported boolean No Whether to support image editing.
isSearchSupported boolean No Whether to support search.
recommendationType number No Whether to support image recommendation.
preselectedUris string[] No URI of the preselected image.
callback function No Callback method. Method declaration: (err, res) => void.

Returns:

Name Type Description
photoUris string[] URI array of the media files selected from Gallery. The URI array can be used only by the photoAccessHelper.getAssets API in temporary authorization mode.
isOriginalPhoto boolean Whether the selected media file is the original image.

Example:

has.photoViewPicker.select({
  maxSelectNumber: 9,
  callback: (err, res) => {
  }
});

[h2]has.getLocalImgData

getLocalImgData(options: object): void

Obtains a local image.

Since: 1.0.12

Parameters:

Name Type Mandatory Description
uri string Yes URI of the file.
compressionRatio number No Compression ratio. The value range is [0,1], with the default value of 0.3.
success function No Callback invoked when the API call is successful.
fail function No Callback invoked when the API call fails.
complete function No Callback to be invoked when the API call is complete, regardless of success or failure.

Returns

Name Type Description
localData string Base64 data of the image.

Example:

has.getLocalImgData({
  uri: '/data/storage/el2/base/haps/entry/cache/example.jpg',
  compressionRatio: 0.3,
  success: (res) => {
    let localData = res.localData;
  },
  fail: (err) => {
  },
  complete: (res) => {
  }
});

[h2]has.filePreview.openPreview

openPreview(options: object): void

Previews a file. Only local files can be previewed.

Since: 1.0.12

Parameters:

Name Type Mandatory Description
title string No File title.
uri string Yes URI of the file.
mimeType string No Media resource type of the file or folder, for example, text/plain.
callback function No Callback method. Method declaration: (err, res) => void.

mimeType description

Type File Name Extension MIME Type
Text txt, cpp, c, h, java, xhtml, and xml text/plain, text/x-c++src, text/x-csrc, text/x-chdr, text/x-java, application/xhtml+xml, and text/xml
Web page html and htm text/html
Image jpg, png, gif, webp, bmp, and svg image/jpeg, image/png, image/gif, image/webp, image/bmp, and image/svg+xml
Audio m4a, aac, mp3, ogg, and wav audio/mp4a-latm, audio/aac, audio/mpeg, audio/ogg, and audio/x-wav
Video mp4, mkv, and ts video/mp4, video/x-matroska, and video/mp2ts
Folder N/A N/A

Example:

has.filePreview.openPreview({
  title: 'Image Preview',
  uri: '/data/storage/el2/base/haps/entry/cache/example.jpg',
  mimeType: 'image/jpeg',
  callback: (err, res) => {
  }
});

[h2]has.request.uploadFile

uploadFile(options: object): void

Uploads a file.

Since: 1.0.12

Required permission: ohos.permission.INTERNET, which needs to be declared in module.json5

Precautions: Before calling this API, you need to configure the server domain name.

Parameters:

Name Type Mandatory Description
url string Yes URL of the file to upload.
header object No Request header.
method string No Request method. The default value is POST.
files UploadFile[] Yes File to upload.
data UploadRequestData[] No Form data in the request body.
callback function No Callback method. Method declaration: (err, res) => void.

Returns:

Name Type Description
taskStates UploadFileTaskState[] Result of the file upload task.
headers object Response headers.
body object Response body.

Example:

has.request.uploadFile({
  url: 'https://www.example.com/upload',
  header: { 'Accept': '*/*' },
  method: 'POST',
  files: [{
    filename: 'example.jpg',
    name: 'file',
    uri: '/data/storage/el2/base/haps/entry/cache/example.jpg',
    type: 'jpg'
  }],
  data: [{
    name: 'key1',
    value: 'value1'
  }],
  callback: (err, res) => {
  }
});

[h2]has.request.downloadFile

downloadFile(options: object): void

Downloads a file.

Since: 1.0.12

Required permission: ohos.permission.INTERNET, which needs to be declared in module.json5

Precautions: Before calling this API, you need to configure the server domain name.

Parameters:

Name Type Mandatory Description
url string Yes URL of the file to download.
header object No Request header.
fileName string No Name of the downloaded file.
enableMetered boolean No Whether to allow downloads over metered connections. The default value is false. Mobile data connections are considered metered, while Wi-Fi connections are typically non-metered.
enableRoaming boolean No Whether to allow downloads on a roaming network. The default value is false.
networkType number No Type of the network that allows download. The default value is NETWORK_MOBILE&NETWORK_WIFI. You can set the type to NETWORK_MOBILE (0x00000001) or NETWORK_WIFI (0x00010000) as required.
callback function No Callback method. Method declaration: (err, res) => void.

Returns:

Name Type Description
uri uri URI for saving the file.

Example:

has.request.downloadFile({
  url: 'https://www.example.com/test.jpg',
  fileName: 'test.jpg',
  callback: (err, res) => {
  }
});

[h2]has.connection.getNetworkType

getNetworkType(options: object): void

Obtains the network status.

Since: 1.0.12

Required permission: ohos.permission.GET_NETWORK_INFO, which must be declared in module.json5

Parameters:

Name Type Mandatory Description
callback function No Callback method. Method declaration: (err, res) => void.

Returns:

Name Type Description
bearerTypes number[] Network type. The value 0 indicates the cellular network, 1 indicates the Wi-Fi network, and 2 indicates the Ethernet network.
networkCap number[] Network capability. The value 0 indicates that the network can access the MMSC of the carrier to send and receive MMS messages. 11 indicates that the network traffic is not charged. 12 indicates that the network must have the capability of accessing the Internet. 15 indicates that the network does not use the VPN. 16 indicates that the Internet access capability of the network is successfully verified by the network management module.
linkUpBandwidthKbps number Uplink (device-to-network) bandwidth, in kbit/s. The value 0 indicates that the network bandwidth cannot be evaluated.
linkDownBandwidthKbps number Downlink (network-to-device) bandwidth, in kbit/s. The value 0 indicates that the network bandwidth cannot be evaluated.

Example:

has.connection.getNetworkType({
  callback: (err, res) => {
  }
});

[h2]has.location.getLocation

getLocation(options: object): void

Obtains the current geographic location.

The accurate location is used when priority is set to 0x201 (accuracy priority) scenario is set to 0x301 (navigation), 0x302 (trajectory tracking), or 0x303 (ride hailing), or maxAccuracy is set to a value less than 50. Otherwise, the approximate location is used.

Since: 1.0.12

Required permissions: ohos.permission.APPROXIMATELY_LOCATION, which needs to be declared in module.json5 for approximate location; declare ohos.permission.LOCATION and ohos.permission.APPROXIMATELY_LOCATION, which need to be declared in module.json5 for accurate location

Parameters:

Name Type Mandatory Description
priority number No Priority of a location request. The options are as follows: This parameter is effective only when scenario is set to UNSET. If this parameter and scenario are both set to UNSET, the attempt to initiate a location request will fail.
scenario number No Scenario of a location request. The options are as follows: This parameter is effective only when scenario is set to UNSET. If this parameter and scenario are both set to UNSET, the attempt to initiate a location request will fail.
maxAccuracy number No Location accuracy, in meters.
timeoutMs number No Timeout duration, in milliseconds. The minimum value is 1000. The value must be greater than or equal to 1000.

priority Values

Value Description
0x200 priority is not set, indicating it is invalid.
0x201

Location accuracy preferred.

The location accuracy priority mainly uses the GNSS positioning technology. The system uses the network positioning technology as an alternative to provide the location service for your application until the GNSS can provide stable location results. During the continuous location process, the network positioning technology is used if the GNSS location result cannot be obtained within 30 seconds. This policy can lead to significant hardware resource consumption and power consumption.

0x202

Power efficiency preferred.

This policy uses only the network positioning technology to obtain device location in both indoor and outdoor scenarios. The location accuracy depends on the distribution of surrounding base stations, visible WLANs, and Bluetooth devices and therefore may fluctuate greatly. This policy is recommended and can reduce power consumption if a high location accuracy is not required.

0x203

Fast location preferred. Use this option if you want to obtain a location as fast as possible.

This policy uses the GNSS positioning and network positioning technologies simultaneously to obtain the device location in both the indoor and outdoor scenarios. When all positioning technologies provide a location result, the system provides the most accurate location result for your application. It can lead to significant hardware resource consumption and power consumption.

scenario Values

Value Description
0x300 scenario is not set, indicating it is invalid.
0x301

Navigation scenario.

This option is applicable when your application needs to obtain the real-time location of a mobile device outdoors, such as navigation for driving or walking.

This option mainly uses the GNSS positioning technology and therefore the power consumption is relatively high.

0x302

Trajectory tracking scenario.

This option is applicable when your application needs to record user trajectories, for example, the track recording function of sports applications.

This option mainly uses the GNSS positioning technology and therefore the power consumption is relatively high.

0x303

Ride hailing scenario.

Applicable when your application needs to obtain the current location of a user who is hailing a taxi.

This option mainly uses the GNSS positioning technology and therefore the power consumption is relatively high.

0x304

Daily life service scenario.

This option is applicable when your application only needs the approximate location in scenarios such as when the user is browsing news, shopping online, and ordering food.

It mainly uses the network positioning technology and therefore the power consumption is relatively low.

0x305

passive location scenario.

In this scenario, location tracking is not actively triggered; the location is returned to the application only when other applications trigger location requests.

Returns:

Name Type Description
latitude number Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude. The value ranges from -90 to 90.
longitude number Longitude information. A positive value indicates east longitude, and a negative value indicates west longitude. The value ranges from -180 to 180.
altitude number Location altitude, in meters.
accuracy number Location accuracy, in meters.
speed number Speed, in m/s.
timeStamp number Location timestamp in the UTC format.
direction number Direction information. The value ranges from 0 to 360, in degrees.
timeSinceBoot number Location timestamp since boot.
additions string[] Additional description.
additionSize number Number of additional descriptions. The value must be greater than or equal to 0.

Example:

has.location.getLocation({
  priority: 0x203,
  scenario: 0x300,
  maxAccuracy: 0,
  timeoutMs: 5000,
  callback: (err, res) => {
  }
});

[h2]has.authorize

has.authorize(Object object): void

Initiates an authorization request to a user in advance. After the API is called, a dialog box will be displayed immediately, asking the user to authorize the atomic service to use a feature or acquire user data. However, it will not actually call the corresponding API to use the feature or acquire the data. If the user has already agreed to the authorization, no dialog box is displayed and a success message is returned directly.

Since: 1.0.23

Parameters:

The input parameter is an object containing the following fields.

Property Type Mandatory Description
scope string Yes

Scope of the permission to be obtained. For details, see Scope List.

Note: Only the camera lens (scope.camera) and microphone (scope.microphone) permissions can be requested.

success function No Callback invoked when the API call is successful.
fail function No Callback invoked when the API call fails.
complete function No Callback to be invoked when the API call is complete, regardless of success or failure.

To apply for permissions, declare all the permissions one by one in the project configuration file. For details about the configuration method, see Declaring Permissions.

Example:

has.authorize({
  scope: 'scope.camera',
  success: () => {
    console.info('authorize success');
  },
  fail: (err) => {
    console.error('authorize fail', err);
  },
  complete: (res) => {
    console.info('authorize complete', res);
  }
});

[h2]has.login

has.login(Object object): void

Obtains the login credential (code). The credential is used to obtain the user login information, including the unique user identifier in the application (openid), the unique identifier of the platform account (unionid), and the session key of the current login (session_key). The session key is used to encrypt and decrypt user data.

Since: 1.0.12

Parameters:

The input parameter is an object containing the following fields.

Property Type Default Value Mandatory Description
success function - No Callback invoked when the API call is successful.
fail function - No Callback invoked when the API call fails.
complete function - No Callback to be invoked when the API call is complete, regardless of success or failure.

Return values of success

Property Type Description
code string Sign-in credential of the user (valid for 5 minutes).
idToken string User information in JWT format.
openID string Identifier of a HUAWEI ID user when using different applications. A user has different OpenIDs for different applications.
unionID string Identifier of a HUAWEI ID user in different applications of the same developer. A user has the same UnionID for different applications of the same developer.

Example:

has.login({
  success: (res) => {
    console.info('login success', res);
  },
  fail: (err) => {
    console.error('login fail', err);
  },
  complete: (res) => {
    console.info('login complete', res);
  }
});

[h2]has.requestSubscribeMessage

has.requestSubscribeMessage(Object object)

Subscribes to messages.

Since: 1.0.12

Parameters:

The input parameter is an object containing the following fields.

Parameter Type Default Value Mandatory Description
tmplIds Array<string> - Yes IDs of the message templates to be subscribed to. A maximum of three messages can be subscribed to at a time.
success function - No Callback invoked when the API call is successful.
fail function - No Callback invoked when the API call fails.
complete function - No Callback to be invoked when the API call is complete, regardless of success or failure.

Return values of success

Parameter Type Description
errMsg string 'requestSubscribeMessage:ok' if the API call is successful.
[TEMPLATE_ID:string] string

TEMPLATE_ID indicates the template ID. The string can be any of the following:

- 'accept': The user agrees to subscribe to the message of the specified template.

- 'reject': The user rejects to subscribe to the message of the specified template.

- 'ban': The template is banned by the background.

- 'filter': The template is filtered out by the background due to duplicate template titles.

Example:

has.requestSubscribeMessage({
  tmplIds: [''],
  success: (res) => {
    console.info('requestSubscribeMessage success', res);
  },
  fail: (err) => {
    console.error('requestSubscribeMessage fail', err);
  },
  complete: (res) => {
    console.info('requestSubscribeMessage complete', res);
  }
});

[h2]has.queryIapEnvStatus

has.queryIapEnvStatus(Object object)

Checks whether the logged-in account is located in a country or region where IAP is available. The IAP service is currently available only in the Chinese mainland.

Required permissions: Before development, you need to configure the client ID, configure the signing certificate fingerprint, enable merchant service, and enable and activate IAP Kit.

Since: 1.0.12

Parameters:

The input parameter is an object containing the following fields.

Parameter Type Default Value Mandatory Description
success function - No Callback invoked when the API call is successful.
fail function - No Callback invoked when the API call fails.
complete function - No Callback to be invoked when the API call is complete, regardless of success or failure.

Return value of fail

Result Code Error Message
401 Parameter error.
1001860000 The operation was canceled by the user.
1001860001 System internal error.
1001860004 Too frequent API calls.
1001860005 Network connection error.
1001860050 The HUAWEI ID is not signed in.
1001860054 The country or region of the signed-in HUAWEI ID does not support IAP.

Example:

has.queryIapEnvStatus({
  success: () => {
    console.info('queryIapEnvStatus success');
  },
  fail: (err) => {
    console.error('queryIapEnvStatus fail', err);
  },
  complete: (res) => {
    console.info('queryIapEnvStatus complete', res);
  }
});

[h2]has.createIap

has.createIap(Object object)

Initiates a purchase. Consumables, non-consumables, and auto-renewable subscriptions are supported. After a user initiates a purchase for a product already configured in AppGallery Connect, this API brings up the checkout screen of IAP Kit to show information such as the product name and price.

Required permissions: Before development, you need to configure the client ID, configure the signing certificate fingerprint, enable merchant service, and enable and activate IAP Kit.

Since: 1.0.12

Parameters:

The input parameter is an object containing the following fields.

Parameter Type Default Value Mandatory Description
productId string - Yes ID of the product to purchase. The product IDs come from the product information you have configured in AppGallery Connect. For details, see Configuring Products.
productType number - Yes

Type of products to be queried.

- 0: consumables

- 1: non-consumables

- 2: auto-renewable subscription

- 3: non-renewable subscription

developerPayload string - No

Information provided by the merchant.

If this parameter contains a value, it will be returned to the application unchanged in the payment-success callback result.

NOTE

The value length is [0, 256].

reservedInfo string - No

Additional information passed via a JSON string in key-value format.

Example:

let reservedInfo = "{"key1":"value1","key2":"value2"}";

NOTE

This field is reserved and optional.

promotionalOfferId string - No Promotional offer ID. The value is the promotion identifier set by you when configuring product information in the AppGallery Connect. For details, see Auto-renewable Subscriptions. The parameter is valid only when being passed with jwsRepresentation.
applicationUserName string - No Obfuscated string that uniquely identifies a user's account. This parameter can be passed when promotionalOfferId is passed.
jwsRepresentation string - No Signature data containing purchase parameters, such as the promotion information, in JWS format. For details, see Generating a Signed Purchase Parameter for a Promotion.
success function - No Callback invoked when the API call is successful.
fail function - No Callback invoked when the API call fails.
complete function - No Callback to be invoked when the API call is complete, regardless of success or failure.

Return value of success

Parameter Type Description
purchaseData string JSON string containing the payment result. For details about the parameters, see PurchaseData.

Return value of fail

Result Code Error Message
102 Param error
401 Parameter error.
1001860000 The operation was canceled by the user.
1001860001 System internal error.
1001860002 The application is not authorized.
1001860003 Invalid product information.
1001860004 Too frequent API calls.
1001860005 Network connection error.
1001860007 The app to which the product belongs is not released in a specified location.
1001860051 Failed to purchase a product because the user already owns the product.
1001860054 The country or region of the signed-in HUAWEI ID does not support IAP.
1001860056 The user is not allowed to make purchase.
1001860059 Invalid promotional offer id.
1001860060 Invalid purchase signature.

Example:

has.createIap({
  // Replace it with the actual product ID.
  productId: 'product_id',
  productType: 0,
  developerPayload: '',
  reservedInfo: JSON.stringify({ key1: 'value1' }),
  promotionalOfferId: '',
  applicationUserName: '',
  jwsRepresentation: '',
  success: (res) => {
    console.info('createIap success', res);
  },
  fail: (err) => {
    console.error('createIap fail', err);
  },
  complete: (res) => {
    console.info('createIap complete', res);
  }
});

[h2]has.finishIap

has.finishIap(Object object)

Finalizes the purchase transaction. This API is called after the purchased product is delivered.

Required permissions: Before development, you need to configure the client ID, configure the signing certificate fingerprint, enable merchant service, and enable and activate IAP Kit.

Since: 1.0.12

Parameters:

The input parameter is an object containing the following fields.

Parameter Type Default Value Mandatory Description
productType number - Yes

Type of products to be queried.

- 0: consumables

- 1: non-consumables

- 2: auto-renewable subscription

- 3: non-renewable subscription

purchaseToken string - Yes

Purchase token returned in the purchase order.

For a single purchase, the value corresponds to a purchase order. For a subscription purchase, the value corresponds to a subscription ID.

The value is returned by the has.createIap or has.queryIap API.

purchaseOrderId string - Yes

Order ID returned after a purchase.

The value is returned by the has.createIap or has.queryIap API.

success function - No Callback invoked when the API call is successful.
fail function - No Callback invoked when the API call fails.
complete function - No Callback to be invoked when the API call is complete, regardless of success or failure.

Return value of fail

Result Code Error Message
102 Param error
401 Parameter error.
1001860001 System internal error.
1001860002 The application is not authorized.
1001860004 Too frequent API calls.
1001860005 Network connection error.
1001860050 The HUAWEI ID is not signed in.
1001860052 The purchase cannot be finished because the user has not paid for it.
1001860053 The purchase has been finished and cannot be finished again.
1001860054 The country or region of the signed-in HUAWEI ID does not support IAP.

Example:

has.finishIap({
  productType: 0,
  // Replace it with the actual purchaseToken.
  purchaseToken: '***',
  // Replace it with the actual purchaseOrderId.
  purchaseOrderId: '***',
  success: () => {
    console.info('finishIap success');
  },
  fail: (err) => {
    console.error('finishIap fail', err);
  },
  complete: (res) => {
    console.info('finishIap complete', res);
  }
});

[h2]has.queryIap

has.queryIap(Object object)

Queries information about the purchased products, including consumables and non-consumables. Only one type of products can be queried per API call.

Required permissions: Before development, you need to configure the client ID, configure the signing certificate fingerprint, enable merchant service, and enable and activate IAP Kit.

Since: 1.0.12

Parameters:

The input parameter is an object containing the following fields.

Parameter Type Default Value Mandatory Description
productType number - Yes

Type of products to be queried.

- 0: consumables

- 1: non-consumables

- 2: auto-renewable subscription

- 3: non-renewable subscription

continuationToken string - No

Pagination cursor used to locate data for paginated queries.

This parameter is optional for the first query. If a user owns a large number of products and a continuationToken is returned in the response, the app must call this API again and pass the received continuationToken. If not all products have been retrieved, additional calls must continue to be made until no continuationToken is returned, indicating that all products have been fetched.

queryType number 1 No

Query type. The default value is 1.

- 0: all purchase records of consumables, non-consumables, or auto-renewable subscriptions

- 1: all purchased consumables, non-consumables, or auto-renewable subscriptions that have not been delivered

- 2: purchased non-consumables or active auto-renewable subscriptions

In the sandbox environment:

If productType is 1, only information about the purchased non-consumables that have not been delivered will be returned.

If productType is 2, only information about the active auto-renewable subscriptions is returned.

success function - No Callback invoked when the API call is successful.
fail function - No Callback invoked when the API call fails.
complete function - No Callback to be invoked when the API call is complete, regardless of success or failure.

Return values of success

Parameter Type Description
purchaseDataList string[] Array of PurchaseData strings.
continuationToken string

Pagination cursor used to locate data for paginated queries.

If a user owns a large number of products and a continuationToken is returned in the response, the app must call this API again and pass the received continuationToken. If not all products have been retrieved, additional calls must continue to be made until no continuationToken is returned, indicating that all products have been fetched.

Return values of fail

Result Code Error Message
102 Param error
401 Parameter error.
1001860001 System internal error.
1001860002 The application is not authorized.
1001860004 Too frequent API calls.
1001860005 Network connection error.
1001860050 The HUAWEI ID is not signed in.
1001860054 The country or region of the signed-in HUAWEI ID does not support IAP.

Example:

has.queryIap({
  productType: 0,
  queryType: 1,
  success: (res) => {
    console.info('queryIap success', res);
  },
  fail: (err) => {
    console.error('queryIap fail', err);
  },
  complete: (res) => {
    console.info('queryIap complete', res);
  }
});

[h2]has.queryIapProducts

has.queryIapProducts(Object object)

Obtains the product details configured in AppGallery Connect.

Required permissions: Before development, you need to configure the client ID, configure the signing certificate fingerprint, enable merchant service, and enable and activate IAP Kit.

Since: 1.0.12

Parameters:

The input parameter is an object containing the following fields.

Parameter Type Default Value Mandatory Description
productType number - Yes

Type of products to be queried.

- 0: consumables

- 1: non-consumables

- 2: auto-renewable subscription

- 3: non-renewable subscription

productIds string[] - Yes

ID list of products to be queried.

Each product ID must exist and be unique in your app.

The product IDs come from the product information you have configured in AppGallery Connect. For details, see Configuring Products.

NOTE

A maximum of 200 product IDs can be queried at a time. For a large number of products, it is advised to query their IDs in batches.

success function - No Callback invoked when the API call is successful.
fail function - No Callback invoked when the API call fails.
complete function - No Callback to be invoked when the API call is complete, regardless of success or failure.

Return values of success

Product array.

Return values of fail

Result Code Error Message
102 Param error
401 Parameter error.
1001860001 System internal error.
1001860002 The application is not authorized.
1001860003 Invalid product information.
1001860004 Too frequent API calls.
1001860005 Network connection error.
1001860007 The app to which the product belongs is not released in a specified location.
1001860050 The HUAWEI ID is not signed in.
1001860054 The country or region of the signed-in HUAWEI ID does not support IAP.

Example:

has.queryIapProducts({
  productType: 0,
  productIds: ['xxx-1', 'xxx-2'],
  success: (res) => {
    console.info('queryIapProducts success', res);
  },
  fail: (err) => {
    console.error('queryIapProducts fail', err);
  },
  complete: (res) => {
    console.info('queryIapProducts complete', res);
  }
});

[h2]has.isIapSandboxActivated

has.isIapSandboxActivated(Object object)

Checks whether the sandbox environment is available.

Required permissions: Before development, you need to configure the client ID, configure the signing certificate fingerprint, enable merchant service, and enable and activate IAP Kit.

Since: 1.0.12

Parameters:

The input parameter is an object containing the following fields.

Parameter Type Default Value Mandatory Description
success function - No Callback invoked when the API call is successful.
fail function - No Callback invoked when the API call fails.
complete function - No Callback to be invoked when the API call is complete, regardless of success or failure.

Return values of success

A boolean value, indicating whether the sandbox testing capability is active.

Return values of fail

Result Code Error Message
401 Parameter error.
1001860001 System internal error.
1001860002 The application is not authorized.
1001860004 Too frequent API calls.
1001860005 Network connection error.
1001860050 The HUAWEI ID is not signed in.
1001860054 The country or region of the signed-in HUAWEI ID does not support IAP.
1001860057 The app provision type is not debug.
1001860058 The HUAWEI ID is not test account.

Example:

has.isIapSandboxActivated({
  success: (res) => {
    console.info('isIapSandboxActivated success', res);
  },
  fail: (err) => {
    console.error('isIapSandboxActivated fail', err);
  },
  complete: (res) => {
    console.info('isIapSandboxActivated complete', res);
  }
});

[h2]has.showIapManagedSubscriptions

has.showIapManagedSubscriptions(Object object)

Redirects to the subscription status screen or the subscription details screen.

Required permissions: Before development, you need to configure the client ID, configure the signing certificate fingerprint, enable merchant service, and enable and activate IAP Kit.

Since: 1.0.12

Parameters:

The input parameter is an object containing the following fields.

Parameter Type Default Value Mandatory Description
uiParameter UIWindowParameter - Yes UIWindowParameter object, which contains the window display mode.
groupId string - No

Subscription group ID, which you have defined in AppGallery Connect. For details,see Configuring Products.

NOTE

If groupId is passed, the subscription details screen will be displayed.

If groupId is not passed, the subscription status screen will be displayed. If a user has only one subscription data record in an app, the screen for showing the details of this subscription will be displayed.

success function - No Callback invoked when the API call is successful.
fail function - No Callback invoked when the API call fails.
complete function - No Callback to be invoked when the API call is complete, regardless of success or failure.

Return values of fail

Result Code Error Message
102 Param error
401 Parameter error.
1001860001 System internal error.
1001860002 The application is not authorized.
1001860004 Too frequent API calls.
1001860005 Network connection error.
1001860050 The HUAWEI ID is not signed in.
1001860054 The country or region of the signed-in HUAWEI ID does not support IAP.

Example:

has.showIapManagedSubscriptions({
  uiParameter: {
    windowScreenMode: 1
  },
  groupId: 'xxx',
  success: () => {
    console.info('showIapManagedSubscriptions success');
  },
  fail: (err) => {
    console.error('showIapManagedSubscriptions fail', err);
  },
  complete: (res) => {
    console.info('showIapManagedSubscriptions complete', res);
  }
});

[h2]has.getPhoneNumber

has.getPhoneNumber(Object object):void

Launches the function page for obtaining a user's phone number. Before using this API, see Getting Started.

Since: 1.0.12

Parameters:

The input parameter is an object containing the following fields.

Parameter Type Default Value Mandatory Description
success function - No Callback invoked when the API call is successful.
fail function - No Callback invoked when the API call fails.
complete function - No Callback to be invoked when the API call is complete, regardless of success or failure.

Return value of success

Property Type Description
code string Mobile number of the user.

Example:

has.getPhoneNumber({
  success: (res) => {
    console.info('getPhoneNumber success', res);
  },
  fail: (err) => {
    console.error('getPhoneNumber fail', err);
  },
  complete: (res) => {
    console.info('getPhoneNumber complete', res);
  }
});

Below shows the UI effect.

[h2]has.getAvatarInfo

has.getAvatarInfo(Object object): void

Launches the function page for obtaining a user's profile photo. Before using this API, see Configuring the Client ID.

Since: 1.0.12

Parameters:

The input parameter is an object containing the following fields.

Parameter Type Default Value Mandatory Description
success function - No Callback invoked when the API call is successful.
fail function - No Callback invoked when the API call fails.
complete function - No Callback to be invoked when the API call is complete, regardless of success or failure.

Return value of success

Property Type Description
avatarUri string Local path of the profile photo.

Example:

has.getAvatarInfo({
  success: (res) => {
    console.info('getAvatarInfo success', res);
  },
  fail: (err) => {
    console.error('getAvatarInfo fail', err);
  },
  complete: (res) => {
    console.info('getAvatarInfo complete', res);
  }
});

Below shows the UI effect.

[h2]has.getInvoiceTitle

has.getInvoiceTitle(Object object): void

Launches the function page for obtaining a user's invoice title. Before using this API, see Configuring the Client ID.

Since: 1.0.12

Parameters:

The input parameter is an object containing the following fields.

Parameter Type Default Value Mandatory Description
success function - No Callback invoked when the API call is successful.
fail function - No Callback invoked when the API call fails.
complete function - No Callback to be invoked when the API call is complete, regardless of success or failure.

Return values of success

Property Type Description
type string Invoice title type.
title string Invoice title.
taxNumber string Taxpayer identification number.
companyAddress string Company address.
telephone string Phone number of a company.
bankName string Bank name of a company.
bankAccount string Bank account of a company.

Example:

has.getInvoiceTitle({
  success: () => {
    console.info('getInvoiceTitle success');
  },
  fail: (err) => {
    console.error('getInvoiceTitle fail', err);
  },
  complete: (res) => {
    console.info('getInvoiceTitle complete', res);
  }
});

Below shows the UI effect.

[h2]has.getDeliveryAddress

has.getDeliveryAddress(Object object): void

Launches the function page for obtaining a user's shipping address. Before using this API, see Configuring the Client ID.

Since: 1.0.12

Parameters:

The input parameter is an object containing the following fields.

Parameter Type Default Value Mandatory Description
success function - No Callback invoked when the API call is successful.
fail function - No Callback invoked when the API call fails.
complete function - No Callback to be invoked when the API call is complete, regardless of success or failure.

Return values of success

Property Type Description
userName string Recipient name
telNumber string Phone number of the recipient.
postalCode string Postal code.
nationalCode string Country code obtained.
provinceName string Province name.
cityName string City name.
countyName string District name.
streetName string Street name.
detailInfo string Detailed address.

Example:

has.getDeliveryAddress({
  success: (res) => {
    console.info('getDeliveryAddress success', res);
  },
  fail: (err) => {
    console.error('getDeliveryAddress fail', err);
  },
  complete: (res) => {
    console.info('getDeliveryAddress complete', res);
  }
});

Below shows the UI effect.

[h2]has.getServiceSubscription

has.getServiceSubscription(Object object): void

Launches the subscription service page. Before using this API, enable Push Kit by referring to Enabling Push Kit.

Since: 1.0.12

Parameters:

The input parameter is an object containing the following fields.

Parameter Type Default Value Mandatory Description
tmplIds Array<string> - Yes IDs of the message templates to be subscribed to. A maximum of three messages can be subscribed to at a time.
success function - No Callback invoked when the API call is successful.
fail function - No Callback invoked when the API call fails.
complete function - No Callback to be invoked when the API call is complete, regardless of success or failure.

Return value of success

Property Type Description
errMsg string Call result. 'requestSubscribeMessage:ok' is returned if the API call is successful.

Example:

has.getServiceSubscription({
  tmplIds: [''],
  success: (res) => {
    console.info('getServiceSubscription success', res);
  },
  fail: (err) => {
    console.error('getServiceSubscription fail', err);
  },
  complete: (res) => {
    console.info('getServiceSubscription complete', res);
  }
});

Below shows the UI effect.

UploadFile

Represents the uploaded file information.

Since: 1.0.12

Name Type Mandatory Description
filename string Yes File name in the header when multipart is used.
name string Yes Name of a form item when multipart is used. The default value is file.
uri string Yes File path. The value can be a user directory or an application directory.
type string Yes Type of the file content. By default, the type is obtained based on the extension of the file name or URI.

UploadRequestData

Represents the uploaded form data.

Since: 1.0.12

Name Type Mandatory Description
name string Yes Name of a form element.
value string Yes Value of a form element.

UploadFileTaskState

Represents the information about an upload task.

Since: 1.0.12

Name Type Mandatory Description
path string Yes Path of the file to upload.
responseCode number Yes Result code of the upload task. For details about the result codes, see TaskState.
message string Yes Description of the upload task result.

PurchaseData

Represents the order information and subscription status information in JWS format.

Since: 1.0.12

Name Type Mandatory Description
type number Yes

Product type.

- 0: consumables

- 1: non-consumables

- 2: auto-renewable subscription

- 3: non-renewable subscription

jwsPurchaseOrder string No Order information in JWS format. Follow the instructions in Verifying the Signature in the Returned Result to decode and perform signature verification for the returned result to obtain purchase data in JSON format. Check the parameters in the JSON string in PurchaseOrderPayload.
jwsSubscriptionStatus string No Subscription status information in JWS format. You can decode the signature verification by referring to Verifying the Signature in the Returned Result to obtain the JSON string containing the subscription status information.

PurchaseOrderPayload

Represents the purchase order model, which supports consumables, non-consumables, and auto-renewable subscriptions.

Since: 1.0.12

Name Type Mandatory Description
environment string Yes

Environment type.

- NORMAL: normal environment

- SANDBOX: sandbox environment

purchaseOrderId string Yes Order ID of a purchase.
purchaseToken string Yes Purchase token. In a consumable/non-consumable purchase, each purchase token matches a specific order. In a subscription purchase, each purchase token matches a subscription ID.
applicationId string Yes App ID.
productId string Yes Product ID.
productType string Yes

Product type. The options are as follows:

- 0: consumables

- 1: non-consumables

- 2: auto-renewable subscription

- 3: non-renewable subscription

purchaseTime number Yes

Purchase time, which is a UTC timestamp in milliseconds.

If the purchase is not complete, this parameter is left empty.

finishStatus string No

Delivery status. The options are as follows:

- 1: delivered

- 2: not delivered

needFinish boolean No

Indicates whether the delivery should be acknowledged to complete the purchase process. The options are as follows:

- true: Delivery acknowledgement is required.

- false: Delivery acknowledgement is optional.

price number Yes Price in currency sub-units. The specific sub-unit, like cents, varies by currency.
currency string Yes Currency. For details, see the ISO 4217 standard. For example, CNY, USD, and MYR.
developerPayload string No Information stored on the merchant side, which an app passes when calling the payment API.
purchaseOrderRevocationReasonCode string No

Reason for revoking the purchase order.

- 0: others

- 1: order revoked at the user's request

revocationTime number No Time when a purchase order is canceled, which is a UTC timestamp in milliseconds.
offerTypeCode string No

Promotional offer type.

- 1: introductory offers for new users

- 2: promotional offers for specific user groups

offerId string No Promotional offer ID.
countryCode string Yes Country/Region code, which is used to identify the country or region. For details, see the ISO 3166 standard.
signedTime number Yes Time when signing is performed, which is a UTC timestamp in milliseconds.

SubGroupStatusPayload

Represents the subscription status information related to a subscription group.

Since: 1.0.12

Name Type Mandatory Description
environment string Yes

Environment type.

- NORMAL: normal environment

- SANDBOX: sandbox environment

applicationId string Yes App ID.
packageName string Yes App package name.
subGroupId string Yes Subscription group ID.
lastSubscriptionStatus object No Final subscription status (SubscriptionStatus) within a subscription group. For example, if a user switches from subscription A to B and then to C, this parameter indicates the status of subscription C.
historySubscriptionStatusList object[] No List of all historical subscription statuses (SubscriptionStatus) within a subscription group. For example, if a user switches from subscription A to B and then to C, this parameter indicates the statuses of subscriptions C, B, and A.

SubscriptionStatus

Represents subscription status information.

Since: 1.0.12

Name Type Mandatory Description
subGroupGenerationId string Yes

Subscription group generation ID.

- This ID remains unchanged when a user switches between different subscription products in the same group.

- This ID will change when a user purchases the product again after the subscription expires and the retention period ends.

subscriptionId string Yes

Subscription ID. The ID will change when:

- A user switches from a subscription to another.

- A user purchases the product again after the subscription expires and the retention period ends.

purchaseToken string Yes Purchase token. In a consumable/non-consumable purchase, each purchase token matches a specific order. In a subscription purchase, each purchase token matches a subscription ID.
status string Yes

Subscription status.

- 1: active

- 2: expired

- 3: billing retry

- 5: revoked

expiresTime number Yes Time when the subscription expires. The value is a UTC timestamp, in milliseconds.
lastPurchaseOrder object No Latest purchase order for a subscription. For details about the parameters contained in the purchase order, see PurchaseOrderPayload.
recentPurchaseOrderList object[] No List of the recently purchased subscriptions, including the purchase orders generated upon renewal and balance conversion. For details about the parameters contained in the purchase order, see PurchaseOrderPayload.
renewalInfo object No Latest future billing plan of the current subscription. For details about the parameters contained in the billing plan, see SubRenewalInfo.

SubRenewalInfo

Represents the renewal information about a subscription.

Since: 1.0.12

Name Type Mandatory Description
environment string Yes

Environment type.

- NORMAL: normal environment

- SANDBOX: sandbox environment

subGroupGenerationId string Yes

Subscription group generation ID.

- This ID remains unchanged when a user switches between different subscription products in the same group.

- This ID will change when a user purchases the product again after the subscription expires and the retention period ends.

nextRenewPeriodProductId string No ID of the product to be renewed in the next billing cycle.
productId string Yes ID of the product that is currently active.
autoRenewStatusCode string Yes

Auto-renewal status.

- 0: disabled

- 1: enabled

hasInBillingRetryPeriod boolean Yes

Whether the system is still attempting to retry the billing.

- true: yes

- false: no

priceIncreaseStatusCode string No

Price increase status code.

- 1: The user has not agreed to a price increase.

- 2: The user has agreed to a price increase.

offerTypeCode string No

Promotional offer type.

- 1: introductory offers for new users

- 2: promotional offers for specific user groups

offerId string No Promotional offer ID.
renewalPrice number No Price for the next renewal, in currency sub-units. The specific sub-unit, like cents, varies by currency. This field is not returned if the subscription is revoked.
currency string No Currency. For details, see the ISO 4217 standard. For example, CNY, USD, and MYR.
renewalTime number No Time when the subscription is renewed. The value is a UTC timestamp, in milliseconds.
expirationIntent string No

Reason for subscription renewal failure.

- 1: The user canceled the subscription.

- 2: The product is invalid.

- 3: The subscription agreement is invalid.

- 4: An exception occurred during billing.

- 5: The user did not agree to the price increase.

- 6: The failure reason is unknown.

UIWindowParameter

Window parameters.

Since: 1.0.12

Name Type Mandatory Description
windowScreenMode number Yes

UI window mode.

- 1: pop-up

- 2: full-screen

Product

Details of a product.

Since: 1.0.12

Name Type Mandatory Description
id string Yes Product ID.
type number Yes

Product type.

- 0: consumables

- 1: non-consumables

- 2: auto-renewable subscription

- 3: non-renewable subscription

name string Yes

Product name, which you set when adding a product.

The name is displayed on the checkout screen of IAP Kit.

description string Yes Product description, which you set when adding a product.
price string Yes

Displayed price of a product, in the format Currency+Price, for example, EUR 0.15.

In some countries or regions, the value format is Currency symbol+Price, for example, ¥0.15 in the Chinese mainland.

The price includes the tax.

- For consumable or non-consumable products, this parameter represents the promotional price if one is set; otherwise, it defaults to the original price.

- For an auto-renewable subscription, this parameter indicates its original price.

NOTE

This parameter has been deprecated. You are advised to use localPrice instead.

localPrice string No

Displayed price of a product, in the format Currency+Price, for example, EUR 0.15.

In some countries or regions, the value format is Currency symbol+Price, for example, ¥0.15 in the Chinese mainland.

The price includes the tax.

- For consumable or non-consumable products, this parameter represents the promotional price if one is set; otherwise, it defaults to the original price.

- For an auto-renewable subscription, this parameter indicates its original price.

microPrice number Yes

Product price in micro unit, which equals the actual product price multiplied by 1,000,000.

For example, if the actual price of a product is US$1.99, the product price in micro unit is 1,990,000 (1.99*1000000).

- For consumable, non-consumable, or non-renewable subscriptions, this parameter indicates the promotional price in micro unit if set; otherwise, it defaults to the original price in micro unit.

- For an auto-renewable subscription, this parameter indicates its original price in micro unit.

originalLocalPrice string Yes

Original price of a product, in the format Currency+Price, for example, EUR 0.15.

In some countries or regions, the value format is Currency symbol+Price, for example, ¥0.15 in the Chinese mainland.

The price includes the tax.

- For a consumable, non-consumable, or non-renewable subscription, this parameter indicates the original price regardless of whether a promotional price is set.

- For an auto-renewable subscription, this parameter will not be returned.

originalMicroPrice number Yes

Original price in micro unit of a product.

It equals the original product price multiplied by 1,000,000.

For example, if the original price of a product is US$1.99, the product price in micro unit is 1,990,000 (1.99*1000000).

- For a consumable, non-consumable, or non-renewable subscription, this parameter indicates the original price in micro-units regardless of whether a promotional price is set.

- For an auto-renewable subscription, this parameter will not be returned.

currency string Yes Currency used to pay for a product, for example, CNY.
status number No

Product status.

- 0: valid

- 1: canceled, that is, deleted Products in this status cannot be purchased by new users or renewed by existing subscribers.

- 3: offline. Offline subscriptions cannot be purchased by new users, but existing subscribers can still renew their plans.

subscriptionInfo SubscriptionInfo No Information about an auto-renewable subscription.
promotionalOffers PromotionalOffer[] No List of promotional offers supported by a subscription.
jsonRepresentation string No Original JSON character string of product details.

SubscriptionInfo

Subscription information.

Since: 1.0.12

Name Type Mandatory Description
periodUnit number Yes

Unit of the subscription billing cycle.

- 0: day

- 1: week

- 2: month

- 3: year

- 4: minute (reserved; not supported currently)

periodCount number Yes Number of billing cycles for a subscription.
groupId string Yes Subscription group ID.
groupLevel number Yes Product level.
hasEligibilityForIntroOffer boolean No

Whether a user has already enjoyed the promotion of a subscription in the same group. Options:

- true: yes

- false: no

- Other values: No relevant information is obtained.

introductoryOffer SubscriptionOffer No Promotion information.

SubscriptionOffer

Promotion information.

Since: 1.0.12

Name Type Mandatory Description
paymentMode number Yes

Payment method for a promotion.

- 1: free trial

- 2: pay-per-use

- 3: upfront payment

periodUnit number Yes

Unit of the subscription billing cycle.

- 0: day

- 1: week

- 2: month

- 3: year

- 4: minute (reserved; not supported currently)

periodCount number Yes Period count of a promotion.
localPrice string Yes

Promotional price of a product, in the format Currency+Price, for example, EUR 0.15.

In some countries or regions, the value format is Currency symbol+Price, for example, ¥0.15 in the Chinese mainland.

microPrice number Yes

Promotional price in micro unit.

Promotional price in micro unit, which equals the product price multiplied by 1,000,000.

offerType number Yes

Promotion type.

- 0: offer for new users

- 1: promotional offers for specific user groups

PromotionalOffer

Promotional offer information that you can define for a subscription.

Since: 1.0.12

Name Type Mandatory Description
offerId string Yes Promotional offer ID.
paymentMode number Yes

Payment method for a promotion.

- 1: free trial

- 2: pay-per-use

- 3: upfront payment

periodUnit number No

Unit of the subscription billing cycle.

- 0: day

- 1: week

- 2: month

- 3: year

- 4: minute (reserved; not supported currently)

periodCount number No Number of billing cycles for a subscription.
localPrice string Yes

Discounted price of a product, in the format Currency+Price, for example, EUR 0.15.

In some countries or regions, the value format is Currency symbol+Price, for example, ¥0.15 in the Chinese mainland.

microPrice number Yes Discounted price in micro unit, which equals the actual product price multiplied by 1,000,000. For example, if the actual price of a product is US$1.99, the product price in micro unit is 1,990,000 (1.99*1000000).

Example

[h2]Example 1

This example demonstrates how to load a local web page.

// xxx.ets
import { AtomicServiceEnhancedWeb, AtomicServiceEnhancedWebController } from '@atomicservice/ascfapi';
@Entry
@Component
struct WebComponent {
  @State controller: AtomicServiceEnhancedWebController = new AtomicServiceEnhancedWebController();
  build() {
    Column() {
      AtomicServiceEnhancedWeb({ src: $rawfile("index.html"), controller: this.controller })
    }
  }
}

[h2]Example 2

This example loads an online web page:

// xxx.ets
import { AtomicServiceEnhancedWeb, AtomicServiceEnhancedWebController } from '@atomicservice/ascfapi';
@Entry
@Component
struct WebComponent {
  @State controller: AtomicServiceEnhancedWebController = new AtomicServiceEnhancedWebController();
  build() {
    Column() {
      AtomicServiceEnhancedWeb({ src: 'https://www.example.com', controller: this.controller })
    }
  }
}

[h2]Example 3

This example demonstrates how to load a web page within a NavDestination container.

// xxx.ets
import { AtomicServiceEnhancedWeb, AtomicServiceEnhancedWebController } from '@atomicservice/ascfapi';
@Builder
export function WebComponentBuilder(name: string, param: Object) {
  WebComponent()
}
@Component
struct WebComponent {
  navPathStack: NavPathStack = new NavPathStack();
  @State controller: AtomicServiceEnhancedWebController = new AtomicServiceEnhancedWebController();
  build() {
    NavDestination() {
      AtomicServiceEnhancedWeb({
        src: $rawfile("index.html"),
        controller: this.controller,
        navPathStack: this.navPathStack
      })
    }
    .onReady((context: NavDestinationContext) => {
      this.navPathStack = context.pathStack;
    })
  }
}

[h2]Example 4

This example sets the onMessage() event callback.

// xxx.ets
import { AtomicServiceEnhancedWeb, AtomicServiceEnhancedWebController, OnMessageEvent } from '@atomicservice/ascfapi';
@Entry
@Component
struct WebComponent {
  @State controller: AtomicServiceEnhancedWebController = new AtomicServiceEnhancedWebController();
  build() {
    Column() {
      AtomicServiceEnhancedWeb({
        src: $rawfile("index.html"),
        controller: this.controller,
        // Called when the user clicks Send Message and then Back on an HTML5 page.
        onMessage: (event: OnMessageEvent) => {
          console.info(`onMessage data = ${JSON.stringify(event.data)}`);
        }
      })
    }
  }
}
<!-- index.html -->
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<!-- Import the JS SDK file. -->
<script src="../js/aseweb-sdk.umd.js" type="text/javascript"></script>
<body>
<h1>JS SDK - postMessage()</h1>
<br/>
<button type="button" onclick="postMessage({ name: 'Jerry', age: 18 });">Send Message</button>
<br/>
<button type="button" onclick="back();">Back</button>
</body>
<script type="text/javascript">
    function postMessage(data) {
        // API provided by the JS SDK for sending messages.
        has.asWeb.postMessage({
            data: data,
            callback: (err, res) => {
                if (err) {
                    console.error(`postMessage error err. Code: ${err.code}, message: ${err.message}`);
                } else {
                    console.info(`postMessage success res = ${JSON.stringify(res)}`);
                }
            }
        });
    }
    function back() {
        // Router API provided by the JS SDK for navigation back.
        has.router.back({
            delta: 1
        });
    }
</script>
</html>

[h2]Example 5

This example sets the web page loading event callbacks.

// xxx.ets
import {
  AtomicServiceEnhancedWeb,
  AtomicServiceEnhancedWebController,
  OnErrorReceiveEvent,
  OnHttpErrorReceiveEvent,
  OnPageBeginEvent,
  OnPageEndEvent
} from '@atomicservice/ascfapi';
@Entry
@Component
struct WebComponent {
  @State controller: AtomicServiceEnhancedWebController = new AtomicServiceEnhancedWebController();
  build() {
    Column() {
      AtomicServiceEnhancedWeb({
        src: $rawfile('index.html'),
        controller: this.controller,
        // Invoked when an error occurs during web page loading.
        onErrorReceive: (event: OnErrorReceiveEvent) => {
          console.info(`onErrorReceive event=${JSON.stringify({
            requestUrl: event.request?.getRequestUrl(),
            requestMethod: event.request?.getRequestMethod(),
            errorCode: event.error?.getErrorCode(),
            errorInfo: event.error?.getErrorInfo()
          })}`);
        },
        // Invoked when an HTTP error occurs during web page resource loading.
        onHttpErrorReceive: (event: OnHttpErrorReceiveEvent) => {
          console.info(`onHttpErrorReceive event=${JSON.stringify({
            requestUrl: event.request?.getRequestUrl(),
            requestMethod: event.request?.getRequestMethod(),
            responseCode: event.response?.getResponseCode(),
            responseData: event.response?.getResponseData(),
          })}`);
        },
        // Invoked when the web page starts to be loaded.
        onPageBegin: (event: OnPageBeginEvent) => {
          console.info(`onPageBegin event=${JSON.stringify({
            url: event.url
          })}`);
        },
        // Invoked when loading of the web page is complete.
        onPageEnd: (event: OnPageEndEvent) => {
          console.info(`onPageEnd event=${JSON.stringify({
            url: event.url
          })}`);
        }
      })
    }
  }
}

[h2]Example 6

This example demonstrates how to use AtomicServiceEnhancedWeb and AtomicServiceEnhancedWebController.

// xxx.ets
import {
  AtomicServiceEnhancedWeb,
  AtomicServiceEnhancedWebController,
  OnErrorReceiveEvent,
  OnHttpErrorReceiveEvent,
  OnPageBeginEvent,
  OnPageEndEvent,
  OnMessageEvent,
  OnLoadInterceptEvent,
  OnProgressChangeEvent
} from '@atomicservice/ascfapi';
@Entry
@Component
struct WebComponent {
  @State darkMode: WebDarkMode = WebDarkMode.On;
  @State forceDarkAccess: boolean = true;
  @State mixedMode: MixedMode = MixedMode.None;
  @State controller: AtomicServiceEnhancedWebController = new AtomicServiceEnhancedWebController();
  @State num: number = 1;
  build() {
    Column() {
      Button('accessForward').onClick(() => {
        console.info(`accessForward = ${this.controller.accessForward()}`);
      })
      Button('accessBackward').onClick(() => {
        console.info(`accessBackward = ${this.controller.accessBackward()}`);
      })
      Button('accessStep').onClick(() => {
        console.info(`accessStep = ${this.controller.accessStep(1)}`);
      })
      Button('forward').onClick(() => {
        this.controller.forward();
        console.info('forward success');
      })
      Button('backward').onClick(() => {
        this.controller.backward();
        console.info('backward success');
      })
      Button('refresh').onClick(() => {
        this.controller.refresh();
        console.info('refresh success');
      })
      Button('loadUrl').onClick(() => {
        this.controller.loadUrl('https://www.baidu.com/');
        console.info('loadUrl success');
      })
      Button('Dark Mode').onClick(() => {
        this.forceDarkAccess = !this.forceDarkAccess;
      })
      Button('mixedMode').onClick(() => {
        this.mixedMode = this.mixedMode == MixedMode.None ? MixedMode.All : MixedMode.None;
      })
      Button('Click').onClick(() => {
        console.info(`getUserAgent = ${this.controller.getUserAgent()}`);
        console.info(`getCustomUserAgent = ${this.controller.getCustomUserAgent()}`);
        this.controller.setCustomUserAgent('test' + this.num++);
        console.info(`getUserAgent after set = ${this.controller.getUserAgent()}`);
        console.info(`getCustomUserAgent after set = ${this.controller.getCustomUserAgent()}`);
      })
      AtomicServiceEnhancedWeb({
        src: 'https://www.example.com',
        mixedMode: this.mixedMode,
        darkMode: this.darkMode,
        forceDarkAccess: this.forceDarkAccess,
        controller: this.controller,
        onControllerAttached: () => {
          console.info("onControllerAttached call back success");
        },
        onLoadIntercept: (event: OnLoadInterceptEvent) => {
          console.info("onLoadIntercept call back success " + JSON.stringify({
            getRequestUrl: event.data.getRequestUrl(),
            getRequestMethod: event.data.getRequestMethod(),
            getRequestHeader: event.data.getRequestHeader(),
            isRequestGesture: event.data.isRequestGesture(),
            isMainFrame: event.data.isMainFrame(),
            isRedirect: event.data.isRedirect(),
          }))
          return false;
        },
        onProgressChange: (event: OnProgressChangeEvent) => {
          console.info("onProgressChange call back success " + JSON.stringify(event));
        },
        onMessage: (event: OnMessageEvent) => {
          console.info("onMessage call back success " + JSON.stringify(event));
        },
        onPageBegin: (event: OnPageBeginEvent) => {
          console.info("onPageBegin call back success " + JSON.stringify(event));
        },
        onPageEnd: (event: OnPageEndEvent) => {
          console.info("onPageEnd call back success " + JSON.stringify(event));
        },
        onHttpErrorReceive: (event: OnHttpErrorReceiveEvent) => {
          console.info("onHttpErrorReceive call back success " + JSON.stringify(event));
        },
        onErrorReceive: (event: OnErrorReceiveEvent) => {
          console.info("onErrorReceive call back success " + JSON.stringify(event));
        }
      })
    }
  }
}

[h2]Example 7

This example shows how to set nested scrolling.

import { AtomicServiceEnhancedWeb, AtomicServiceEnhancedWebController } from '@atomicservice/ascfapi';
@Entry
@Component
struct AtomicServiceNestedScroll {
  @State controller: AtomicServiceEnhancedWebController = new AtomicServiceEnhancedWebController();
  @State mode: string = 'PARALLEL mode (click to switch)';
  @State nestedScroll: NestedScrollOptions | NestedScrollOptionsExt = {
    scrollForward: NestedScrollMode.PARALLEL,
    scrollBackward: NestedScrollMode.PARALLEL
  };
  build() {
    Scroll() {
      Column() {
        Text("Nested AsWeb - Header")
          .height("15%")
          .width("100%")
          .fontSize(30)
          .backgroundColor(Color.Yellow)
        Button(this.mode)
          .margin({ top: 10, bottom: 10 })
          .onClick(() => {
            if (!(this.nestedScroll as NestedScrollOptions).scrollForward) {
              this.mode = 'SELF_FIRST mode (click to switch)';
              this.nestedScroll = {
                scrollForward: NestedScrollMode.SELF_FIRST,
                scrollBackward: NestedScrollMode.SELF_FIRST
              }
            } else {
              this.mode = 'PARENT_FIRST mode (click to switch)';
              this.nestedScroll = {
                scrollUp: NestedScrollMode.PARENT_FIRST,
                scrollDown: NestedScrollMode.PARENT_FIRST
              }
            }
          })
        AtomicServiceEnhancedWeb({
          src: 'https://www.example.com',
          controller: this.controller,
          nestedScroll: this.nestedScroll
        })
        Text("Nested AsWeb - Footer")
          .height("15%")
          .width("100%")
          .fontSize(30)
          .backgroundColor(Color.Yellow)
      }
    }
  }
}