Skip to main content

API

Basics#

mpService.canIUse(schema)#

Determines whether the APIs, callbacks, parameters, and components of the Mini Program are available in the current version.

Parameters#

string 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, and callback.
  • ${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 Values#

Boolean Indicates whether the API is supported in the current version.

Sample code#

mpService.canIUse('openBluetoothAdapter')mpService.canIUse('getSystemInfoSync.return.screenWidth')mpService.canIUse('getSystemInfo.success.screenWidth')mpService.canIUse('showToast.object.image')mpService.canIUse('onCompassChange.callback.direction')mpService.canIUse('request.object.method.GET')
mpService.canIUse('live-player')mpService.canIUse('text.selectable')mpService.canIUse('button.open-type.contact')

mpService.getSystemInfo#

Return Values#

Object res

PropertyTypeExampleDescription
brandstring"Apple" "Xiaomi"Device brand
modelstringDevice model
pixelRationumberDevice's pixel ratio
screenWidthnumberScreen width in px
screenHeightnumberScreen height in px
windowWidthnumberAvailable window width in px
windowHeightnumberAvailable window height in px
statusBarHeightnumberStatus bar height in px
languagestringLanguage set in App
versionstringApp version
SDKVersionstringBase library version for the App version
systemstringOperating system and version
platformstring"ios" "android"Client platform
safeAreaObjectSafe area when the screen is in vertical orientation platform

res.safeArea

PropertyTypeDescription
leftnumberThe x-coordinate of the top-left corner of the safe area
rightnumberThe x-coordinate of the bottom-right corner of the safe area
topnumberThe y-coordinate of the top-left corner of the safe area
bottomnumberThe y-coordinate of the bottom-right corner of the safe area
widthnumberSafe area width in logical pixels
heightnumberSafe area height in logical pixels

mpService.getUpdateManager#

Get the singleton update manager for managing mini program updates.

Return Values#

UpdateManager

The update manager object.

mpService.getLaunchOptionsSync#

Obtains the parameters upon Mini Program startup. The callback parameters are consistent with those of onLaunch.

Return Values#

Object res Startup parameters

PropertyTypeDefault ValueRequiredDescription
pathstring--The path for Mini Program startup
scenenumber--The scene value for Mini Program startup
queryObject--The query parameter for Mini Program startup
referrerInfoObject--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

PropertyTypeDefault ValueRequiredDescription
appIdstring--The appId of the source Mini Program, Official Account, or app.
extraDataObject--

mpService.getEnterOptionsSync#

Gets 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 Values#

Object res Startup parameters

PropertyTypeDefault ValueRequiredDescription
pathstring--The path for Mini Program startup
scenenumber--The scene value for Mini Program startup
queryObject--The query parameter for Mini Program startup
referrerInfoObject--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

PropertyTypeDefault ValueRequiredDescription
appIdstring--The appId of the source Mini Program, Official Account, or app.
extraDataObject--

mpService.onUnhandledRejection#

Listen for unhandled Promise rejection events.

Parameters#

function callback#

Callback function for unhandled Promise rejection event.

function parameters#

Object res

PropertyTypeDefault ValueRequiredDescription
reasonstring-Reason for rejection, usually an Error object
promisePromise.<any>-scene code

Notes#

All unhandledRejection can be captured by this monitor, but only the Error type will trigger an alarm in the background of the applet.

mpService.onThemeChange#

Monitor system theme change events.

Parameters#

function callback#

Callback function for system theme change event.

function parameters#

Object res

PropertyTypeDefault ValueRequiredDescription
themestring-The current theme of the system, the value is light or dark

The legal value of the

PropertyTypeDefault ValueRequiredDescription
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

Notes#

This event will only be triggered when the global configuration "darkmode": true

mpService.onError#

Listens 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 callback#

The callback function for the Mini Program error event.

Parameters#

string error Error message, including stacks.

mpService.onAppShow#

Listens 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 callback#

The callback function for the event that Mini Program is switched to foreground.

Parameters#

Object res

PropertyTypeDefault ValueRequiredDescription
pathstring--The path for Mini Program startup
scenenumber--The scene value for Mini Program startup
queryObject--The query parameter for Mini Program startup
referrerInfoObject--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

PropertyTypeDefault ValueRequiredDescription
appIdstring--The appId of the source Mini Program, Official Account, or app.
extraDataObject--

Notes#

In 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.onAppHide#

Listens 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 callback#

The callback function for the event that Mini Program is switched to background.

mpService.offUnhandledRejection#

Cancel listening for unhandled Promise rejection events.

Parameters#

function callback#

Callback function for unhandled Promise rejection event.

mpService.offThemeChange#

Cancel listening for system theme change events.

Parameters#

function callback#

The callback function for the Mini Program theme change.

mpService.offError#

Un-listens on Mini Program error event.

Parameters#

function callback#

The callback function for the Mini Program error event.

mpService.offAppShow#

Un-listens on the event that Mini Program is switched to foreground.

Parameters#

function callback#

The callback function for the event that Mini Program is switched to foreground.

mpService.offAppHide#

Un-listens on the event that Mini Program is switched to background.

Parameters#

function callback#

The callback function for the event that Mini Program is switched to background.

UpdateManager#

UpdateManager object, used to manage updates, the instance can be obtained through the mpService.getUpdateManager() interface.

Methods#

UpdateManager.applyUpdate#

Force 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.

PropertyTypeDefault ValueRequiredDescription
callbackfunction-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.

PropertyTypeDefault ValueRequiredDescription
callbackfunction-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

PropertyTypeDefault ValueRequiredDescription
callbackfunction-The callback function. () => void
Example#
const updateManager = mpService.getUpdateManager()
updateManager.onCheckForUpdate(function (res) {  // Callback after requesting new version information  console.log(res.hasUpdate)})
updateManager.onUpdateReady(function () {  mpService.showModal({    title: 'Update reminder',    content: 'The new version is ready, do you want to restart the mini-program? ',    success: function (res) {      if (res.confirm) {        // The new version has been downloaded, call applyUpdate to apply the new version and restart        updateManager.applyUpdate()      }    }  })})
updateManager.onUpdateFailed(function () {  // Failed to download the new version})

bn.loadSubpackage(payload)#

For MiniGame.

Triggers subpackage loading.

Parameters#

Object payload

PropertyTypeDefault ValueRequiredDescription
namestringThe name of the subpackage, which can be name or root.
successfunctionThe callback event that the subpackage loading succeeds.
failfunctionCThe callback event that the subpackage loading fails.
completefunctionThe callback event that the subpackage loading completed (always executed whether the loading succeeds or fails)

Return Values#

LoadSubpackageTask

Loads subpackage task instances to obtain the subpackage loading status.

LoadSubpackageTask.onProgressUpdate(function callback)#

Listens on the subpackage loading progress change event.

Parameters#
PropertyTypeDefault ValueRequiredDescription
callbackfunction-The callback function. ({ progress }) => void
Parameters object of callback function#
PropertyTypeDescription
progressnumberSubpackage download progress percentage
totalBytesWrittennumberThe length of downloaded data, in bytes
totalBytesExpectedToWritenumberThe length of data expected to be downloaded, in bytes

Example

const loadTask = bn.loadSubpackage({  name: 'subpackage1', // could be value of name or root  success: function (res) {},  fail: function (res) {},})loadTask.onProgressUpdate(res => {  console.log(res.progress)  console.log(res.totalBytesWritten)  console.log(res.totalBytesExpectedToWrite)})

Routing#

mpService.redirectTo#

Closes the current page and redirects to a page (except for the tabbar page) in the app.

Parameters#

PropertyTypeDefault ValueRequiredDescription
urlstringPath 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.reLaunch#

Closes all pages and opens a page in the app.

Parameters#

PropertyTypeDefault ValueRequiredDescription
urlstringPath 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.navigateTo#

Keeps 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.

Parameters#

Object payload

PropertyTypeDefault ValueRequiredDescription
urlstringurl to navigate
eventsObjectregister callbacks to listen EventChannel

Return Values#

Object res

PropertyTypeDescription
eventChannelEventChannelcommunication channel between opener page and opened page

mpService.switchTab#

Redirects to the tabBar page and closes all non-tabBar pages.

payload

PropertyTypeDefault ValueRequiredDescription
urlstringPath 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.navigateBack#

Closes the current page and returns to the previous page or multi-level page.

Parameters#

PropertyTypeDefault ValueRequiredDescription
deltanumber1The 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.navigateToMiniProgram#

Opens another Mini Program.

payload

PropertyTypeDefault ValueRequiredDescription
appIdstringThe appId of the Mini Program to be opened.
pathstringThe 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.
extraDataobjectThe 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'publishedThe channel of the Mini Program to be opened. It is valid when target="miniProgram".
type'app', 'web', 'webview'appThe type of the Mini Program to be opened. It is valid when target="miniProgram".
revStringThe rev of the Mini Program to be opened. It is valid when target="miniProgram".
mpService.navigateToMiniProgram({  appId: '',  path: 'page/1',  extraData: {    foo: 'bar',  },  envVersion: 'published',  type: 'app',  rev: '006a05ebf14db3e4a8e69cb6bc8b2589',})

mpService.navigateBackMiniProgram#

Returns to the previous Mini Program. It can be called only when the current Mini Program is opened from another Mini Program.

payload

PropertyTypeDefault ValueRequiredDescription
extraDataobjectThe data that needs to be returned to the previous Mini Program. The previous Mini Program can get this data from App.onShow.
mpService.navigateBackMiniProgram({  extraData: {    foo: 'bar',  },})

mpService.exitMiniProgram#

Exit the miniprogram. There must be a click behavior to call successfully.

Framework#

mpService.getApp#

Gets the globally unique App instance of the Mini Program.

Interface#

;() => App

mpService.getCurrentPages#

Gets the current page stack. In the array, the first element is the homepage and the last element is the current page.

Interface#

() => Page[]

Interface#

mpService.showToast#

Displays the message prompt box.

Parameters#

PropertyTypeDefault ValueRequiredDescription
titlestring-Prompt content
iconstringsuccessIcon. Available values: success,loading, none, error
durationnumber1500The delay time for a prompt

mpService.hideToast#

Hides the message prompt box.

mpService.showLoading#

Displays the loading prompt box. mpService.hideLoading must be called to close the prompt box.

mpService.hideLoading#

Hides the loading prompt box.

mpService.showModal#

Displays the modal dialog box.

Parameters#

PropertyTypeDefault ValueRequiredDescription
titlestring-Prompt title
contentstring-Prompt content
confirmTextstring-The text of the "OK "button, not more than 4 characters
showCancelbooleansuccessIndicates whether to display the "Cancel" button
cancelTextstring-The text of the "Cancel" button, not more than 4 characters

Return Values#

Object res

PropertyTypeDescription
statusbooleanWhen the value is "true", it indicates that the user tapped the "OK" button.

mpService.showActionSheet#

Displays the action sheet.

Parameters#

PropertyTypeDefault ValueRequiredDescription
alertTextstring-Alert text
itemListstring[]-The text array of the button, with a length limited to 6
itemColorstring#000000The text color of the button

Return Values#

Object res

PropertyTypeDescription
tapIndexnumberThe sequence number of the button tapped by the user, from top to bottom and starting from 0

mpService.setNavigationBarTitle#

Dynamically sets the title of the current page.

Parameters#

PropertyTypeDefault ValueRequiredDescription
titlestringtitle of the navigation bar

mpService.setTabBarItem#

Dynamically sets the content of a tabBarn item.

Parameters#

PropertyTypeDefault ValueRequiredDescription
indexnumberSpecifies which item of tabBar, starting from the left.
textstringThe text of a button on tab.
iconPathstringThe 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.
selectedIconPathstringThe 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.showTabBar#

Display tabBar.

Parameters#

PropertyTypeDefault ValueRequiredDescription
animationbooleanfalseShow animation effect

mpService.hideTabBar#

Hide tabBar.

Parameters#

PropertyTypeDefault ValueRequiredDescription
animationbooleanfalseShow animation effect

mpService.showTabBarRedDot#

Show red dot on the right top corner of tab bar item.

Parameters#

PropertyTypeDefault ValueRequiredDescription
indexnumber The index of the tab bar item from left. The first one is 0

mpService.hideTabBarRedDot#

Hide red dot of tab bar item.

Parameters#

PropertyTypeDefault ValueRequiredDescription
indexnumber The index of the tab bar item from left. The first one is 0

mpService.pageScrollTo#

Scrolls the screen to the target location

Parameters#

PropertyTypeDefault ValueRequiredDescription
scrollTopnumberNoScrolls the screen to the target location (in px)
durationnumber300NoScrolls the screen to the target location (in px)
selectorstringNoselector
selector syntax#

selector 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.hideHomeButton#

Hide 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.chooseImage#

Selects an image from the local album or takes a photo with the camera.

Parameters#

PropertyTypeDefault ValueRequiredDescription
countnumber9noThe maximum number of images allowed
sizeTypeArray.['original', 'compressed']noThe size of the select image
sourceTypeArray.['album', 'camera']noThe source of the image
Valid values of object.sizeType#
ValueDescription
originalOriginal image
compressedCompressed image
Valid values of object.sourceType#
ValueDescription
albumSelects an image from the album
cameraTakes a photo with the camera

Return Values#

PropertyTypeDescription
tempFilePathsArray.The list of local temporary file paths to images
tempFilesArray.<Object>The local temporary file list for images
res.tempFiles is composed as follows#
PropertyTypeDescription
pathstringThe path to the local temporary file
sizenumberThe size of a local temporary file, in bytes

mpService.previewImage#

Preview the picture in full screen on the new page. Preview the process of the user can save pictures, send to friends and other operations.

Parameters#

PropertyTypeDefault ValueRequiredDescription
urlsArray.<string>yesA list of links to images that need to be previewed.
showmenubooleantruenoDisplays long press menu
currentstringurls The first one.noLink to currently displayed picture
referrerPolicystringno-referrer/originnoorigin: Send the full referrer no-referrer: Do not send.

mpService.saveImageToPhotosAlbum#

Save the image to the system album.

Parameters#

PropertyTypeDefault ValueRequiredDescription
filePathnumbernoImage 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

React.useEffect(() => {  function onAudioInterruptionBegin(e: any) {    console.log(`[Audio] ${id} onAudioInterruptionBegin`, e)  }  function onAudioInterruptionEnd(e: any) {    console.log(`[Audio] ${id} onAudioInterruptionEnd`, e)  }  mpService.onAudioInterruptionBegin(onAudioInterruptionBegin)  mpService.onAudioInterruptionEnd(onAudioInterruptionEnd)
  return () => {    mpService.offAudioInterruptionBegin(onAudioInterruptionBegin)    mpService.offAudioInterruptionEnd(onAudioInterruptionEnd)  }}, [])

mpService.setInnerAudioOption(Object object)#

Set the options of InnerAudioContext. Set to take effect globally for the current Mini Program.

object

PropertyTypeDefault ValueRequiredDescription
mixWithOtherbooleantrueWhether to mix with other audio. Set to true, after that, the music in other apps or Binance will not be terminated.
obeyMuteSwitchbooleantrue(iOS only) Whether to follow the mute switch. Set to false, after that, the sound can be played even in silent mode.
speakerOnbooleantruetrue Stand for playing on speaker. false Represents handset playback.

mpService.createInnerAudioContext()#

Creates the context InnerAudioContext object for an internal audio.

const innerAudioContext = mpService.createInnerAudioContext()innerAudioContext.autoplay = trueinnerAudioContext.src = 'https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3'innerAudioContext.onPlay(() => {  console.log('Start playback')})innerAudioContext.onError(res => {  console.log(res.errMsg)  console.log(res.errCode)})

InnerAudioContext#

string src#

The audio file address which can be used to play the audio file directly.

number startTime#

The position where the playback starts (in sec). It is 0 by default.

boolean autoplay#

Whether to enable auto playback. It is false by default.

boolean loop#

Whether to enable loop playback. It is false by default.

boolean obeyMuteSwitch#

Whether 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 volume#

Specifies the volume, which ranges from 0 to 1. It is 1 by default.

number playbackRate#

Specifies the playbackRate, which ranges from 0.5 to 2. It is 1 by default.

number duration#

The length of the audio file (in sec). It is only returned when a valid src attribute exists (read only).

number currentTime#

The 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 paused#

Whether the playback is paused or stopped (read only).

number buffered#

The 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 referrerPolicy#
  • origin: send request with referrer
  • no-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.

Parameters#

PropertyTypeDefault ValueRequiredDescription
idstringThe video component's ID

Return Values#

VideoContext

videoContext.play#

Plays the video.

videoContext.pause#

Pauses the video.

videoContext.stop#

Stops the video.

videoContext.seek(position)#

Jumps to the specific position.

PropertyTypeDefault ValueRequiredDescription
positionnumberThe position to be jumped to (in sec)
videoContext.playbackRate(rate)#

Sets multi-speed playback.

PropertyTypeDefault ValueRequiredDescription
ratenumberIndicates 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 Component#

Defers some operations until the next time slice. (similar to setTimeout)

mpService.nextTick(function callback)#

Parameters#

PropertyTypeDefault ValueRequiredDescription
callbackfunction-the callback function

Keyboard#

mpService.onKeyboardHeightChange(callback function)#

Listens on the keyboard height changes

Parameters#

PropertyTypeDefault ValueRequiredDescription
callbackfunction-the callback function

mpService.offKeyboardHeightChange(callback function)#

Remove the listener on the keyboard height changes

Parameters#

PropertyTypeDefault ValueRequiredDescription
callbackfunction-the callback function

Sample code#

function callback(res) {  console.log(res.height)}
mpService.onKeyboardHeightChange(callback)mpService.offKeyboardHeightChange(callback)

mpService.hideKeyboard#

Hide keyboard

Sample code#

mpService  .hideKeyboard()  .then(res => {    console.log('hideKeyboard res', res)  })  .catch(error => {    console.log('hideKeyboard error', error)  })

mpService.getSelectedTextRange#

Obtains 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#

mpService  .getSelectedTextRange()  .then(res => {    console.log('getSelectedTextRange res', res.start, res.end)  })  .catch(error => {    console.log('hideKeyboard error', error)  })

Network#

mpService.request#

Initiates an HTTPS request.

Parameters#

PropertyTypeDefault ValueRequiredDescription
urlstring-request url
datastring-request params
headerobject-set request header, can't set Referer. default value of content-type is application/json
timeoutnumber10000timeout of request, unit is millisecond
methodstring'GET'HTTP request method
dataTypestring'json'Returned data format
responseTypestring'text'Response data type
successfunctionCallback function for successful interface call
failfunctionCallback function for failed interface call
completefunctionThe callback function for the end of the interface call
Available values of object.dataType#
ValueDescription
'json'The returned data is JSON. After returning, JSON.parse will be performed on the returned data.
othersDo not perform JSON.parse on the returned content
Available values of object.responseType#
ValueDescription
'text'The response data is text
'arraybuffer'The response data is ArrayBuffer
Parameters of object.success callback#

Object res

PropertyTypeDescription
datastring/Object/ArraybufferData returned by the developer server
statusCodenumberThe status code of the response. (This will be 200 for a success).
headerObjectThe Header object associated with the response.
statusTextstringThe status message corresponding to the status code. (e.g., OK for 200).
Description of data parameter#

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:
encodeURIComponent(k)=encodeURIComponent(v)&encodeURIComponent(k)=encodeURIComponent(v)...
  • 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

encodeURIComponent(k)=encodeURIComponent(v)&encodeURIComponent(k)=encodeURIComponent(v)...

Return Values#

RequestTask

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

PropertyTypeDefault ValueRequiredDescription
callbackfunction-The callback function. ({ header: Object }) => void
requestTask.offHeadersReceived(callback)#

Cancel listening for HTTP Response Header event

mpService.downloadFile#

Downloads 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.

Parameters#

PropertyTypeDefault ValueRequiredDescription
urlstring-URL to download resources
headerobject-Set request header, can't set Referer. default value of content-type is application/json
timeoutnumber60000timeout of request, unit is millisecond
filePathstringSpecify the path where the file is stored after downloading (local path)
successfunctionCallback function for successful interface call
failfunctionCallback function for successful interface call
completefunctionThe callback function for the end of the interface call
Parameters of object.success callback#

Object res

PropertyTypeDescription
tempFilePathstringTemporary 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.
filePathstringUser file path (local path). It will be returned when filePath is passed in, which is consistent with the filePath passed in
statusCodenumberHTTP status code returned by the developer server

Return Values#

DownloadTask

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

PropertyTypeDefault ValueRequiredDescription
callbackfunction-The callback function. ({ header: Object }) => void
downloadTask.offHeadersReceived(callback)#

Cancel listening for HTTP Response Header event

downloadTask.onProgressUpdate(callback)#

Monitor download progress change events.

PropertyTypeDefault ValueRequiredDescription
callbackfunction-The callback function. (progress) => void
Parameters object of callback function#
PropertyTypeDescription
progressnumberDownload progress percentage
totalBytesWrittennumberThe length of the downloaded data, in Bytes
totalBytesExpectedToWritenumberThe total length of data expected to be downloaded, in Bytes
downloadTask.offProgressUpdate(callback)#

Cancel listening to download progress change event

mpService.uploadFile#

Upload local resources to the server. The client initiates an HTTPS POST request, where the content-type is multipart/form-data.

Parameters#

PropertyTypeDefault ValueRequiredDescription
urlstringThe HTTPS API URL of developer server
filePathstringThe path of the file resource to be uploaded (local path)
namestringThe key corresponding to the file, the server can get the file content through this key
headerObjectHeader of HTTP request, Referer cannot be set in Header
formDataObjectOther additional form data in the HTTP request
timeoutnumber60000timeout of request, unit is millisecond
successfunctionCallback function for successful interface call
failfunctionCallback function for successful interface call
completefunctionThe callback function for the end of the interface call
Parameters of object.success callback#

Object res

PropertyTypeDescription
datastringData returned by the developer server
statusCodenumberHTTP status code returned by the developer server

Return Values#

UploadTask

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

PropertyTypeDefault ValueRequiredDescription
callbackfunction-The callback function. ({ header: Object }) => void
uploadTask.offHeadersReceived(callback)#

Cancel listening for HTTP Response Header event

uploadTask.onProgressUpdate(callback)#

Monitor upload progress change events.

PropertyTypeDefault ValueRequiredDescription
callbackfunction-The callback function. (progress) => void
Parameters object of callback function#
PropertyTypeDescription
progressnumberThe percentage of upload progress
totalBytesSentnumberThe length of the uploaded data, in Bytes
totalBytesExpectedToSendnumberThe total length of data expected to be uploaded, in Bytes
uploadTask.offProgressUpdate(callback)#

Cancel listening to upload progress change event

Example#

mpService.chooseImage({  success(res) {    const tempFilePaths = res.tempFilePaths    mpService.uploadFile({      url: 'https://www.example.com/upload',      filePath: tempFilePaths[0],      name: 'file',      formData: {        user: 'test',      },      success(res) {        const data = res.data        //do something      },    })  },})

mpService.createBufferURL(buffer): url#

create a unique url in memory

payload

PropertyTypeDefault ValueRequiredDescription
bufferArrayBuffer/TypedArray-The data to be sent.

response

PropertyTypeDefault ValueRequiredDescription
urlstringunique url on native

mpService.revokeBufferURL(url): void#

revoke a unique url in memory

payload

PropertyTypeDefault ValueRequiredDescription
urlstringunique url on native

example:

const res = await mpService.request<ArrayBuffer>({  url: imageUrl,  responseType: 'arraybuffer',})
// createBufferURL is a sync apiconst url = mpService.createBufferURL(res.data)
// revokempService.revokeBufferURL(url)

mpService.connectSocket#

Creates a WebSocket connection.

Parameters#

PropertyTypeDefault ValueRequiredDescription
urlstring-The wss API URL of developer server
headerobject-set request header, can't set Referer. default value of content-type is application/json
protocolsstring[]-Sub-protocol array.

Return Values#

SocketTask

WebSocket task

socketTask.send#

Sends data over a WebSocket connection.

PropertyTypeDefault ValueRequiredDescription
datastring/ArrayBuffer-The data to be sent.
socketTask.close#

Disables the WebSocket connection.

PropertyTypeDefault ValueRequiredDescription
codenumber1000 (indicating that the connection is disabled normally)A numeric value indicates the status code explaining why the connection has been disabled.
reasonstring-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.

PropertyTypeDefault ValueRequiredDescription
callbackfunction-The callback function. ({ header: Object }) => void
socketTask.onClose(callback)#

Listens on the event of disabling the WebSocket connection.

PropertyTypeDefault ValueRequiredDescription
callbackfunction-The callback function. () => void
socketTask.onError(callback)#

Listens on the WebSocket error event.

PropertyTypeDefault ValueRequiredDescription
callbackfunction-The callback function. ({ errMsg: string }) => void
socketTask.onMessage(callback)#

Listens on the event of receiving server messages by WebSocket

PropertyTypeDefault ValueRequiredDescription
callbackfunction-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.getStorageInfo#

Gets the information related to the current storage.

Return Values#

Object res

PropertyTypeDescription
keysstring[]All keys in the current storage
currentSizenumberCurrent space occupied (in KB)
limitSizenumberSpace size limit (in KB)

mpService.getStorage#

Gets the content of the specified key from the local cache

Parameters#

PropertyTypeDefault ValueRequiredDescription
keystringThe specified key in the local cache

Return Values#

Object res

PropertyTypeDescription
dataanyContent of the key

mpService.setStorage#

Stores 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.

Parameters#

PropertyTypeDefault ValueRequiredDescription
keystringThe specified key in the local cache
dataanyContents to be stored can only be native types, dates, and objects that can be serialized via JSON.stringify.

mpService.removeStorage#

Removes the specified key from the local cache.

Parameters#

PropertyTypeDefault ValueRequiredDescription
keystringThe specified key in the local cache

mpService.clearStorage#

Clears the data cached locally.

File System Manager#

mpService.getFileSystemManager#

Get the file system manager instance which is a singleton. On Android devices, file system api will save file on external storage by default.

Return Values#

Object res

PropertyTypeDescription
readFileFunctionRead files in local directory.
var fs = mpService.getFileSystemManager() // FileSystemManager

FileSystemManager.readFile#

Parameters#

PropertyTypeDefault ValueRequiredDescription
filePathstringThe file path to read.
encodingstringFile's character encoding. if not provided, read it in format of ArrayBuffer.
positionnumberRead 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.
lengthnumberSpecify 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 or a/b.Files with extensions of js,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

PropertyTypeDefault ValueRequiredDescription
datastring or ArrayBufferFile content in string or ArrayBuffer format.
{  data: string | ArrayBuffer}

FileSystemManager.readFileSync(filePath, encoding?, position?, length?): data#

Parameters#

PropertyTypeDefault ValueRequiredDescription
filePathstringThe file path to read.
encodingstringFile's character encoding. if not provided, read it in format of ArrayBuffer.
positionnumberRead 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.
lengthnumberSpecify 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 or a/b.Files with extensions of js,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 Value#

PropertyTypeDefault ValueRequiredDescription
datastring or ArrayBufferFile content in string or ArrayBuffer format.

FileSystemManager.writeFile(options)#

Parameters#

options

PropertyTypeDefault ValueRequiredDescription
filePathstringThe file path to write data in.
datastring or ArrayBufferThe data to write.
encodingstringutf8Character encoding of the file to be written.

Response#

FileSystemManager.writeFileSync(filePath, data, encoding?): void#

Parameters#

PropertyTypeDefault ValueRequiredDescription
filePathstringThe file path to write data in.
datastring or ArrayBufferThe data to write.
encodingstringutf8Character encoding of the file to be written.

Return Value#

FileSystemManager.mkdir(options): void#

Parameters#

options

PropertyTypeDefault ValueRequiredDescription
dirPathstringThe directory to create.
recursivebooleanfalseWhether 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#

Parameters#

PropertyTypeDefault ValueRequiredDescription
dirPathstringThe directory to create.
recursivebooleanfalseWhether 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#

Parameters#

options

PropertyTypeDefault ValueRequiredDescription
pathstringTo check whether this file/directory exits.

Response#

FileSystemManager.accessSync(path): void#

Parameters#

PropertyTypeDefault ValueRequiredDescription
pathstringTo check whether this file/directory exits.

Return Value#

Location#

mpService.openLocation#

Views location using the built-in map.

Parameters#

PropertyTypeDefault ValueRequiredDescription
latitudenumber-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
longitudenumber-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
scalenumber18Scale, ranging from 5 to 18
namestringLocation name
addressstringDetailed address

mpService.getLocation#

Gets current geographic location and speed. The API cannot be called when the user exits the Mini Program.

Parameters#

PropertyTypeDefault ValueRequiredDescription
typestringwgs84GPS coordinates are returned for WGS84, and coordinates used for mpService.openLocation are returned for GCJ-02.
altitudebooleanfalseAltitude 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 Values#

Object res

PropertyTypeDescription
latitudenumberLatitude. The value ranges from -90 to +90, and the negative number means south latitude.
longitudenumberLongitude. The value ranges from -180 to +180, and the negative number means west longitude.
speednumberspeed(unit: m/s)
accuracynumberLocation accuracy
altitudenumberaltitude(unit: m)
verticalAccuracynumberVertical accuracy(unit: m)
horizontalAccuracynumberHorizontal accuracy(unit: m)

mpService.chooseLocation#

Opens the map to select a location.

Parameters#

PropertyTypeDefault ValueRequiredDescription
latitudenumber-Latitude of the target.
longitudenumber-Longitude of the target.

Return Values#

Object res

PropertyTypeDescription
namestringLocation name brand
addressstringDetailed address platform
latitudenumberLatitude, 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.
longitudenumberLongitude, 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.startLocationUpdate#

Start monitoring real-time position changes in the foreground

mpService.stopLocationUpdate#

Stop monitoring real-time location changes

mpService.onLocationChange#

Subscribe the event of real-time location changes,used with mpService.startLocationUpdate.

mpService.offLocationChange#

Unsubscribe the event of real-time location changes.

Example#

import mpService from '@binance/mp-service'
// To get the user's location by api In the mini program, the developer needs to firstly request the user for the authorization.mpService  .authorize({ scope: 'scope.userLocation' })  .then(res => console.log(`[authorize] SUCCESS:`, res))  .catch(err => console.log(`[authorize] ERROR:`, err))
mpService  .getLocation({ type: 'wgs84', altitude: false })  .then(res =>    mpService.showModal({      title: 'getLocation',      content: 'success' + JSON.stringify(res),    }),  )  .catch(error =>    mpService.showModal({      title: 'getLocation',      content: 'fail' + JSON.stringify(error),    }),  )
// Please note: the user may disable the location permissions in the open settings of the mini program. The developer can use getSetting api to have a check.const res = await mpService.getSetting()console.log(res.authSetting['scope.userLocation']) // boolean// and also, the developer can open the permission panel for user to enable the settingawait mpService.openSetting()

Open APIS#

mpService.login#

Gets 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 Values#

Object res

PropertyTypeDescription
codestringThe authorization code.

mpService.getUserProfile#

Get user information.

Return Values#

Object res

PropertyTypeDescription
userInfoObjectUser information object.

Object userInfo

PropertyTypeDescription
nickNamestringUser nickname
avatarUrlstringUser profile picture URL

mpService.isLoggedIn#

check whether the user is logged in or not

Return Values#

PropertyTypeDescription
resultboolwhether the user is logged in or not

mpService.requestPayment#

Initiates a request for payment via Binance Pay.

Parameters#

Object payload

PropertyTypeDefault ValueRequiredDescription
certSnstring-API identity key issued by Binance payment system
merchantIdstring-The merchant account id, issued when merchant been created at Binance.
timeStampstring-timestamp of the sign
nonceStrstring-nonceStr for the sign
packagestring-The value of the prepay_id parameter returned by the unified order placement API
paySignstring-Signature. For specific signature schemes, see Binance Pay API Documentation

Return Values#

Object res

PropertyTypeDescription
statusstring0 : pay success
others : pay failed

Notes the response is a string, not a number.

example:

mpService  .requestPayment({    certSn: '',    merchantId: '',    timeStamp: '',    nonceStr: '',    package: '',    paySign: '', // signature of the parameters  })  .then(res => {    if (res.status === '0') {      // success    }  })

mpService.getPerformance#

Gets the performance information

Return Values#

Performance

performance.getEntries#

Get all current performance information.

Return Entry[]

Entry property

PropertyTypeDescription
entryTypenavigation, render, scripttype of entry
namestringname of entry
startTimenumberstart time of entry
durationnumbertotal time of entry
pathstringpath
navigationStartnumberthe real time of navigation
navigationTypestringtype of navigation
entryTypeDescription
navigationappLaunch: time of app launch. route: performance of routing
renderfirstRender: first render time
scriptevaluateScript: inject script time

Example

const performance = mpService.getPerformance()const entries = performance.getEntries()
[  {    entryType: 'navigation',    name: 'appLaunch',    navigationType: 'appLaunch',    startTime: 1618467220999,    duration: 434,  },
  // 1. entryPage  {    entryType: 'script',    name: 'evaluateScript',    path: 'pages/component/index',    startTime: 1618467221374,    duration: 5,  },  {    entryType: 'render',    name: 'firstRender',    path: 'pages/component/index',    startTime: 1618467221379,    duration: 73,  },
  // 2. navigateTo to "pages/component/pages/view/view"  {    entryType: 'navigation',    name: 'route',    navigationType: 'navigateTo',    navigationStart: 1618467224916,    path: 'pages/component/pages/view/view',    startTime: 1618467224906,    duration: 312,  },  {    entryType: 'script',    name: 'evaluateScript',    path: 'pages/component/pages/view/view',    startTime: 1618467225218,    duration: 5,  },  {    entryType: 'render',    name: 'firstRender',    path: 'pages/component/pages/view/view',    startTime: 1618467225223,    duration: 16,  },
  // 3. switchTab to "pages/API/index"  {    entryType: 'navigation',    name: 'route',    navigationType: 'switchTab',    navigationStart: 1618467227064,    path: 'pages/API/index',    startTime: 1618467227062,    duration: 303,  },  {    entryType: 'script',    name: 'evaluateScript',    path: 'pages/API/index',    startTime: 1618467227365,    duration: 7,  },  {    entryType: 'render',    name: 'firstRender',    path: 'pages/API/index',    startTime: 1618467227372,    duration: 16,  },]

mpService.getWeb3Provider#

Get web3 provider of DWallet.

https://docs.metamask.io/guide/ethereum-provider.html

Return Values#

Object Web3Provider

PropertyTypeDescription
requestFunctiondocs
onFunctiondocs

Example

const web3Provider = mpService.getWeb3Provider()
// requesttry {  const result1 = await web3Provider.request({    method: 'eth_accounts',  })  const result2 = await web3Provider.request({    method: 'eth_requestAccounts',  })  const result3 = await web3Provider.request({    method: 'eth_sendTransaction',    params,  })  // The result varies by RPC method.  // For example, this method will return a transaction hash hexadecimal string on success.} catch (error) {  // If the request fails, the Promise will reject with an error.}
// eventsweb3Provider.on('accountsChanged', accounts => {  // Handle the new accounts, or lack thereof.  // "accounts" will always be an array, but it can be empty.})
web3Provider.on('chainChanged', chainId => {  // Handle the new chain.})

mpService.authCapture#

AuthCapture 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.

Parameters#

PropertyTypeDefault ValueRequiredDescription
certSnstring-API identity key issued by Binance payment system
merchantIdstring-The merchant account id, issued when merchant been created at Binance.
noncestrstring-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
cashierIdstring-the cashierId got from generateCashierUrl API
timeStampstring-UnixTimestamp in millis that the requests send, guarantee the machine time is sync with the network
paySignstring-A signature generated according to a certain logic.

Return Values#

Object res

PropertyTypeDescription
statusstring"SUCCESS" or "FAIL"。"0" for success
const { status } = await mpService.authCapture({  certSn: string,  merchantId: string,  noncestr: string,  cashierId: string,  timeStamp: string,  paySign: string,})

Device#

mpService.setClipboardData#

Set the contents of the system clipboard.

Parameters#

PropertyTypeDefault ValueRequiredDescription
datastringClipboard content

Return Values#

mpService.getClipboardData#

Get the contents of the system clipboard.

Parameters#

Return Values#

Object res

PropertyTypeDescription
datastringClipboard content

mpService.onNetworkStatusChange#

Listens on the network status change event.

Parameters#

function callback#

The callback function for the network status change event.

Parameters#

Object res

PropertyTypeDescription
isConnectedbooleanIndicates whether it is connected to the network
networkTypestringNetwork type

Valid values of networkType

ValueDescription
wifiWi-Fi network
2g2G network
3g3G network
4g4G network
5g5G network
unknownUncommon network types for Android
noneNo network

Return Values#

mpService.offNetworkStatusChange#

Un-listens on Mini Program network status change event.

Parameters#

function callback#

Cancel the callback function for the network status change event.

mpService.getNetworkType#

Gets the network type.

Parameters#

Return Values#

Object res

PropertyTypeDescription
networkTypestringNetwork type
signalStrengthnumberSignal strength, dbm
errMsgstringerror info

mpService.scanCode#

Tun up the client scan code interface for scanning code.

Parameters#

PropertyTypeDefault ValueRequiredDescription
scanTypeArray.['qrCode']-Scan code type

Return Values#

PropertyTypeDefault ValueRequiredDescription
resultstring-the content of scanned code
scanTypestring-the type of scanned code

Object scanType

ValueDescriptionVersion
QR_CODEQR Code-

mpService.startCompass#

Start monitoring compass data.

mpService.stopCompass#

Stop listening to compass data.

mpService.onCompassChange#

Monitor compass data changes. Frequency: 5 second/Seconds, the interface will automatically start listening after the call, you can use the mpService.stopCompass Stop listening.

parameter#

function callback Callback function for compass data change events

Return Values#

function callback Callback function for compass data change events

PropertyTypeDefault ValueRequiredDescription
directionnumber-Degree of direction faced
accuracynumber/string-accuracy

mpService.offCompassChange#

Cancel listening compass data change event, the parameter is empty, then cancel all the event listening.

parameter#

function callback

Callback function for compass data change events

mpService.startAccelerometer#

Start monitoring the acceleration data.

Parameters#

PropertyTypeDefault ValueRequiredDescription
intervalstringnormal-Monitor the execution frequency of the acceleration data callback function

Object interval

ValueDescriptionVersion
gameThe callback frequency for updating the game, in 20ms/second About-
uiApply to update UI Callback frequency of 60ms/second About-
normalNormal callback frequency, in the 200ms/second About-

mpService.stopAccelerometer#

Stop listening for acceleration data.

mpService.onAccelerometerChange#

Listen for acceleration data events. Frequency basis mpService.startAccelerometer() of interval Parameters, Interface calls automatically start listening

parameter#

function callback

Acceleration Data Event Callback Function

Return Values#

PropertyTypeDefault ValueRequiredDescription
xnumber-X axis
ynumber--Y axis
znumber--Z axis

mpService.offAccelerometerChange#

Cancel monitoring of acceleration data events. If the parameter is null, cancel all event monitoring.

parameter#

function callback

Acceleration Data Event Callback Function

mpService.startDeviceMotionListening#

Start listening for changes in device orientation.

Parameters#

PropertyTypeDefault ValueRequiredDescription
intervalstringnormal-Monitor device direction change callback function execution frequency

Object interval

ValueDescriptionVersion
gameThe callback frequency for updating the game, in 20ms/second About-
uiApply to update UI Callback frequency of 60ms/second About-
normalNormal callback frequency, in the 200ms/second About-

mpService.stopDeviceMotionListening#

Stop listening for changes in device direction.

mpService.onDeviceMotionChange#

Listen for device direction change events. Frequency basis mpService.startDeviceMotionListening() of interval Parameters. Can be used mpService.stopDeviceMotionListening() Stop listening.

parameter#

function callback

Callback function for device orientation change event

Return Values#

PropertyTypeDefault ValueRequiredDescription
alphanumber--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.
betanumber--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.
gammanumber--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.offDeviceMotionChange#

Cancels listening device direction change event, parameter is null, then cancels all event monitoring.

parameter#

function callback

Callback function for device orientation change event

mpService.startGyroscope#

Start monitoring the gyroscope data.

Parameters#

PropertyTypeDefault ValueRequiredDescription
intervalstringnormal-Monitor the execution frequency of the gyro data callback function

Object interval

ValueDescriptionVersion
gameThe callback frequency for updating the game, in 20ms/second About-
uiApply to update UI Callback frequency of 60ms/second About-
normalNormal callback frequency, in the 200ms/second About-

mpService.stopGyroscope#

Stop monitoring the gyroscope data.

mpService.onGyroscopeChange#

Monitor gyro data change events. Frequency basis mpService.startGyroscope() of interval Parameters. Can be used mpService.stopGyroscope() Stop listening.

parameter#

function callback

A callback function for gyro data change events

Return Values#

PropertyTypeDefault ValueRequiredDescription
xnumber-X axis
ynumber--Y axis
znumber--Z axis

mpService.offDeviceMotionChange#

Unlisten for gyro data change events.

parameter#

function callback

A callback function for gyro data change events

mpService.onMemoryWarning#

Listens 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.

parameter#

function callback

Callback function for out-of-memory warning event

Return Values#

PropertyTypeDefault ValueRequiredDescription
levelnumber-Memory alert level, only Android There is, corresponding to the system macro definition

level Legal value

valueIntroductions Minimum
5TRIM_MEMORY_RUNNING_MODERATE
10TRIM_MEMORY_RUNNING_LOW
15TRIM_MEMORY_RUNNING_CRITICAL

mpService.offMemoryWarning#

Cancels listening for out-of-memory warning events.

parameter#

function callback

Callback function for out-of-memory warning event

mpService.vibrateShort#

Make the mobile phone vibrate for a short time (15 ms). Only in iPhone 7 / 7 More Above and Android Model entry into force.

Parameters#

PropertyTypeDefault ValueRequiredDescription
typestringyesVibration intensity type, valid values are: heavy, medium, light

mpService.vibrateLong#

Make the phone vibrate for a longer time (400 ms)

Open Data#

bn.setUserCloudStorage#

Writes data to the user's hosted data. Multiple sets of KV data can be written at a time.

payload

PropertyTypeDefault ValueRequiredDescription
KVDataListArray.<{key: string; value: string}>The list of KV data to be modified

response

PropertyTypeDefault ValueRequiredDescription

bn.removeUserCloudStorage#

Deletes the key data from the hosted data of the user.

payload

PropertyTypeDefault ValueRequiredDescription
keyListArray.<string>The list of keys to be deleted.

response

PropertyTypeDefault ValueRequiredDescription

bn.getUserCloudStorage#

Gets the key data in the hosted data of the current user.

payload

PropertyTypeDefault ValueRequiredDescription
keyListArray.<string>The list of keys to be obtained.

response

PropertyTypeDescription
KVDataListArray.<{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

PropertyTypeDefault ValueRequiredDescription

response

PropertyTypeDescription
keyListArray.<string>The list of keys.

Leaderboard#

bn.showLeaderboardPanel#

Open the leaderboard panel by api. The game center.

payload

PropertyTypeDefault ValueRequiredDescription
leaderboardIdstringId for the leaderboard

response

PropertyTypeDefault ValueRequiredDescription

Share#

bn.showSharePanel#

Pop up the sharing panel.

bn.hideShareMenu#

Hide the Share button on the current page.

Animation#

Page.animate#

In the page or custom component, when you need to perform key frame animation, you can use Page.animate interface:

page.animate(selector, keyframes, duration, callback)

Parameters#

PropertyTypeDefault ValueRequiredDescription
selectorstringSelector (same as the selector format of SelectorQuery.select)
keyframesAnimatonKeyframe[]Key frame information
durationnumberAnimation duration (in milliseconds)
callbackfunctionThe callback function after the animation is completed

AnimatonKeyframe#

PropertyTypeDefault ValueRequiredDescription
offsetnumberOffset of key frame, range [0-1]
easestring'linear'Animation easing function
transformOriginstringSame as CSS transform-origin
backgroundColorstringSame as CSS background-color
bottomnumber/stringSame as CSS bottom
heightnumber/stringSame as CSS height
leftnumber/stringSame as CSS left
widthnumber/stringSame as CSS width
opacitynumberSame as CSS opacity
rightnumberSame as CSS right
topnumber/stringSame as CSS top
matrixarraySame as CSS transform matrix
matrix3darraySame as CSS transform matrix3d
rotatenumberSame as CSS transform rotate
rotate3darraySame as CSS transform rotate3d
rotateXnumberSame as CSS transform rotateX
rotateYnumberSame as CSS transform rotateY
rotateZnumberSame as CSS transform rotateZ
scalearraySame as CSS transform scale
scale3darraySame as CSS transform scale3d
scaleXnumberSame as CSS transform scaleX
scaleYnumberSame as CSS transform scaleY
scaleZnumberSame as CSS transform scaleZ
skewarraySame as CSS transform skew
skewXnumberSame as CSS transform skewX
skewYnumberSame as CSS transform skewY
translatearraySame as CSS transform translate
translate3darraySame as CSS transform translate3d
translateXnumberSame as CSS transform translateX
translateYnumberSame as CSS transform translateY
translateZnumberSame as CSS transform translateZ

Example#

const pages = getCurrentPages()const currentPage = pages[pages.length - 1]currentPage.animate(  '#container',  [    { opacity: 1.0, rotate: 0, backgroundColor: '#FF0000' },    { opacity: 0.5, rotate: 45, backgroundColor: '#00FF00' },    { opacity: 0.0, rotate: 90, backgroundColor: '#FF0000' },  ],  5000,  function () {    currentPage.clearAnimation('#container', { opacity: true, rotate: true }, function () {      console.log('Cleared the opacity and rotate attributes on #container')    })  },)
currentPage.animate(  '.block',  [    { scale: [1, 1], rotate: 0, ease: 'ease-out' },    { scale: [1.5, 1.5], rotate: 45, ease: 'ease-in', offset: 0.9 },    { scale: [2, 2], rotate: 90 },  ],  5000,  function () {    currentPage.clearAnimation('.block', function () {      console.log('Cleared all animation properties on .block ')    })  },)

Page.clearAnimation#

After 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.

page.clearAnimation(selector, options, callback)

Parameters#

PropertyTypeDefault ValueRequiredDescription
selectorstringSelector (same as the selector format of SelectorQuery.select)
optionsobjectThe attributes that need to be cleared, if not filled in, all are cleared
callbackfunctionCallback function after clearing is complete

Scroll-driven animation#

It 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:

page.animate(selector, keyframes, duration, ScrollTimeline)

Structure of objects in ScrollTimeline#

PropertyTypeDefault ValueRequiredDescription
scrollSourcestringSpecify the selector of the scroll element (only support scroll-view), which will drive the progress of the animation when the element is scrolled
orientationstring'vertical'Specify the direction of scrolling. Valid values are horizontal or vertical
startScrollOffsetnumberSpecify the scroll offset to start driving the animation progress, the unit is px
endScrollOffsetnumberSpecify the scroll offset to stop driving the animation progress, the unit is px
timeRangenumberThe 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

Example#

const pages = getCurrentPages()const currentPage = pages[pages.length - 1]currentPage.animate(  '.avatar',  [    {      borderRadius: '0',      borderColor: 'red',      transform: 'scale(1) translateY(-20px)',      offset: 0,    },    {      borderRadius: '25%',      borderColor: 'blue',      transform: 'scale(.65) translateY(-20px)',      offset: 0.5,    },    {      borderRadius: '50%',      borderColor: 'blue',      transform: `scale(.3) translateY(-20px)`,      offset: 1,    },  ],  2000,  {    scrollSource: '#scroller',    timeRange: 2000,    startScrollOffset: 0,    endScrollOffset: 85,  },)
currentPage.animate(  '.search_input',  [    {      opacity: '0',      width: '0%',    },    {      opacity: '1',      width: '100%',    },  ],  1000,  {    scrollSource: '#scroller',    timeRange: 1000,    startScrollOffset: 120,    endScrollOffset: 252,  },)