API
#
Basics#
mpService.canIUse(schema)Determines whether the APIs, callbacks, parameters, and components of the Mini Program are available in the current version.
#
Parametersstring
schema
The API is called using the ${API}.${method}.${param}.${options}
or ${component}.${attribute}.${option}
method.
${API}:
API name${method}:
Call method. Available values:return
,success
,object
, andcallback
.${param}:
Parameter or return value${options}:
Available values for the parameter${component}:
Component name${attribute}:
Component attribute${options}:
Available values for the component attribute
#
Return ValuesBoolean
Indicates whether the API is supported in the current version.
#
Sample code#
mpService.getSystemInfo#
Return ValuesObject res
Property | Type | Example | Description |
---|---|---|---|
brand | string | "Apple" "Xiaomi" | Device brand |
model | string | Device model | |
pixelRatio | number | Device's pixel ratio | |
screenWidth | number | Screen width in px | |
screenHeight | number | Screen height in px | |
windowWidth | number | Available window width in px | |
windowHeight | number | Available window height in px | |
statusBarHeight | number | Status bar height in px | |
language | string | Language set in App | |
version | string | App version | |
SDKVersion | string | Base library version for the App version | |
system | string | Operating system and version | |
platform | string | "ios" "android" | Client platform |
safeArea | Object | Safe area when the screen is in vertical orientation platform |
res.safeArea
Property | Type | Description |
---|---|---|
left | number | The x-coordinate of the top-left corner of the safe area |
right | number | The x-coordinate of the bottom-right corner of the safe area |
top | number | The y-coordinate of the top-left corner of the safe area |
bottom | number | The y-coordinate of the bottom-right corner of the safe area |
width | number | Safe area width in logical pixels |
height | number | Safe area height in logical pixels |
#
mpService.getUpdateManagerGet the singleton update manager for managing mini program updates.
#
Return ValuesThe update manager object.
#
mpService.getLaunchOptionsSyncObtains the parameters upon Mini Program startup. The callback parameters are consistent with those of onLaunch
.
#
Return ValuesObject res Startup parameters
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
path | string | - | - | The path for Mini Program startup |
scene | number | - | - | The scene value for Mini Program startup |
query | Object | - | - | The query parameter for Mini Program startup |
referrerInfo | Object | - | - | The source information. This is returned when a user enters the Mini Program from another Mini Program, Official Account, or app. Otherwise, {} is returned. (see the Note below for details.) |
referrerInfo is composed as follows
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
appId | string | - | - | The appId of the source Mini Program, Official Account, or app. |
extraData | Object | - | - |
#
mpService.getEnterOptionsSyncGets the parameters when the applet starts. If the current startup is cold, the return value is the same as the callback parameter for onLaunch
; If the current is a hot start, the return value is the same as onShow
.
#
Return ValuesObject res Startup parameters
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
path | string | - | - | The path for Mini Program startup |
scene | number | - | - | The scene value for Mini Program startup |
query | Object | - | - | The query parameter for Mini Program startup |
referrerInfo | Object | - | - | The source information. This is returned when a user enters the Mini Program from another Mini Program, Official Account, or app. Otherwise, {} is returned. (see the Note below for details.) |
referrerInfo is composed as follows
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
appId | string | - | - | The appId of the source Mini Program, Official Account, or app. |
extraData | Object | - | - |
#
mpService.onUnhandledRejectionListen for unhandled Promise
rejection events.
#
Parameters#
function callbackCallback function for unhandled Promise
rejection event.
#
function parametersObject res
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
reason | string | - | Reason for rejection, usually an Error object | |
promise | Promise.<any> | - | scene code |
#
NotesAll unhandledRejection
can be captured by this monitor, but only the Error
type will trigger an alarm in the background of the applet.
#
mpService.onThemeChangeMonitor system theme change events.
#
Parameters#
function callbackCallback function for system theme change event.
#
function parametersObject res
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
theme | string | - | The current theme of the system, the value is light or dark |
The legal value of the
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
dark | - | The current theme of the system, the value is light or dark | ||
light | - | The current theme of the system, the value is light or dark |
#
NotesThis event will only be triggered when the global configuration "darkmode": true
#
mpService.onErrorListens on the Mini Program error event. This event is triggered as a result of script error or failed API call. The callback timing and parameters of this event are consistent with those of App.onError
#
Parameters#
function callbackThe callback function for the Mini Program error event.
#
Parametersstring error Error message, including stacks.
#
mpService.onAppShowListens on the event that Mini Program is switched to foreground. The callback timing for this event is consistent with that of App.onShow.
Use
bn.onShow, bn.offShow
for MiniGame.
#
Parameters#
function callbackThe callback function for the event that Mini Program is switched to foreground.
#
ParametersObject res
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
path | string | - | - | The path for Mini Program startup |
scene | number | - | - | The scene value for Mini Program startup |
query | Object | - | - | The query parameter for Mini Program startup |
referrerInfo | Object | - | - | The source information. This is returned when a user enters the Mini Program from another Mini Program, Official Account, or app. Otherwise, {} is returned. (see the Note below for details.) |
referrerInfo is composed as follows
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
appId | string | - | - | The appId of the source Mini Program, Official Account, or app. |
extraData | Object | - | - |
#
NotesIn some versions, when there is no referrerInfo
, the value undefined is returned. You can use options.referrerInfo && options.referrerInfo.appId
to make a judgment.
#
mpService.onAppHideListens on the event that Mini Program is switched to background. The callback timing for this event is consistent with that of App.onHide
.
Use
bn.onHide, bn.offHide
for MiniGame.
#
Parameters#
function callbackThe callback function for the event that Mini Program is switched to background.
#
mpService.offUnhandledRejectionCancel listening for unhandled Promise rejection events.
#
Parameters#
function callbackCallback function for unhandled Promise rejection event.
#
mpService.offThemeChangeCancel listening for system theme change events.
#
Parameters#
function callbackThe callback function for the Mini Program theme change.
#
mpService.offErrorUn-listens on Mini Program error event.
#
Parameters#
function callbackThe callback function for the Mini Program error event.
#
mpService.offAppShowUn-listens on the event that Mini Program is switched to foreground.
#
Parameters#
function callbackThe callback function for the event that Mini Program is switched to foreground.
#
mpService.offAppHideUn-listens on the event that Mini Program is switched to background.
#
Parameters#
function callbackThe callback function for the event that Mini Program is switched to background.
#
UpdateManagerUpdateManager object, used to manage updates, the instance can be obtained through the mpService.getUpdateManager() interface.
#
Methods#
UpdateManager.applyUpdateForce the mini program to restart and use the new version.
Called after the new version of the mini program has been downloaded (that is, the onUpdateReady
callback is received).
#
UpdateManager.onCheckForUpdate(function callback)Listen to the Binance App background request to check the update result event. The Binance App automatically checks for updates when the mini program is cold-started, and does not need to be triggered by the developer.
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
callback | function | - | ✓ | The callback function. ({ hasUpdate: boolean }) => void |
#
UpdateManager.onUpdateReady(function callback)Monitor the version update event of the mini program. The client actively triggers the download (no need for the developer to trigger), and the callback will be called after the download is successful.
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
callback | function | - | ✓ | The callback function. () => void |
#
UpdateManager.onUpdateFailed(function callback)Monitor the update failure event of the mini program. There is a new version of the mini program, the client actively triggers the download (no need for the developer to trigger), and the download fails (maybe due to network reasons, etc.) and callback
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
callback | function | - | ✓ | The callback function. () => void |
#
Example#
bn.loadSubpackage(payload)For MiniGame.
Triggers subpackage loading.
#
ParametersObject payload
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
name | string | ✓ | The name of the subpackage, which can be name or root. | |
success | function | The callback event that the subpackage loading succeeds. | ||
fail | function | CThe callback event that the subpackage loading fails. | ||
complete | function | The callback event that the subpackage loading completed (always executed whether the loading succeeds or fails) |
#
Return ValuesLoadSubpackageTask
Loads subpackage task instances to obtain the subpackage loading status.
#
LoadSubpackageTask.onProgressUpdate(function callback)Listens on the subpackage loading progress change event.
#
ParametersProperty | Type | Default Value | Required | Description |
---|---|---|---|---|
callback | function | - | ✓ | The callback function. ({ progress }) => void |
#
Parameters object of callback functionProperty | Type | Description |
---|---|---|
progress | number | Subpackage download progress percentage |
totalBytesWritten | number | The length of downloaded data, in bytes |
totalBytesExpectedToWrite | number | The length of data expected to be downloaded, in bytes |
Example
#
Routing#
mpService.redirectToCloses the current page and redirects to a page (except for the tabbar page) in the app.
#
ParametersProperty | Type | Default Value | Required | Description |
---|---|---|---|---|
url | string | ✓ | Path to a non-tabBar page to be navigated to in the app. Parameters can be appended after the path. You can use ? to separate the path from parameters, = to connect a parameter key with a parameter value, and & to separate different parameters. For example, 'path?key=value&key2=value2'. |
#
mpService.reLaunchCloses all pages and opens a page in the app.
#
ParametersProperty | Type | Default Value | Required | Description |
---|---|---|---|---|
url | string | ✓ | Path to a non-tabBar page to be navigated to in the app. Parameters can be appended after the path. You can use ? to separate the path from parameters, = to connect a parameter key with a parameter value, and & to separate different parameters. For example, 'path?key=value&key2=value2'. |
#
mpService.navigateToKeeps the current page open and redirects to a page (except for the tabbar page) in the app. You can return to the original page using mpService.navigateBack
.
#
ParametersObject payload
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
url | string | ✓ | url to navigate | |
events | Object | register callbacks to listen EventChannel |
#
Return ValuesObject res
Property | Type | Description |
---|---|---|
eventChannel | EventChannel | communication channel between opener page and opened page |
#
mpService.switchTabRedirects to the tabBar page and closes all non-tabBar pages.
payload
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
url | string | ✓ | Path to the tabBar page (a page to be defined in the tabBar field of app.json) to be navigated to. Parameters cannot be appended after the path. |
#
Parameters#
mpService.navigateBackCloses the current page and returns to the previous page or multi-level page.
#
ParametersProperty | Type | Default Value | Required | Description |
---|---|---|---|---|
delta | number | 1 | The position in the history to which you want to move, relative to the current page. For example, pop(2) moves back two pages. If no value is passed then the default delta is 1 . |
#
mpService.navigateToMiniProgramOpens another Mini Program.
payload
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
appId | string | ✓ | The appId of the Mini Program to be opened. | |
path | string | The path of the page to be opened. If it is empty, the homepage is opened. Content following the question mark (?) in the path becomes a query. | ||
extraData | object | The data that needs to be passed to the target Mini Program. The target Mini Program can obtain this data from App.onLaunch and App.onShow. | ||
envVersion | 'preview', 'experience', 'published' | published | The channel of the Mini Program to be opened. It is valid when target="miniProgram". | |
type | 'app', 'web', 'webview' | app | The type of the Mini Program to be opened. It is valid when target="miniProgram". | |
rev | String | The rev of the Mini Program to be opened. It is valid when target="miniProgram". |
#
mpService.navigateBackMiniProgramReturns to the previous Mini Program. It can be called only when the current Mini Program is opened from another Mini Program.
payload
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
extraData | object | The data that needs to be returned to the previous Mini Program. The previous Mini Program can get this data from App.onShow. |
#
mpService.exitMiniProgramExit the miniprogram. There must be a click behavior to call successfully.
#
Framework#
mpService.getAppGets the globally unique App instance of the Mini Program.
#
Interface#
mpService.getCurrentPagesGets the current page stack. In the array, the first element is the homepage and the last element is the current page.
#
Interface#
Interface#
mpService.showToastDisplays the message prompt box.
#
ParametersProperty | Type | Default Value | Required | Description |
---|---|---|---|---|
title | string | - | ✓ | Prompt content |
icon | string | success | Icon. Available values: success ,loading , none , error | |
duration | number | 1500 | The delay time for a prompt |
#
mpService.hideToastHides the message prompt box.
#
mpService.showLoadingDisplays the loading prompt box. mpService.hideLoading
must be called to close the prompt box.
#
mpService.hideLoadingHides the loading prompt box.
#
mpService.showModalDisplays the modal dialog box.
#
ParametersProperty | Type | Default Value | Required | Description |
---|---|---|---|---|
title | string | - | ✓ | Prompt title |
content | string | - | ✓ | Prompt content |
confirmText | string | - | The text of the "OK "button, not more than 4 characters | |
showCancel | boolean | success | Indicates whether to display the "Cancel" button | |
cancelText | string | - | The text of the "Cancel" button, not more than 4 characters |
#
Return ValuesObject res
Property | Type | Description |
---|---|---|
status | boolean | When the value is "true", it indicates that the user tapped the "OK" button. |
#
mpService.showActionSheetDisplays the action sheet.
#
ParametersProperty | Type | Default Value | Required | Description |
---|---|---|---|---|
alertText | string | - | Alert text | |
itemList | string[] | - | ✓ | The text array of the button, with a length limited to 6 |
itemColor | string | #000000 | The text color of the button |
#
Return ValuesObject res
Property | Type | Description |
---|---|---|
tapIndex | number | The sequence number of the button tapped by the user, from top to bottom and starting from 0 |
#
mpService.setNavigationBarTitleDynamically sets the title of the current page.
#
ParametersProperty | Type | Default Value | Required | Description |
---|---|---|---|---|
title | string | ✓ | title of the navigation bar |
#
mpService.setTabBarItemDynamically sets the content of a tabBarn item.
#
ParametersProperty | Type | Default Value | Required | Description |
---|---|---|---|---|
index | number | ✓ | Specifies which item of tabBar, starting from the left. | |
text | string | The text of a button on tab. | ||
iconPath | string | The path to the icon. The icon size is limited to 40 KB. Recommended size is 81 px * 81 px, This parameter does not take effect when position is top. | ||
selectedIconPath | string | The path to the selected icon. The icon size is limited to 40 KB. Recommended size is 81 px * 81 px, This parameter does not take effect when position is top. |
#
mpService.showTabBarDisplay tabBar.
#
ParametersProperty | Type | Default Value | Required | Description |
---|---|---|---|---|
animation | boolean | false | Show animation effect |
#
mpService.hideTabBarHide tabBar.
#
ParametersProperty | Type | Default Value | Required | Description |
---|---|---|---|---|
animation | boolean | false | Show animation effect |
#
mpService.showTabBarRedDotShow red dot on the right top corner of tab bar item.
#
ParametersProperty | Type | Default Value | Required | Description |
---|---|---|---|---|
index | number | ✓ | The index of the tab bar item from left. The first one is 0 |
#
mpService.hideTabBarRedDotHide red dot of tab bar item.
#
ParametersProperty | Type | Default Value | Required | Description |
---|---|---|---|---|
index | number | ✓ | The index of the tab bar item from left. The first one is 0 |
#
mpService.pageScrollToScrolls the screen to the target location
#
ParametersProperty | Type | Default Value | Required | Description |
---|---|---|---|---|
scrollTop | number | No | Scrolls the screen to the target location (in px) | |
duration | number | 300 | No | Scrolls the screen to the target location (in px) |
selector | string | No | selector |
#
selector syntaxselector is similar to CSS selector, but only supports the following syntax.
- ID selector:
#the-id
- class selector:
.a-class.another-class
- child selector:
.the-parent > .the-child
- descendant selector:
.the-ancestor .the-descendant
- Descendant selector across custom components:
.the-ancestor >>> .the-descendant
- Union of multiple selectors:
#a-node, .some-other-nodes
#
mpService.hideHomeButtonHide Back HomeButton.When the bottom page of the mini program opened by the user is not the homepage, the "Back to Homepage" button is displayed by default. Developers can use hideHomeButton
in the onShow/componentDidShow page to hide HomeButton.
#
Media#
mpService.chooseImageSelects an image from the local album or takes a photo with the camera.
#
ParametersProperty | Type | Default Value | Required | Description |
---|---|---|---|---|
count | number | 9 | no | The maximum number of images allowed |
sizeType | Array. | ['original', 'compressed'] | no | The size of the select image |
sourceType | Array. | ['album', 'camera'] | no | The source of the image |
#
Valid values of object.sizeTypeValue | Description |
---|---|
original | Original image |
compressed | Compressed image |
#
Valid values of object.sourceTypeValue | Description |
---|---|
album | Selects an image from the album |
camera | Takes a photo with the camera |
#
Return ValuesProperty | Type | Description |
---|---|---|
tempFilePaths | Array. | The list of local temporary file paths to images |
tempFiles | Array.<Object> | The local temporary file list for images |
#
res.tempFiles is composed as followsProperty | Type | Description |
---|---|---|
path | string | The path to the local temporary file |
size | number | The size of a local temporary file, in bytes |
#
mpService.previewImagePreview the picture in full screen on the new page. Preview the process of the user can save pictures, send to friends and other operations.
#
ParametersProperty | Type | Default Value | Required | Description |
---|---|---|---|---|
urls | Array.<string> | yes | A list of links to images that need to be previewed. | |
showmenu | boolean | true | no | Displays long press menu |
current | string | urls The first one. | no | Link to currently displayed picture |
referrerPolicy | string | no-referrer/origin | no | origin: Send the full referrer no-referrer: Do not send. |
#
mpService.saveImageToPhotosAlbumSave the image to the system album.
#
ParametersProperty | Type | Default Value | Required | Description |
---|---|---|---|---|
filePath | number | no | Image file path, which can be temporary file path or permanent file path (Local path) Network path not supported |
#
mpService.onAudioInterruptionBegin(function callback)Listen audio is interrupted by system occupation. Start event. The following scenarios trigger this event: alarm clock, phone, FaceTime Call, voice chat, video chat. When this event is triggered, all audio in the Mini Program will pause.
#
mpService.onAudioInterruptionEnd(function callback)Listen for audio interrupt end event. Received. onAudioInterruptionBegin After the event, all audio in the Mini Program will be suspended and can be played again after receiving this event.
#
mpService.offAudioInterruptionBegin(function callback)Cancel listening audio is interrupted due to system occupation Start event
#
mpService.offAudioInterruptionEnd(function callback)Unlisten Audio Interrupt End Event
#
mpService.setInnerAudioOption(Object object)Set the options of InnerAudioContext. Set to take effect globally for the current Mini Program.
object
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
mixWithOther | boolean | true | Whether to mix with other audio. Set to true, after that, the music in other apps or Binance will not be terminated. | |
obeyMuteSwitch | boolean | true | (iOS only) Whether to follow the mute switch. Set to false, after that, the sound can be played even in silent mode. | |
speakerOn | boolean | true | true Stand for playing on speaker. false Represents handset playback. |
#
mpService.createInnerAudioContext()Creates the context InnerAudioContext object for an internal audio.
#
InnerAudioContext#
string srcThe audio file address which can be used to play the audio file directly.
#
number startTimeThe position where the playback starts (in sec). It is 0 by default.
#
boolean autoplayWhether to enable auto playback. It is false by default.
#
boolean loopWhether to enable loop playback. It is false by default.
#
boolean obeyMuteSwitchWhether to follow the "Mute" switch. It is true by default. If it is set to false, the audio file still sounds even if the "Mute" switch is on.
#
number volumeSpecifies the volume, which ranges from 0 to 1. It is 1 by default.
#
number playbackRateSpecifies the playbackRate, which ranges from 0.5 to 2. It is 1 by default.
#
number durationThe length of the audio file (in sec). It is only returned when a valid src attribute exists (read only).
#
number currentTimeThe position where the playback has got to (in sec). It is only returned when a valid src attribute exists and is rounded to six decimal places (read only).
#
boolean pausedWhether the playback is paused or stopped (read only).
#
number bufferedThe position where the audio is buffered. Only the part between the position where the playback has got to and this position is buffered (read only).
#
string referrerPolicyorigin
: send request with referrerno-referrer
: do send with referrer
#
InnerAudioContext.play()Plays an audio file.
#
InnerAudioContext.pause()Pauses the audio playback. The playback is resumed at the point where it was paused.
#
InnerAudioContext.stop()Stops the audio playback. The playback starts from the beginning if the file is played again.
#
InnerAudioContext.seek(number position)Jumps to the specific position.
#
InnerAudioContext.destroy()Terminates the current instance.
#
InnerAudioContext.onCanplay(function callback)Listens on the event that an audio file is ready for playback. A smooth playback is not guaranteed.
#
InnerAudioContext.offCanplay(function callback)Un-listens on the event that an audio file is ready for playback.
#
InnerAudioContext.onPlay(function callback)Listens on the audio playback event.
#
InnerAudioContext.offPlay(function callback)Un-listens on the audio playback event.
#
InnerAudioContext.onPause(function callback)Listens on the audio pause event.
#
InnerAudioContext.offPause(function callback)Un-listens on the audio pause event.
#
InnerAudioContext.onStop(function callback)Listens on the event of stopping audio playback.
#
InnerAudioContext.offStop(function callback)Un-listens on the event of stopping audio playback.
#
InnerAudioContext.onEnded(function callback)Listens on the event of playing an audio file to the end without interruption.
#
InnerAudioContext.offEnded(function callback)Un-listens on the event of playing an audio file to the end without interruption.
#
InnerAudioContext.onTimeUpdate(function callback)Listens on the event of updating audio playback progress.
#
InnerAudioContext.offTimeUpdate(function callback)Un-listens on the event of updating audio playback progress.
#
InnerAudioContext.onError(function callback)Listens on the audio playback error event.
#
InnerAudioContext.offError(function callback)Un-listens on the audio playback error event.
#
InnerAudioContext.onWaiting(function callback)Listens on the audio loading event. It is triggered when the playback of an audio file stops to load the file due to insufficient data.
#
InnerAudioContext.offWaiting(function callback)Un-listens on the audio loading event.
#
InnerAudioContext.onSeeking(function callback)Listens on the event of jumping to a specific position in the audio file.
#
InnerAudioContext.offSeeking(function callback)Un-listens on the event of jumping to a specific position in the audio file.
#
InnerAudioContext.onSeeked(function callback)Listens on the event of finishing the jump to a specific position in the audio file.
#
InnerAudioContext.offSeeked(function callback)Un-listens on the event of finishing the jump to a specific position in the audio file.
#
mpService.createVideoContext(id)Creates the VideoContext object for the video.
#
ParametersProperty | Type | Default Value | Required | Description |
---|---|---|---|---|
id | string | ✓ | The video component's ID |
#
Return ValuesVideoContext
videoContext.play
#
Plays the video.
videoContext.pause
#
Pauses the video.
videoContext.stop
#
Stops the video.
videoContext.seek(position)
#
Jumps to the specific position.
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
position | number | ✓ | The position to be jumped to (in sec) |
videoContext.playbackRate(rate)
#
Sets multi-speed playback.
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
rate | number | ✓ | Indicates the playback speed (0.5x/0.8x/1x/1.25x/1.5x). |
videoContext.requestFullScreen
#
Enters the full screen.
videoContext.exitFullScreen
#
Exits the full screen.
videoContext.exitPictureInPicture
#
Exits the picture in picture mode.
#
Custom ComponentDefers some operations until the next time slice. (similar to setTimeout)
#
mpService.nextTick(function callback)#
ParametersProperty | Type | Default Value | Required | Description |
---|---|---|---|---|
callback | function | - | ✓ | the callback function |
#
Keyboard#
mpService.onKeyboardHeightChange(callback function)Listens on the keyboard height changes
#
ParametersProperty | Type | Default Value | Required | Description |
---|---|---|---|---|
callback | function | - | ✓ | the callback function |
#
mpService.offKeyboardHeightChange(callback function)Remove the listener on the keyboard height changes
#
ParametersProperty | Type | Default Value | Required | Description |
---|---|---|---|---|
callback | function | - | ✓ | the callback function |
#
Sample code#
mpService.hideKeyboardHide keyboard
#
Sample code#
mpService.getSelectedTextRangeObtains the cursor position of the input box after the focus of input, textarea, etc. Note: This API works only when it is called during the focus process.
#
Sample code#
Network#
mpService.requestInitiates an HTTPS request.
#
ParametersProperty | Type | Default Value | Required | Description |
---|---|---|---|---|
url | string | - | ✓ | request url |
data | string | - | request params | |
header | object | - | set request header, can't set Referer . default value of content-type is application/json | |
timeout | number | 10000 | timeout of request, unit is millisecond | |
method | string | 'GET' | HTTP request method | |
dataType | string | 'json' | Returned data format | |
responseType | string | 'text' | Response data type | |
success | function | Callback function for successful interface call | ||
fail | function | Callback function for failed interface call | ||
complete | function | The callback function for the end of the interface call |
object.dataType
#
Available values of Value | Description |
---|---|
'json' | The returned data is JSON. After returning, JSON.parse will be performed on the returned data. |
others | Do not perform JSON.parse on the returned content |
object.responseType
#
Available values of Value | Description |
---|---|
'text' | The response data is text |
'arraybuffer' | The response data is ArrayBuffer |
object.success
callback#
Parameters of Object res
Property | Type | Description |
---|---|---|
data | string/Object/Arraybuffer | Data returned by the developer server |
statusCode | number | The status code of the response. (This will be 200 for a success). |
header | Object | The Header object associated with the response. |
statusText | string | The status message corresponding to the status code. (e.g., OK for 200). |
data
parameter#
Description of The final data sent to the server is of type String. If the data passed in is not of type String, it will be converted to String. The conversion rules are as follows:
- For the data of the
GET
method, the data will be converted into query string:
For data with POST method and header['content-type'] is application/json, the data will be serialized in JSON
For POST method and header['content-type'] is application/x-www-form-urlencoded data, the data will be converted into query string
#
Return ValuesRequestTask
Request task
requestTask.abort
#
Interrupt request task
requestTask.onHeadersReceived(callback)
#
Listen to the HTTP Response Header event. Will be earlier than the requested completion event
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
callback | function | - | ✓ | The callback function. ({ header: Object }) => void |
requestTask.offHeadersReceived(callback)
#
Cancel listening for HTTP Response Header event
#
mpService.downloadFileDownloads local resources to the local device. The client initiates an HTTPS GET request. The local temporary path to the file is returned.
Note: Specify a reasonable Content-Type field in the server response header to ensure that the client handles the file type properly.
#
ParametersProperty | Type | Default Value | Required | Description |
---|---|---|---|---|
url | string | - | ✓ | URL to download resources |
header | object | - | Set request header, can't set Referer . default value of content-type is application/json | |
timeout | number | 60000 | timeout of request, unit is millisecond | |
filePath | string | Specify the path where the file is stored after downloading (local path) | ||
success | function | Callback function for successful interface call | ||
fail | function | Callback function for successful interface call | ||
complete | function | The callback function for the end of the interface call |
object.success
callback#
Parameters of Object res
Property | Type | Description |
---|---|---|
tempFilePath | string | Temporary file path. It is returned when the filePath to save files is not specified. The downloaded files will be stored in a temporary file path. |
filePath | string | User file path (local path). It will be returned when filePath is passed in, which is consistent with the filePath passed in |
statusCode | number | HTTP status code returned by the developer server |
#
Return ValuesDownloadTask
An object that can monitor the download progress change event and cancel the download
downloadTask.abort
#
Interrupt download task
downloadTask.onHeadersReceived(callback)
#
Listen to the HTTP Response Header event. Will be earlier than the requested completion event
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
callback | function | - | ✓ | The callback function. ({ header: Object }) => void |
downloadTask.offHeadersReceived(callback)
#
Cancel listening for HTTP Response Header event
downloadTask.onProgressUpdate(callback)
#
Monitor download progress change events.
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
callback | function | - | ✓ | The callback function. (progress) => void |
#
Parameters object of callback functionProperty | Type | Description |
---|---|---|
progress | number | Download progress percentage |
totalBytesWritten | number | The length of the downloaded data, in Bytes |
totalBytesExpectedToWrite | number | The total length of data expected to be downloaded, in Bytes |
downloadTask.offProgressUpdate(callback)
#
Cancel listening to download progress change event
#
mpService.uploadFileUpload local resources to the server. The client initiates an HTTPS POST request, where the content-type
is multipart/form-data
.
#
ParametersProperty | Type | Default Value | Required | Description |
---|---|---|---|---|
url | string | ✓ | The HTTPS API URL of developer server | |
filePath | string | ✓ | The path of the file resource to be uploaded (local path) | |
name | string | ✓ | The key corresponding to the file, the server can get the file content through this key | |
header | Object | Header of HTTP request, Referer cannot be set in Header | ||
formData | Object | Other additional form data in the HTTP request | ||
timeout | number | 60000 | timeout of request, unit is millisecond | |
success | function | Callback function for successful interface call | ||
fail | function | Callback function for successful interface call | ||
complete | function | The callback function for the end of the interface call |
object.success
callback#
Parameters of Object res
Property | Type | Description |
---|---|---|
data | string | Data returned by the developer server |
statusCode | number | HTTP status code returned by the developer server |
#
Return ValuesUploadTask
An object that can monitor upload progress change events and cancel upload tasks
uploadTask.abort
#
Interrupt upload task
uploadTask.onHeadersReceived(callback)
#
Listen to the HTTP Response Header event. Will be earlier than the requested completion event
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
callback | function | - | ✓ | The callback function. ({ header: Object }) => void |
uploadTask.offHeadersReceived(callback)
#
Cancel listening for HTTP Response Header event
uploadTask.onProgressUpdate(callback)
#
Monitor upload progress change events.
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
callback | function | - | ✓ | The callback function. (progress) => void |
#
Parameters object of callback functionProperty | Type | Description |
---|---|---|
progress | number | The percentage of upload progress |
totalBytesSent | number | The length of the uploaded data, in Bytes |
totalBytesExpectedToSend | number | The total length of data expected to be uploaded, in Bytes |
uploadTask.offProgressUpdate(callback)
#
Cancel listening to upload progress change event
#
Example#
mpService.createBufferURL(buffer): urlcreate a unique url in memory
payload
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
buffer | ArrayBuffer/TypedArray | - | ✓ | The data to be sent. |
response
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
url | string | ✓ | unique url on native |
#
mpService.revokeBufferURL(url): voidrevoke a unique url in memory
payload
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
url | string | ✓ | unique url on native |
example:
#
mpService.connectSocketCreates a WebSocket connection.
#
ParametersProperty | Type | Default Value | Required | Description |
---|---|---|---|---|
url | string | - | ✓ | The wss API URL of developer server |
header | object | - | set request header, can't set Referer . default value of content-type is application/json | |
protocols | string[] | - | Sub-protocol array. |
#
Return ValuesSocketTask
WebSocket task
socketTask.send
#
Sends data over a WebSocket connection.
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
data | string/ArrayBuffer | - | ✓ | The data to be sent. |
socketTask.close
#
Disables the WebSocket connection.
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
code | number | 1000 (indicating that the connection is disabled normally) | A numeric value indicates the status code explaining why the connection has been disabled. | |
reason | string | - | A readable string explaining why the connection has been disabled. This string must be a UTF-8-encoded text (not characters) with not more than 123 bytes. |
socketTask.onOpen(callback)
#
Listens on the event of enabling the WebSocket connection.
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
callback | function | - | ✓ | The callback function. ({ header: Object }) => void |
socketTask.onClose(callback)
#
Listens on the event of disabling the WebSocket connection.
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
callback | function | - | ✓ | The callback function. () => void |
socketTask.onError(callback)
#
Listens on the WebSocket error event.
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
callback | function | - | ✓ | The callback function. ({ errMsg: string }) => void |
socketTask.onMessage(callback)
#
Listens on the event of receiving server messages by WebSocket
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
callback | function | - | ✓ | The callback function. ({ data: string/ArrayBuffer }) => void |
#
Number of Concurrent Connections- Up to 5 WebSocket connections can exist at the same time.
#
Data Caching#
mpService.getStorageInfoGets the information related to the current storage.
#
Return ValuesObject res
Property | Type | Description |
---|---|---|
keys | string[] | All keys in the current storage |
currentSize | number | Current space occupied (in KB) |
limitSize | number | Space size limit (in KB) |
#
mpService.getStorageGets the content of the specified key from the local cache
#
ParametersProperty | Type | Default Value | Required | Description |
---|---|---|---|---|
key | string | ✓ | The specified key in the local cache |
#
Return ValuesObject res
Property | Type | Description |
---|---|---|
data | any | Content of the key |
#
mpService.setStorageStores data in the specified key in the local cache. This operation will overwrite the original content of the key. The data storage lifecycle is consistent with the Mini Program, that is, data is always available unless manually deleted by the user or automatically deleted after a certain period of time.
#
ParametersProperty | Type | Default Value | Required | Description |
---|---|---|---|---|
key | string | ✓ | The specified key in the local cache | |
data | any | ✓ | Contents to be stored can only be native types, dates, and objects that can be serialized via JSON.stringify. |
#
mpService.removeStorageRemoves the specified key from the local cache.
#
ParametersProperty | Type | Default Value | Required | Description |
---|---|---|---|---|
key | string | ✓ | The specified key in the local cache |
#
mpService.clearStorageClears the data cached locally.
#
File System Manager#
mpService.getFileSystemManagerGet the file system manager instance which is a singleton. On Android devices, file system api will save file on external storage by default.
#
Return ValuesObject res
Property | Type | Description |
---|---|---|
readFile | Function | Read files in local directory. |
#
FileSystemManager.readFile#
ParametersProperty | Type | Default Value | Required | Description |
---|---|---|---|---|
filePath | string | ✓ | The file path to read. | |
encoding | string | File's character encoding. if not provided, read it in format of ArrayBuffer. | ||
position | number | Read file starting from specific position.If not provided, start from file head.The reading range should be left-closed and right-open, [position, position+length). Valid range: [0, fileLength - 1].Unit: byte. | ||
length | number | Specify the length of file. If not provided, read until the end of file.Valid range: [1, fileLength].Unit: byte. |
- About filePath: filePath should starts from root directory of source code bundle.Only supports absolute path like
/a/b
ora/b
.Files with extensions ofjs,json,bxss,bxm
will be transformed into other files after compilation, so they are not expected to be accessible. - Valid value of encoding: utf-8, utf8
response
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
data | string or ArrayBuffer | ✓ | File content in string or ArrayBuffer format. |
#
FileSystemManager.readFileSync(filePath, encoding?, position?, length?): data#
ParametersProperty | Type | Default Value | Required | Description |
---|---|---|---|---|
filePath | string | ✓ | The file path to read. | |
encoding | string | File's character encoding. if not provided, read it in format of ArrayBuffer. | ||
position | number | Read file starting from specific position.If not provided, start from file head.The reading range should be left-closed and right-open, [position, position+length). Valid range: [0, fileLength - 1].Unit: byte. | ||
length | number | Specify the length of file. If not provided, read until the end of file.Valid range: [1, fileLength].Unit: byte. |
- About filePath: filePath should starts from root directory of source code bundle.Only supports absolute path like
/a/b
ora/b
.Files with extensions ofjs,json,bxss,bxm
will be transformed into other files after compilation, so they are not expected to be accessible. - Valid value of encoding: utf-8, utf8
#
Return ValueProperty | Type | Default Value | Required | Description |
---|---|---|---|---|
data | string or ArrayBuffer | ✓ | File content in string or ArrayBuffer format. |
#
FileSystemManager.writeFile(options)#
Parametersoptions
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
filePath | string | ✓ | The file path to write data in. | |
data | string or ArrayBuffer | ✓ | The data to write. | |
encoding | string | utf8 | Character encoding of the file to be written. |
#
Response#
FileSystemManager.writeFileSync(filePath, data, encoding?): void#
ParametersProperty | Type | Default Value | Required | Description |
---|---|---|---|---|
filePath | string | ✓ | The file path to write data in. | |
data | string or ArrayBuffer | ✓ | The data to write. | |
encoding | string | utf8 | Character encoding of the file to be written. |
#
Return Value#
FileSystemManager.mkdir(options): void#
Parametersoptions
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
dirPath | string | ✓ | The directory to create. | |
recursive | boolean | false | Whether to create parent directories recursively before create the specific one. If the parent directories exist, skip this step. For example if dirPath is a/b/c/d and recursive is true, create a at first and then a/b and so on until a/b/c/d |
#
Response#
FileSystemManager.mkdirSync(dirPath, recursive?): void#
ParametersProperty | Type | Default Value | Required | Description |
---|---|---|---|---|
dirPath | string | ✓ | The directory to create. | |
recursive | boolean | false | Whether to create parent directories recursively before create the specific one. If the parent directories exist, skip this step. For example if dirPath is a/b/c/d and recursive is true, create a at first and then a/b and so on until a/b/c/d |
#
Return Value#
FileSystemManager.access(options): void#
Parametersoptions
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
path | string | ✓ | To check whether this file/directory exits. |
#
Response#
FileSystemManager.accessSync(path): void#
ParametersProperty | Type | Default Value | Required | Description |
---|---|---|---|---|
path | string | ✓ | To check whether this file/directory exits. |
#
Return Value#
Location#
mpService.openLocationViews location using the built-in map.
#
ParametersProperty | Type | Default Value | Required | Description |
---|---|---|---|---|
latitude | number | - | ✓ | Latitude. The value ranges from -90 to +90, and the negative number means south latitude. The GCJ-02 coordinate system of the State Bureau of Surveying and Mapping is used. title |
longitude | number | - | ✓ | Longitude. The value ranges from -180 to +180, and the negative number means west longitude. The GCJ-02 coordinate system of the State Bureau of Surveying and Mapping is used. content |
scale | number | 18 | Scale, ranging from 5 to 18 | |
name | string | Location name | ||
address | string | Detailed address |
#
mpService.getLocationGets current geographic location and speed. The API cannot be called when the user exits the Mini Program.
#
ParametersProperty | Type | Default Value | Required | Description |
---|---|---|---|---|
type | string | wgs84 | GPS coordinates are returned for WGS84, and coordinates used for mpService.openLocation are returned for GCJ-02. | |
altitude | boolean | false | Altitude information is returned if true is passed. The API will take a longer time to respond since a higher accuracy is required to obtain the altitude. |
#
Return ValuesObject res
Property | Type | Description |
---|---|---|
latitude | number | Latitude. The value ranges from -90 to +90, and the negative number means south latitude. |
longitude | number | Longitude. The value ranges from -180 to +180, and the negative number means west longitude. |
speed | number | speed(unit: m/s) |
accuracy | number | Location accuracy |
altitude | number | altitude(unit: m) |
verticalAccuracy | number | Vertical accuracy(unit: m) |
horizontalAccuracy | number | Horizontal accuracy(unit: m) |
#
mpService.chooseLocationOpens the map to select a location.
#
ParametersProperty | Type | Default Value | Required | Description |
---|---|---|---|---|
latitude | number | - | Latitude of the target. | |
longitude | number | - | Longitude of the target. |
#
Return ValuesObject res
Property | Type | Description |
---|---|---|
name | string | Location name brand |
address | string | Detailed address platform |
latitude | number | Latitude, which is expressed by a floating point number ranging from -90 to +90, and the negative number means south latitude. The GCJ-02 coordinate system of the State Bureau of Surveying and Mapping is used. |
longitude | number | Longitude, which is expressed by a floating point number ranging from -180 to +180, and the negative number means west longitude. The GCJ-02 coordinate system of the State Bureau of Surveying and Mapping is used. |
#
mpService.startLocationUpdateStart monitoring real-time position changes in the foreground
#
mpService.stopLocationUpdateStop monitoring real-time location changes
#
mpService.onLocationChangeSubscribe the event of real-time location changes,used with mpService.startLocationUpdate
.
#
mpService.offLocationChangeUnsubscribe the event of real-time location changes.
#
Example#
Open APIS#
mpService.loginGets the login credential (code), which is then used to exchange for the user login status information, including the unique identifier (openid) of the user and the session key (session_key) of the current login.
#
Return ValuesObject res
Property | Type | Description |
---|---|---|
code | string | The authorization code. |
#
mpService.getUserProfileGet user information.
#
Return ValuesObject res
Property | Type | Description |
---|---|---|
userInfo | Object | User information object. |
Object userInfo
Property | Type | Description |
---|---|---|
nickName | string | User nickname |
avatarUrl | string | User profile picture URL |
#
mpService.isLoggedIncheck whether the user is logged in or not
#
Return ValuesProperty | Type | Description |
---|---|---|
result | bool | whether the user is logged in or not |
#
mpService.requestPaymentInitiates a request for payment via Binance Pay.
#
ParametersObject payload
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
certSn | string | - | ✓ | API identity key issued by Binance payment system |
merchantId | string | - | ✓ | The merchant account id, issued when merchant been created at Binance. |
timeStamp | string | - | ✓ | timestamp of the sign |
nonceStr | string | - | ✓ | nonceStr for the sign |
package | string | - | ✓ | The value of the prepay_id parameter returned by the unified order placement API |
paySign | string | - | ✓ | Signature. For specific signature schemes, see Binance Pay API Documentation |
#
Return ValuesObject res
Property | Type | Description |
---|---|---|
status | string | 0 : pay success others : pay failed |
Notes the response is a string, not a number.
example:
#
mpService.getPerformanceGets the performance information
#
Return ValuesPerformance
performance.getEntries
#
Get all current performance information.
Return Entry[]
Entry
property
Property | Type | Description |
---|---|---|
entryType | navigation, render, script | type of entry |
name | string | name of entry |
startTime | number | start time of entry |
duration | number | total time of entry |
path | string | path |
navigationStart | number | the real time of navigation |
navigationType | string | type of navigation |
entryType | Description |
---|---|
navigation | appLaunch : time of app launch. route : performance of routing |
render | firstRender : first render time |
script | evaluateScript : inject script time |
Example
#
mpService.getWeb3ProviderGet web3 provider of DWallet.
https://docs.metamask.io/guide/ethereum-provider.html
#
Return ValuesObject Web3Provider
Property | Type | Description |
---|---|---|
request | Function | docs |
on | Function | docs |
Example
#
mpService.authCaptureAuthCapture is the entrance to initiate auth capture for merchants. Pre-authorization is a function launched by Binance Pay for merchants in consumption scenarios (such as taxis, hotel reservations, etc.) that require users to make guarantees in advance. The user needs to make a fund authorization when the service is started. When the service is settled, the consumption amount will be deducted from the authorized fund, and the rest will be returned to the user.
#
ParametersProperty | Type | Default Value | Required | Description |
---|---|---|---|---|
certSn | string | - | ✓ | API identity key issued by Binance payment system |
merchantId | string | - | ✓ | The merchant account id, issued when merchant been created at Binance. |
noncestr | string | - | ✓ | A random string with 32 bytes, e.g. random ascii decimal within a-z and A-Z and loop 32 times to form a random string |
cashierId | string | - | ✓ | the cashierId got from generateCashierUrl API |
timeStamp | string | - | ✓ | UnixTimestamp in millis that the requests send, guarantee the machine time is sync with the network |
paySign | string | - | ✓ | A signature generated according to a certain logic. |
#
Return ValuesObject res
Property | Type | Description |
---|---|---|
status | string | "SUCCESS" or "FAIL"。"0" for success |
#
Device#
mpService.setClipboardDataSet the contents of the system clipboard.
#
ParametersProperty | Type | Default Value | Required | Description |
---|---|---|---|---|
data | string | ✓ | Clipboard content |
#
Return Values#
mpService.getClipboardDataGet the contents of the system clipboard.
#
Parameters#
Return ValuesObject res
Property | Type | Description |
---|---|---|
data | string | Clipboard content |
#
mpService.onNetworkStatusChangeListens on the network status change event.
#
Parameters#
function callbackThe callback function for the network status change event.
#
ParametersObject res
Property | Type | Description |
---|---|---|
isConnected | boolean | Indicates whether it is connected to the network |
networkType | string | Network type |
Valid values of networkType
Value | Description |
---|---|
wifi | Wi-Fi network |
2g | 2G network |
3g | 3G network |
4g | 4G network |
5g | 5G network |
unknown | Uncommon network types for Android |
none | No network |
#
Return Values#
mpService.offNetworkStatusChangeUn-listens on Mini Program network status change event.
#
Parameters#
function callbackCancel the callback function for the network status change event.
#
mpService.getNetworkTypeGets the network type.
#
Parameters#
Return ValuesObject res
Property | Type | Description |
---|---|---|
networkType | string | Network type |
signalStrength | number | Signal strength, dbm |
errMsg | string | error info |
#
mpService.scanCodeTun up the client scan code interface for scanning code.
#
ParametersProperty | Type | Default Value | Required | Description |
---|---|---|---|---|
scanType | Array. | ['qrCode'] | - | Scan code type |
#
Return ValuesProperty | Type | Default Value | Required | Description |
---|---|---|---|---|
result | string | - | the content of scanned code | |
scanType | string | - | the type of scanned code |
Object scanType
Value | Description | Version |
---|---|---|
QR_CODE | QR Code | - |
#
mpService.startCompassStart monitoring compass data.
#
mpService.stopCompassStop listening to compass data.
#
mpService.onCompassChangeMonitor compass data changes. Frequency: 5 second/Seconds, the interface will automatically start listening after the call, you can use the mpService.stopCompass
Stop listening.
#
parameterfunction callback Callback function for compass data change events
#
Return Valuesfunction callback Callback function for compass data change events
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
direction | number | - | Degree of direction faced | |
accuracy | number/string | - | accuracy |
#
mpService.offCompassChangeCancel listening compass data change event, the parameter is empty, then cancel all the event listening.
#
parameterfunction callback
Callback function for compass data change events
#
mpService.startAccelerometerStart monitoring the acceleration data.
#
ParametersProperty | Type | Default Value | Required | Description |
---|---|---|---|---|
interval | string | normal | - | Monitor the execution frequency of the acceleration data callback function |
Object interval
Value | Description | Version |
---|---|---|
game | The callback frequency for updating the game, in 20ms/second About | - |
ui | Apply to update UI Callback frequency of 60ms/second About | - |
normal | Normal callback frequency, in the 200ms/second About | - |
#
mpService.stopAccelerometerStop listening for acceleration data.
#
mpService.onAccelerometerChangeListen for acceleration data events. Frequency basis mpService.startAccelerometer()
of interval Parameters, Interface calls automatically start listening
#
parameterfunction callback
Acceleration Data Event Callback Function
#
Return ValuesProperty | Type | Default Value | Required | Description |
---|---|---|---|---|
x | number | - | X axis | |
y | number | - | - | Y axis |
z | number | - | - | Z axis |
#
mpService.offAccelerometerChangeCancel monitoring of acceleration data events. If the parameter is null, cancel all event monitoring.
#
parameterfunction callback
Acceleration Data Event Callback Function
#
mpService.startDeviceMotionListeningStart listening for changes in device orientation.
#
ParametersProperty | Type | Default Value | Required | Description |
---|---|---|---|---|
interval | string | normal | - | Monitor device direction change callback function execution frequency |
Object interval
Value | Description | Version |
---|---|---|
game | The callback frequency for updating the game, in 20ms/second About | - |
ui | Apply to update UI Callback frequency of 60ms/second About | - |
normal | Normal callback frequency, in the 200ms/second About | - |
#
mpService.stopDeviceMotionListeningStop listening for changes in device direction.
#
mpService.onDeviceMotionChangeListen for device direction change events. Frequency basis mpService.startDeviceMotionListening()
of interval Parameters. Can be used mpService.stopDeviceMotionListening()
Stop listening.
#
parameterfunction callback
Callback function for device orientation change event
#
Return ValuesProperty | Type | Default Value | Required | Description |
---|---|---|---|---|
alpha | number | - | - | when Cell phone coordinates X/And and Earth X/And When overlapped, around. With the angle at which the axis rotates is Alpha, with a range value of [0, 2*PI). Turning counterclockwise is positive. |
beta | number | - | - | When the phone coordinates And/With And the Earth And/With When overlapped, around. X The angle at which the axis rotates is beta。 Range values are [-1PI, PI) The top is turned positive towards the Earth's surface. It is also possible to be positive towards the user. |
gamma | number | - | - | When the phone X/With And the Earth X/With When overlapped, around. And The angle at which the axis rotates is gamma。 Range values are [-1PI/2, PI/2)The right side turns positive toward the Earth's surface. |
#
mpService.offDeviceMotionChangeCancels listening device direction change event, parameter is null, then cancels all event monitoring.
#
parameterfunction callback
Callback function for device orientation change event
#
mpService.startGyroscopeStart monitoring the gyroscope data.
#
ParametersProperty | Type | Default Value | Required | Description |
---|---|---|---|---|
interval | string | normal | - | Monitor the execution frequency of the gyro data callback function |
Object interval
Value | Description | Version |
---|---|---|
game | The callback frequency for updating the game, in 20ms/second About | - |
ui | Apply to update UI Callback frequency of 60ms/second About | - |
normal | Normal callback frequency, in the 200ms/second About | - |
#
mpService.stopGyroscopeStop monitoring the gyroscope data.
#
mpService.onGyroscopeChangeMonitor gyro data change events. Frequency basis mpService.startGyroscope()
of interval Parameters. Can be used mpService.stopGyroscope()
Stop listening.
#
parameterfunction callback
A callback function for gyro data change events
#
Return ValuesProperty | Type | Default Value | Required | Description |
---|---|---|---|---|
x | number | - | X axis | |
y | number | - | - | Y axis |
z | number | - | - | Z axis |
#
mpService.offDeviceMotionChangeUnlisten for gyro data change events.
#
parameterfunction callback
A callback function for gyro data change events
#
mpService.onMemoryWarningListens for out-of-memory warning events.
when iOS/Android This event is triggered when a memory warning is issued to the Mini Programs process. Triggering the event does not mean that the Mini Program is killed. In most cases, it is just an alarm. Developers can recover some unnecessary resources after receiving the notification to avoid further aggravating memory strain.
#
parameterfunction callback
Callback function for out-of-memory warning event
#
Return ValuesProperty | Type | Default Value | Required | Description |
---|---|---|---|---|
level | number | - | Memory alert level, only Android There is, corresponding to the system macro definition |
level Legal value
value | Introductions Minimum |
---|---|
5 | TRIM_MEMORY_RUNNING_MODERATE |
10 | TRIM_MEMORY_RUNNING_LOW |
15 | TRIM_MEMORY_RUNNING_CRITICAL |
#
mpService.offMemoryWarningCancels listening for out-of-memory warning events.
#
parameterfunction callback
Callback function for out-of-memory warning event
#
mpService.vibrateShortMake the mobile phone vibrate for a short time (15 ms). Only in iPhone 7 / 7 More Above and Android Model entry into force.
#
ParametersProperty | Type | Default Value | Required | Description |
---|---|---|---|---|
type | string | yes | Vibration intensity type, valid values are: heavy, medium, light |
#
mpService.vibrateLongMake the phone vibrate for a longer time (400 ms)
#
Open Databn.setUserCloudStorage
#
Writes data to the user's hosted data. Multiple sets of KV data can be written at a time.
payload
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
KVDataList | Array.<{key: string; value: string}> | ✓ | The list of KV data to be modified |
response
Property | Type | Default Value | Required | Description |
---|
bn.removeUserCloudStorage
#
Deletes the key data from the hosted data of the user.
payload
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
keyList | Array.<string> | ✓ | The list of keys to be deleted. |
response
Property | Type | Default Value | Required | Description |
---|
bn.getUserCloudStorage
#
Gets the key data in the hosted data of the current user.
payload
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
keyList | Array.<string> | ✓ | The list of keys to be obtained. |
response
Property | Type | Description |
---|---|---|
KVDataList | Array.<{key: string; value: string}> | The user's hosted KV data list. |
bn.getUserCloudStorageKeys
#
Gets the keys in the hosted data of the current user.
payload
Property | Type | Default Value | Required | Description |
---|
response
Property | Type | Description |
---|---|---|
keyList | Array.<string> | The list of keys. |
#
Leaderboardbn.showLeaderboardPanel
#
Open the leaderboard panel by api. The game center.
payload
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
leaderboardId | string | ✓ | Id for the leaderboard |
response
Property | Type | Default Value | Required | Description |
---|
#
Sharebn.showSharePanel
#
Pop up the sharing panel.
bn.hideShareMenu
#
Hide the Share button on the current page.
#
Animation#
Page.animateIn the page or custom component, when you need to perform key frame animation, you can use Page.animate
interface:
#
ParametersProperty | Type | Default Value | Required | Description |
---|---|---|---|---|
selector | string | ✓ | Selector (same as the selector format of SelectorQuery.select) | |
keyframes | AnimatonKeyframe[] | ✓ | Key frame information | |
duration | number | ✓ | Animation duration (in milliseconds) | |
callback | function | The callback function after the animation is completed |
#
AnimatonKeyframeProperty | Type | Default Value | Required | Description |
---|---|---|---|---|
offset | number | Offset of key frame, range [0-1] | ||
ease | string | 'linear' | Animation easing function | |
transformOrigin | string | Same as CSS transform-origin | ||
backgroundColor | string | Same as CSS background-color | ||
bottom | number/string | Same as CSS bottom | ||
height | number/string | Same as CSS height | ||
left | number/string | Same as CSS left | ||
width | number/string | Same as CSS width | ||
opacity | number | Same as CSS opacity | ||
right | number | Same as CSS right | ||
top | number/string | Same as CSS top | ||
matrix | array | Same as CSS transform matrix | ||
matrix3d | array | Same as CSS transform matrix3d | ||
rotate | number | Same as CSS transform rotate | ||
rotate3d | array | Same as CSS transform rotate3d | ||
rotateX | number | Same as CSS transform rotateX | ||
rotateY | number | Same as CSS transform rotateY | ||
rotateZ | number | Same as CSS transform rotateZ | ||
scale | array | Same as CSS transform scale | ||
scale3d | array | Same as CSS transform scale3d | ||
scaleX | number | Same as CSS transform scaleX | ||
scaleY | number | Same as CSS transform scaleY | ||
scaleZ | number | Same as CSS transform scaleZ | ||
skew | array | Same as CSS transform skew | ||
skewX | number | Same as CSS transform skewX | ||
skewY | number | Same as CSS transform skewY | ||
translate | array | Same as CSS transform translate | ||
translate3d | array | Same as CSS transform translate3d | ||
translateX | number | Same as CSS transform translateX | ||
translateY | number | Same as CSS transform translateY | ||
translateZ | number | Same as CSS transform translateZ |
#
Example#
Page.clearAnimationAfter calling the animate API, some style attributes will be added to the node to overwrite the original corresponding styles.
If you need to clear these styles, you can use page.clearAnimation
to clear these properties after all the animations on the node are executed.
#
ParametersProperty | Type | Default Value | Required | Description |
---|---|---|---|---|
selector | string | ✓ | Selector (same as the selector format of SelectorQuery.select) | |
options | object | The attributes that need to be cleared, if not filled in, all are cleared | ||
callback | function | Callback function after clearing is complete |
#
Scroll-driven animationIt is a relatively common scenario to continuously change the progress of the animation according to the scroll position. This type of animation can make people feel that the interface interaction is very coherent and natural, and the experience is better.
Based on the above key frame animation interface, a new parameter of ScrollTimeline
is added to bind scroll elements (currently only supports scroll-view
).
The interface is defined as follows:
#
Structure of objects in ScrollTimelineProperty | Type | Default Value | Required | Description |
---|---|---|---|---|
scrollSource | string | ✓ | Specify the selector of the scroll element (only support scroll-view), which will drive the progress of the animation when the element is scrolled | |
orientation | string | 'vertical' | Specify the direction of scrolling. Valid values are horizontal or vertical | |
startScrollOffset | number | ✓ | Specify the scroll offset to start driving the animation progress, the unit is px | |
endScrollOffset | number | ✓ | Specify the scroll offset to stop driving the animation progress, the unit is px | |
timeRange | number | ✓ | The time length of the start and end scrolling range mapping, this time can be used to match the time in the key frame animation (duration), the unit is ms |