Skip to main content

API

Basics

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

bn.getLaunchOptionsSync

Obtains the parameters upon Mini Game startup.

Return Values

Object res Startup parameters

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

bn.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 bn.getLaunchOptionsSync; If the current is a hot start, the return value is the same as bn.onShow.

Return Values

Object res Startup parameters

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

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

bn.onError

Listens on the Mini Game error event. This event is triggered as a result of script error or failed API call.

Parameters

function callback

The callback function for the Mini Game error event.

Parameters

string error Error message, including stacks.

bn.onShow

Listens on the event that Mini Game is switched to foreground.

Parameters

function callback

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

Parameters

Object res

PropertyTypeDefault ValueRequiredDescription
scenenumber--The scene value for Mini Game startup
queryObject--The query parameter for Mini Game 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.

bn.offHide

Listens on the event that Mini Game is switched to background.

Parameters

function callback

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

bn.offUnhandledRejection

Cancel listening for unhandled Promise rejection events.

Parameters

function callback

Callback function for unhandled Promise rejection event.

bn.offError

Un-listens on Mini Game error event.

Parameters

function callback

The callback function for the Mini Game error event.

bn.offShow

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

Parameters

function callback

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

bn.offHide

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

Parameters

function callback

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

bn.loadSubpackage(payload)

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)
})

Rendering

bn.createCanvas

Creates a canvas object. When this API is called the first time, an on-screen canvas is created, and thereafter, off-screen canvases are created.

Return Values

Canvas

The canvas object.

Canvas.getContext(string contextType, Object contextAttributes)

Gets the drawing context of a canvas object.

Parameters
PropertyTypeDefault ValueRequiredDescription
contextTypestring-drawing context (2d or webgl)
contextAttributesObject--The WebGL context property, which is valid only when contextType is WebGL.

Object contextAttributes

PropertyTypeDefault ValueRequiredDescription
antialiasbooleanfalse-Indicates whether to enable antialiasing.
preserveDrawingBufferbooleanfalse-Indicates whether to preserve drawing buffer when drawing is finished.
antialiasSamplesnumber--The number of antialiasing samples.
Return Values

RenderingContext

The drawing context.

bn.createImage

Creates an image object.

Return Values

Image

The image object.

string src

The image URL.

number width

The actual width of the image.

number height

The actual height of the image.

function onload

The callback function triggered after the image is loaded.

function onerror

The callback function triggered after an error occurred during image loading.

Touch Events

bn.onTouchStart

listens on the event that the user starts to touch the screen.

Parameters

PropertyTypeDefault ValueRequiredDescription
callbackfunction-The callback function.
Parameters object of callback function
PropertyTypeDescription
touchesArray.<Touch>List of all current touch points
changedTouchesArray.<Touch>List of touch points that triggered this event
timeStampnumberTimestamp when the event was triggered

bn.onTouchMove

listens on the event that the user moves a finger on the screen.

Parameters

PropertyTypeDefault ValueRequiredDescription
callbackfunction-The callback function.
Parameters object of callback function
PropertyTypeDescription
touchesArray.<Touch>List of all current touch points
changedTouchesArray.<Touch>List of touch points that triggered this event
timeStampnumberTimestamp when the event was triggered

bn.onTouchEnd

listens on the event that the user releases a finger from the screen.

Parameters

PropertyTypeDefault ValueRequiredDescription
callbackfunction-The callback function.
Parameters object of callback function
PropertyTypeDescription
touchesArray.<Touch>List of all current touch points
changedTouchesArray.<Touch>List of touch points that triggered this event
timeStampnumberTimestamp when the event was triggered

bn.onTouchCancel

listens on the event that the user cancels a touch event.

Parameters

PropertyTypeDefault ValueRequiredDescription
callbackfunction-The callback function.
Parameters object of callback function
PropertyTypeDescription
touchesArray.<Touch>List of all current touch points
changedTouchesArray.<Touch>List of touch points that triggered this event
timeStampnumberTimestamp when the event was triggered

bn.offTouchStart

un-listens on the event that the user starts to touch the screen.

Parameters

PropertyTypeDefault ValueRequiredDescription
callbackfunction-The callback function.

bn.offTouchMove

un-listens on the event that the user moves a finger on the screen.

Parameters

PropertyTypeDefault ValueRequiredDescription
callbackfunction-The callback function.

bn.offTouchEnd

un-listens on the event that the user releases a finger from the screen.

Parameters

PropertyTypeDefault ValueRequiredDescription
callbackfunction-The callback function.

bn.offTouchCancel

un-listens on the event that the user cancels a touch event.

Parameters

PropertyTypeDefault ValueRequiredDescription
callbackfunction-The callback function.

Touch

Touch object indicates a touch point on a touch-controlled device. Usually refers to an operation by a finger or pen on a touchscreen device or touchpad.

number identifier

Touch object's unique identifier (read-only). In the whole process of a touch action (finger touch) moving on the screen, this identifier does not change. Can be used to determine whether it is the same touch that is being tracked.

number pageX

The X coordinate of the touch point relative to the left edge of the screen.

number pageY

The Y coordinate of the touch point relative to the top edge of the screen.

number clientX

The X coordinate of the touch point relative to the left edge of the viewport.

number clientY

The Y coordinate of the touch point relative to the top edge of the viewport.

File System Manager

bn.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 = bn.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

Interface

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

bn.hideToast

Hides the message prompt box.

bn.showLoading

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

bn.hideLoading

Hides the loading prompt box.

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

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

Media

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

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

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

bn.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 Game will pause.

bn.onAudioInterruptionEnd(function callback)

Listen for audio interrupt end event. Received. onAudioInterruptionBegin After the event, all audio in the Mini Game will be suspended and can be played again after receiving this event.

bn.offAudioInterruptionBegin(function callback)

Cancel listening audio is interrupted due to system occupation Start event

bn.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)
}
bn.onAudioInterruptionBegin(onAudioInterruptionBegin)
bn.onAudioInterruptionEnd(onAudioInterruptionEnd)

return () => {
bn.offAudioInterruptionBegin(onAudioInterruptionBegin)
bn.offAudioInterruptionEnd(onAudioInterruptionEnd)
}
}, [])

bn.setInnerAudioOption(Object object)

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

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.

bn.createInnerAudioContext()

Creates the context InnerAudioContext object for an internal audio.

const innerAudioContext = bn.createInnerAudioContext()
innerAudioContext.autoplay = true
innerAudioContext.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.

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

Keyboard

bn.onKeyboardHeightChange(callback function)

Listens on the keyboard height changes

Parameters

PropertyTypeDefault ValueRequiredDescription
callbackfunction-the callback function

bn.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)
}

bn.onKeyboardHeightChange(callback)
bn.offKeyboardHeightChange(callback)

bn.hideKeyboard

Hide keyboard

Sample code

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

Network

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

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

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

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

bn.revokeBufferURL(url): void

revoke a unique url in memory

payload

PropertyTypeDefault ValueRequiredDescription
urlstringunique url on native

example:

const res = await bn.request<ArrayBuffer>({
url: imageUrl,
responseType: 'arraybuffer',
})

// createBufferURL is a sync api
const url = bn.createBufferURL(res.data)

// revoke
bn.revokeBufferURL(url)

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

bn.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)

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

bn.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 Game, 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.

bn.removeStorage

Removes the specified key from the local cache.

Parameters

PropertyTypeDefault ValueRequiredDescription
keystringThe specified key in the local cache

bn.clearStorage

Clears the data cached locally.

Open APIS

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

bn.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:

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

Device

bn.setClipboardData

Set the contents of the system clipboard.

Parameters

PropertyTypeDefault ValueRequiredDescription
datastringClipboard content

Return Values

bn.getClipboardData

Get the contents of the system clipboard.

Parameters

Return Values

Object res

PropertyTypeDescription
datastringClipboard content

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

bn.offNetworkStatusChange

Un-listens on Mini Game network status change event.

Parameters

function callback

Cancel the callback function for the network status change event.

bn.getNetworkType

Gets the network type.

Parameters

Return Values

Object res

PropertyTypeDescription
networkTypestringNetwork type
signalStrengthnumberSignal strength, dbm
errMsgstringerror info

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

bn.startCompass

Start monitoring compass data.

bn.stopCompass

Stop listening to compass data.

bn.onCompassChange

Monitor compass data changes. Frequency: 5 second/Seconds, the interface will automatically start listening after the call, you can use the bn.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

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

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

bn.stopAccelerometer

Stop listening for acceleration data.

bn.onAccelerometerChange

Listen for acceleration data events. Frequency basis bn.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

bn.offAccelerometerChange

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

parameter

function callback

Acceleration Data Event Callback Function

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

bn.stopDeviceMotionListening

Stop listening for changes in device direction.

bn.onDeviceMotionChange

Listen for device direction change events. Frequency basis bn.startDeviceMotionListening() of interval Parameters. Can be used bn.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.

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

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

bn.stopGyroscope

Stop monitoring the gyroscope data.

bn.onGyroscopeChange

Monitor gyro data change events. Frequency basis bn.startGyroscope() of interval Parameters. Can be used bn.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

bn.offDeviceMotionChange

Unlisten for gyro data change events.

parameter

function callback

A callback function for gyro data change events

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

bn.vibrateLong

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

bn.onDeviceOrientationChange(callback)

Listen on device's orientation changing events.

parameter

function callback

A callback function for orientation changing events

Return Values

PropertyTypeDefault ValueRequiredDescription
valuestring-The device's orientation after change.

Valid value:

  • portrait, device is in a vertical display.
  • landscape, device is in a horizontal display.With the HOME button on right of screen.
  • landscapeReverse, device is in a horizontal display.With the HOME button on left of screen.

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.