API
Basics
bn.getSystemInfo
Return Values
Object res
Property | Type | Example | Description |
---|---|---|---|
brand | string | "Apple" "Xiaomi" | Device brand |
model | string | Device model | |
pixelRatio | number | Device's pixel ratio | |
screenWidth | number | Screen width in px | |
screenHeight | number | Screen height in px | |
windowWidth | number | Available window width in px | |
windowHeight | number | Available window height in px | |
statusBarHeight | number | Status bar height in px | |
language | string | Language set in App | |
version | string | App version | |
SDKVersion | string | Base library version for the App version | |
system | string | Operating system and version | |
platform | string | "ios" "android" | Client platform |
safeArea | Object | Safe area when the screen is in vertical orientation platform |
res.safeArea
Property | Type | Description |
---|---|---|
left | number | The x-coordinate of the top-left corner of the safe area |
right | number | The x-coordinate of the bottom-right corner of the safe area |
top | number | The y-coordinate of the top-left corner of the safe area |
bottom | number | The y-coordinate of the bottom-right corner of the safe area |
width | number | Safe area width in logical pixels |
height | number | Safe area height in logical pixels |
bn.getLaunchOptionsSync
Obtains the parameters upon Mini Game startup.
Return Values
Object res Startup parameters
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
scene | number | - | - | The scene value for Mini Game startup |
query | Object | - | - | The query parameter for Mini Game startup |
referrerInfo | Object | - | - | The source information. This is returned when a user enters the Mini Program from another Mini Program, Official Account, or app. Otherwise, {} is returned. (see the Note below for details.) |
referrerInfo is composed as follows
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
appId | string | - | - | The appId of the source Mini Program, Official Account, or app. |
extraData | Object | - | - |
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
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
scene | number | - | - | The scene value for Mini Game startup |
query | Object | - | - | The query parameter for Mini Game startup |
referrerInfo | Object | - | - | The source information. This is returned when a user enters the Mini Program from another Mini Program, Official Account, or app. Otherwise, {} is returned. (see the Note below for details) |
referrerInfo is composed as follows
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
appId | string | - | - | The appId of the source Mini Program, Official Account, or app. |
extraData | Object | - | - |
bn.onUnhandledRejection
Listen for unhandled Promise
rejection events.
Parameters
function callback
Callback function for unhandled Promise
rejection event.
function parameters
Object res
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
reason | string | - | Reason for rejection, usually an Error object | |
promise | Promise.<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
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
scene | number | - | - | The scene value for Mini Game startup |
query | Object | - | - | The query parameter for Mini Game startup |
referrerInfo | Object | - | - | The source information. This is returned when a user enters the Mini Program from another Mini Program, Official Account, or app. Otherwise, {} is returned. (see the Note below for details.) |
referrerInfo is composed as follows
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
appId | string | - | - | The appId of the source Mini Program, Official Account, or app. |
extraData | Object | - | - |
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
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
name | string | ✓ | The name of the subpackage, which can be name or root. | |
success | function | The callback event that the subpackage loading succeeds. | ||
fail | function | CThe callback event that the subpackage loading fails. | ||
complete | function | The callback event that the subpackage loading completed (always executed whether the loading succeeds or fails) |
Return 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
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
callback | function | - | ✓ | The callback function. ({ progress }) => void |
Parameters object of callback function
Property | Type | Description |
---|---|---|
progress | number | Subpackage download progress percentage |
totalBytesWritten | number | The length of downloaded data, in bytes |
totalBytesExpectedToWrite | number | The length of data expected to be downloaded, in bytes |
Example
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
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
contextType | string | - | ✓ | drawing context (2d or webgl) |
contextAttributes | Object | - | - | The WebGL context property, which is valid only when contextType is WebGL. |
Object contextAttributes
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
antialias | boolean | false | - | Indicates whether to enable antialiasing. |
preserveDrawingBuffer | boolean | false | - | Indicates whether to preserve drawing buffer when drawing is finished. |
antialiasSamples | number | - | - | 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
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
callback | function | - | ✓ | The callback function. |
Parameters object of callback function
Property | Type | Description |
---|---|---|
touches | Array.<Touch> | List of all current touch points |
changedTouches | Array.<Touch> | List of touch points that triggered this event |
timeStamp | number | Timestamp when the event was triggered |
bn.onTouchMove
listens on the event that the user moves a finger on the screen.
Parameters
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
callback | function | - | ✓ | The callback function. |
Parameters object of callback function
Property | Type | Description |
---|---|---|
touches | Array.<Touch> | List of all current touch points |
changedTouches | Array.<Touch> | List of touch points that triggered this event |
timeStamp | number | Timestamp when the event was triggered |
bn.onTouchEnd
listens on the event that the user releases a finger from the screen.
Parameters
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
callback | function | - | ✓ | The callback function. |
Parameters object of callback function
Property | Type | Description |
---|---|---|
touches | Array.<Touch> | List of all current touch points |
changedTouches | Array.<Touch> | List of touch points that triggered this event |
timeStamp | number | Timestamp when the event was triggered |
bn.onTouchCancel
listens on the event that the user cancels a touch event.
Parameters
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
callback | function | - | ✓ | The callback function. |
Parameters object of callback function
Property | Type | Description |
---|---|---|
touches | Array.<Touch> | List of all current touch points |
changedTouches | Array.<Touch> | List of touch points that triggered this event |
timeStamp | number | Timestamp when the event was triggered |
bn.offTouchStart
un-listens on the event that the user starts to touch the screen.
Parameters
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
callback | function | - | ✓ | The callback function. |
bn.offTouchMove
un-listens on the event that the user moves a finger on the screen.
Parameters
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
callback | function | - | ✓ | The callback function. |
bn.offTouchEnd
un-listens on the event that the user releases a finger from the screen.
Parameters
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
callback | function | - | ✓ | The callback function. |
bn.offTouchCancel
un-listens on the event that the user cancels a touch event.
Parameters
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
callback | function | - | ✓ | 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
Property | Type | Description |
---|---|---|
readFile | Function | Read files in local directory. |
var fs = bn.getFileSystemManager() // FileSystemManager
FileSystemManager.readFile
Parameters
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
filePath | string | ✓ | The file path to read. | |
encoding | string | File's character encoding. if not provided, read it in format of ArrayBuffer. | ||
position | number | Read file starting from specific position.If not provided, start from file head.The reading range should be left-closed and right-open, [position, position+length). Valid range: [0, fileLength - 1].Unit: byte. | ||
length | number | Specify the length of file. If not provided, read until the end of file.Valid range: [1, fileLength].Unit: byte. |
- About filePath: filePath should starts from root directory of source code bundle.Only supports absolute path like
/a/b
ora/b
.Files with extensions ofjs,json,bxss,bxm
will be transformed into other files after compilation, so they are not expected to be accessible. - Valid value of encoding: utf-8, utf8
Response
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
data | string or ArrayBuffer | ✓ | File content in string or ArrayBuffer format. |
{
data: string | ArrayBuffer
}
FileSystemManager.readFileSync(filePath, encoding?, position?, length?): data
Parameters
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
filePath | string | ✓ | The file path to read. | |
encoding | string | File's character encoding. if not provided, read it in format of ArrayBuffer. | ||
position | number | Read file starting from specific position.If not provided, start from file head.The reading range should be left-closed and right-open, [position, position+length). Valid range: [0, fileLength - 1].Unit: byte. | ||
length | number | Specify the length of file. If not provided, read until the end of file.Valid range: [1, fileLength].Unit: byte. |
- About filePath: filePath should starts from root directory of source code bundle.Only supports absolute path like
/a/b
ora/b
.Files with extensions ofjs,json,bxss,bxm
will be transformed into other files after compilation, so they are not expected to be accessible. - Valid value of encoding: utf-8, utf8
Return Value
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
data | string or ArrayBuffer | ✓ | File content in string or ArrayBuffer format. |
FileSystemManager.writeFile(options)
Parameters
options
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
filePath | string | ✓ | The file path to write data in. | |
data | string or ArrayBuffer | ✓ | The data to write. | |
encoding | string | utf8 | Character encoding of the file to be written. |
Response
FileSystemManager.writeFileSync(filePath, data, encoding?): void
Parameters
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
filePath | string | ✓ | The file path to write data in. | |
data | string or ArrayBuffer | ✓ | The data to write. | |
encoding | string | utf8 | Character encoding of the file to be written. |
Return Value
FileSystemManager.mkdir(options): void
Parameters
options
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
dirPath | string | ✓ | The directory to create. | |
recursive | boolean | false | Whether to create parent directories recursively before create the specific one. If the parent directories exist, skip this step. For example if dirPath is a/b/c/d and recursive is true, create a at first and then a/b and so on until a/b/c/d |
Response
FileSystemManager.mkdirSync(dirPath, recursive?): void
Parameters
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
dirPath | string | ✓ | The directory to create. | |
recursive | boolean | false | Whether to create parent directories recursively before create the specific one. If the parent directories exist, skip this step. For example if dirPath is a/b/c/d and recursive is true, create a at first and then a/b and so on until a/b/c/d |
Return Value
FileSystemManager.access(options): void
Parameters
options
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
path | string | ✓ | To check whether this file/directory exits. |
Response
FileSystemManager.accessSync(path): void
Parameters
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
path | string | ✓ | To check whether this file/directory exits. |
Return Value
Interface
bn.showToast
Displays the message prompt box.
Parameters
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
title | string | - | ✓ | Prompt content |
icon | string | success | Icon. Available values: success ,loading , none , error | |
duration | number | 1500 | The delay time for a prompt |
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
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
title | string | - | ✓ | Prompt title |
content | string | - | ✓ | Prompt content |
confirmText | string | - | The text of the "OK "button, not more than 4 characters | |
showCancel | boolean | success | Indicates whether to display the "Cancel" button | |
cancelText | string | - | The text of the "Cancel" button, not more than 4 characters |
Return Values
Object res
Property | Type | Description |
---|---|---|
status | boolean | When the value is "true", it indicates that the user tapped the "OK" button. |
bn.showActionSheet
Displays the action sheet.
Parameters
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
alertText | string | - | Alert text | |
itemList | string[] | - | ✓ | The text array of the button, with a length limited to 6 |
itemColor | string | #000000 | The text color of the button |
Return Values
Object res
Property | Type | Description |
---|---|---|
tapIndex | number | The 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
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
count | number | 9 | no | The maximum number of images allowed |
sizeType | Array. | ['original', 'compressed'] | no | The size of the select image |
sourceType | Array. | ['album', 'camera'] | no | The source of the image |
Valid values of object.sizeType
Value | Description |
---|---|
original | Original image |
compressed | Compressed image |
Valid values of object.sourceType
Value | Description |
---|---|
album | Selects an image from the album |
camera | Takes a photo with the camera |
Return Values
Property | Type | Description |
---|---|---|
tempFilePaths | Array. | The list of local temporary file paths to images |
tempFiles | Array.<Object> | The local temporary file list for images |
res.tempFiles is composed as follows
Property | Type | Description |
---|---|---|
path | string | The path to the local temporary file |
size | number | The 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
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
urls | Array.<string> | yes | A list of links to images that need to be previewed. | |
showmenu | boolean | true | no | Displays long press menu |
current | string | urls The first one. | no | Link to currently displayed picture |
referrerPolicy | string | no-referrer/origin | no | origin: Send the full referrer no-referrer: Do not send. |
bn.saveImageToPhotosAlbum
Save the image to the system album.
Parameters
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
filePath | number | no | Image file path, which can be temporary file path or permanent file path (Local path) Network path not supported |
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
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
mixWithOther | boolean | true | Whether to mix with other audio. Set to true, after that, the music in other apps or Binance will not be terminated. | |
obeyMuteSwitch | boolean | true | (iOS only) Whether to follow the mute switch. Set to false, after that, the sound can be played even in silent mode. | |
speakerOn | boolean | true | true Stand for playing on speaker. false Represents handset playback. |
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 referrerno-referrer
: do send with referrer
InnerAudioContext.play()
Plays an audio file.
InnerAudioContext.pause()
Pauses the audio playback. The playback is resumed at the point where it was paused.
InnerAudioContext.stop()
Stops the audio playback. The playback starts from the beginning if the file is played again.
InnerAudioContext.seek(number position)
Jumps to the specific position.
InnerAudioContext.destroy()
Terminates the current instance.
InnerAudioContext.onCanplay(function callback)
Listens on the event that an audio file is ready for playback. A smooth playback is not guaranteed.
InnerAudioContext.offCanplay(function callback)
Un-listens on the event that an audio file is ready for playback.
InnerAudioContext.onPlay(function callback)
Listens on the audio playback event.
InnerAudioContext.offPlay(function callback)
Un-listens on the audio playback event.
InnerAudioContext.onPause(function callback)
Listens on the audio pause event.
InnerAudioContext.offPause(function callback)
Un-listens on the audio pause event.
InnerAudioContext.onStop(function callback)
Listens on the event of stopping audio playback.
InnerAudioContext.offStop(function callback)
Un-listens on the event of stopping audio playback.
InnerAudioContext.onEnded(function callback)
Listens on the event of playing an audio file to the end without interruption.
InnerAudioContext.offEnded(function callback)
Un-listens on the event of playing an audio file to the end without interruption.
InnerAudioContext.onTimeUpdate(function callback)
Listens on the event of updating audio playback progress.
InnerAudioContext.offTimeUpdate(function callback)
Un-listens on the event of updating audio playback progress.
InnerAudioContext.onError(function callback)
Listens on the audio playback error event.
InnerAudioContext.offError(function callback)
Un-listens on the audio playback error event.
InnerAudioContext.onWaiting(function callback)
Listens on the audio loading event. It is triggered when the playback of an audio file stops to load the file due to insufficient data.
InnerAudioContext.offWaiting(function callback)
Un-listens on the audio loading event.
InnerAudioContext.onSeeking(function callback)
Listens on the event of jumping to a specific position in the audio file.
InnerAudioContext.offSeeking(function callback)
Un-listens on the event of jumping to a specific position in the audio file.
InnerAudioContext.onSeeked(function callback)
Listens on the event of finishing the jump to a specific position in the audio file.
InnerAudioContext.offSeeked(function callback)
Un-listens on the event of finishing the jump to a specific position in the audio file.
bn.createVideoContext(id)
Creates the VideoContext object for the video.
Parameters
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
id | string | ✓ | The 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.
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
position | number | ✓ | The position to be jumped to (in sec) |
videoContext.playbackRate(rate)
Sets multi-speed playback.
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
rate | number | ✓ | Indicates the playback speed (0.5x/0.8x/1x/1.25x/1.5x). |
videoContext.requestFullScreen
Enters the full screen.
videoContext.exitFullScreen
Exits the full screen.
videoContext.exitPictureInPicture
Exits the picture in picture mode.
Keyboard
bn.onKeyboardHeightChange(callback function)
Listens on the keyboard height changes
Parameters
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
callback | function | - | ✓ | the callback function |
bn.offKeyboardHeightChange(callback function)
Remove the listener on the keyboard height changes
Parameters
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
callback | function | - | ✓ | 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
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
url | string | - | ✓ | request url |
data | string | - | request params | |
header | object | - | set request header, can't set Referer . default value of content-type is application/json | |
timeout | number | 10000 | timeout of request, unit is millisecond | |
method | string | 'GET' | HTTP request method | |
dataType | string | 'json' | Returned data format | |
responseType | string | 'text' | Response data type | |
success | function | Callback function for successful interface call | ||
fail | function | Callback function for failed interface call | ||
complete | function | The callback function for the end of the interface call |
Available values of object.dataType
Value | Description |
---|---|
'json' | The returned data is JSON. After returning, JSON.parse will be performed on the returned data. |
others | Do not perform JSON.parse on the returned content |
Available values of object.responseType
Value | Description |
---|---|
'text' | The response data is text |
'arraybuffer' | The response data is ArrayBuffer |
Parameters of object.success
callback
Object res
Property | Type | Description |
---|---|---|
data | string/Object/Arraybuffer | Data returned by the developer server |
statusCode | number | The status code of the response. (This will be 200 for a success). |
header | Object | The Header object associated with the response. |
statusText | string | The status message corresponding to the status code. (e.g., OK for 200). |
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
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
callback | function | - | ✓ | 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
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
url | string | - | ✓ | URL to download resources |
header | object | - | Set request header, can't set Referer . default value of content-type is application/json | |
timeout | number | 60000 | timeout of request, unit is millisecond | |
filePath | string | Specify the path where the file is stored after downloading (local path) | ||
success | function | Callback function for successful interface call | ||
fail | function | Callback function for successful interface call | ||
complete | function | The callback function for the end of the interface call |
Parameters of object.success
callback
Object res
Property | Type | Description |
---|---|---|
tempFilePath | string | Temporary file path. It is returned when the filePath to save files is not specified. The downloaded files will be stored in a temporary file path. |
filePath | string | User file path (local path). It will be returned when filePath is passed in, which is consistent with the filePath passed in |
statusCode | number | HTTP status code returned by the developer server |
Return 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
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
callback | function | - | ✓ | The callback function. ({ header: Object }) => void |
downloadTask.offHeadersReceived(callback)
Cancel listening for HTTP Response Header event
downloadTask.onProgressUpdate(callback)
Monitor download progress change events.
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
callback | function | - | ✓ | The callback function. (progress) => void |
Parameters object of callback function
Property | Type | Description |
---|---|---|
progress | number | Download progress percentage |
totalBytesWritten | number | The length of the downloaded data, in Bytes |
totalBytesExpectedToWrite | number | The total length of data expected to be downloaded, in Bytes |
downloadTask.offProgressUpdate(callback)
Cancel listening to download progress change event
bn.uploadFile
Upload local resources to the server. The client initiates an HTTPS POST request, where the content-type
is multipart/form-data
.
Parameters
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
url | string | ✓ | The HTTPS API URL of developer server | |
filePath | string | ✓ | The path of the file resource to be uploaded (local path) | |
name | string | ✓ | The key corresponding to the file, the server can get the file content through this key | |
header | Object | Header of HTTP request, Referer cannot be set in Header | ||
formData | Object | Other additional form data in the HTTP request | ||
timeout | number | 60000 | timeout of request, unit is millisecond | |
success | function | Callback function for successful interface call | ||
fail | function | Callback function for successful interface call | ||
complete | function | The callback function for the end of the interface call |
Parameters of object.success
callback
Object res
Property | Type | Description |
---|---|---|
data | string | Data returned by the developer server |
statusCode | number | HTTP 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
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
callback | function | - | ✓ | The callback function. ({ header: Object }) => void |
uploadTask.offHeadersReceived(callback)
Cancel listening for HTTP Response Header event
uploadTask.onProgressUpdate(callback)
Monitor upload progress change events.
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
callback | function | - | ✓ | The callback function. (progress) => void |
Parameters object of callback function
Property | Type | Description |
---|---|---|
progress | number | The percentage of upload progress |
totalBytesSent | number | The length of the uploaded data, in Bytes |
totalBytesExpectedToSend | number | The total length of data expected to be uploaded, in Bytes |
uploadTask.offProgressUpdate(callback)
Cancel listening to upload progress change event
bn.createBufferURL(buffer): url
create a unique url in memory
payload
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
buffer | ArrayBuffer/TypedArray | - | ✓ | The data to be sent. |
response
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
url | string | ✓ | unique url on native |
bn.revokeBufferURL(url): void
revoke a unique url in memory
payload
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
url | string | ✓ | unique 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
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
url | string | - | ✓ | The wss API URL of developer server |
header | object | - | set request header, can't set Referer . default value of content-type is application/json | |
protocols | string[] | - | Sub-protocol array. |
Return Values
SocketTask
WebSocket task
socketTask.send
Sends data over a WebSocket connection.
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
data | string/ArrayBuffer | - | ✓ | The data to be sent. |
socketTask.close
Disables the WebSocket connection.
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
code | number | 1000 (indicating that the connection is disabled normally) | A numeric value indicates the status code explaining why the connection has been disabled. | |
reason | string | - | A readable string explaining why the connection has been disabled. This string must be a UTF-8-encoded text (not characters) with not more than 123 bytes. |
socketTask.onOpen(callback)
Listens on the event of enabling the WebSocket connection.
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
callback | function | - | ✓ | The callback function. ({ header: Object }) => void |
socketTask.onClose(callback)
Listens on the event of disabling the WebSocket connection.
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
callback | function | - | ✓ | The callback function. () => void |
socketTask.onError(callback)
Listens on the WebSocket error event.
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
callback | function | - | ✓ | The callback function. ({ errMsg: string }) => void |
socketTask.onMessage(callback)
Listens on the event of receiving server messages by WebSocket
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
callback | function | - | ✓ | The callback function. ({ data: string/ArrayBuffer }) => void |
Number of Concurrent Connections
- Up to 5 WebSocket connections can exist at the same time.
Data Caching
bn.getStorageInfo
Gets the information related to the current storage.
Return Values
Object res
Property | Type | Description |
---|---|---|
keys | string[] | All keys in the current storage |
currentSize | number | Current space occupied (in KB) |
limitSize | number | Space size limit (in KB) |
bn.getStorage
Gets the content of the specified key from the local cache
Parameters
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
key | string | ✓ | The specified key in the local cache |
Return Values
Object res
Property | Type | Description |
---|---|---|
data | any | Content 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
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
key | string | ✓ | The specified key in the local cache | |
data | any | ✓ | Contents to be stored can only be native types, dates, and objects that can be serialized via JSON.stringify. |
bn.removeStorage
Removes the specified key from the local cache.
Parameters
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
key | string | ✓ | The 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
Property | Type | Description |
---|---|---|
code | string | The authorization code. |
bn.requestPayment
Initiates a request for payment via Binance Pay.
Parameters
Object payload
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
certSn | string | - | ✓ | API identity key issued by Binance payment system |
merchantId | string | - | ✓ | The merchant account id, issued when merchant been created at Binance. |
timeStamp | string | - | ✓ | timestamp of the sign |
nonceStr | string | - | ✓ | nonceStr for the sign |
package | string | - | ✓ | The value of the prepay_id parameter returned by the unified order placement API |
paySign | string | - | ✓ | Signature. For specific signature schemes, see Binance Pay API Documentation |
Return Values
Object res
Property | Type | Description |
---|---|---|
status | string | 0 : 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
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
data | string | ✓ | Clipboard content |
Return Values
bn.getClipboardData
Get the contents of the system clipboard.
Parameters
Return Values
Object res
Property | Type | Description |
---|---|---|
data | string | Clipboard 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
Property | Type | Description |
---|---|---|
isConnected | boolean | Indicates whether it is connected to the network |
networkType | string | Network type |
Valid values of networkType
Value | Description |
---|---|
wifi | Wi-Fi network |
2g | 2G network |
3g | 3G network |
4g | 4G network |
5g | 5G network |
unknown | Uncommon network types for Android |
none | No network |
Return Values
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
Property | Type | Description |
---|---|---|
networkType | string | Network type |
signalStrength | number | Signal strength, dbm |
errMsg | string | error info |
bn.scanCode
Tun up the client scan code interface for scanning code.
Parameters
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
scanType | Array. | ['qrCode'] | - | Scan code type |
Return Values
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
result | string | - | the content of scanned code | |
scanType | string | - | the type of scanned code |
Object scanType
Value | Description | Version |
---|---|---|
QR_CODE | QR Code | - |
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
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
direction | number | - | Degree of direction faced | |
accuracy | number/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
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
interval | string | normal | - | Monitor the execution frequency of the acceleration data callback function |
Object interval
Value | Description | Version |
---|---|---|
game | The callback frequency for updating the game, in 20ms/second About | - |
ui | Apply to update UI Callback frequency of 60ms/second About | - |
normal | Normal callback frequency, in the 200ms/second About | - |
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
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
x | number | - | X axis | |
y | number | - | - | Y axis |
z | number | - | - | 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
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
interval | string | normal | - | Monitor device direction change callback function execution frequency |
Object interval
Value | Description | Version |
---|---|---|
game | The callback frequency for updating the game, in 20ms/second About | - |
ui | Apply to update UI Callback frequency of 60ms/second About | - |
normal | Normal callback frequency, in the 200ms/second About | - |
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
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
alpha | number | - | - | when Cell phone coordinates X/And and Earth X/And When overlapped, around. With the angle at which the axis rotates is Alpha, with a range value of [0, 2*PI). Turning counterclockwise is positive. |
beta | number | - | - | When the phone coordinates And/With And the Earth And/With When overlapped, around. X The angle at which the axis rotates is beta。 Range values are [-1PI, PI) The top is turned positive towards the Earth's surface. It is also possible to be positive towards the user. |
gamma | number | - | - | When the phone X/With And the Earth X/With When overlapped, around. And The angle at which the axis rotates is gamma。 Range values are [-1PI/2, PI/2)The right side turns positive toward the Earth's surface. |
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
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
interval | string | normal | - | Monitor the execution frequency of the gyro data callback function |
Object interval
Value | Description | Version |
---|---|---|
game | The callback frequency for updating the game, in 20ms/second About | - |
ui | Apply to update UI Callback frequency of 60ms/second About | - |
normal | Normal callback frequency, in the 200ms/second About | - |
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
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
x | number | - | X axis | |
y | number | - | - | Y axis |
z | number | - | - | 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
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
type | string | yes | Vibration 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
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
value | string | - | The device's orientation after change. |
Valid value:
portrait
, device is in a vertical display.landscape
, device is in a horizontal display.With theHOME
button on right of screen.landscapeReverse
, device is in a horizontal display.With theHOME
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
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
KVDataList | Array.<{key: string; value: string}> | ✓ | The list of KV data to be modified |
response
Property | Type | Default Value | Required | Description |
---|
bn.removeUserCloudStorage
Deletes the key data from the hosted data of the user.
payload
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
keyList | Array.<string> | ✓ | The list of keys to be deleted. |
response
Property | Type | Default Value | Required | Description |
---|
bn.getUserCloudStorage
Gets the key data in the hosted data of the current user.
payload
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
keyList | Array.<string> | ✓ | The list of keys to be obtained. |
response
Property | Type | Description |
---|---|---|
KVDataList | Array.<{key: string; value: string}> | The user's hosted KV data list. |
bn.getUserCloudStorageKeys
Gets the keys in the hosted data of the current user.
payload
Property | Type | Default Value | Required | Description |
---|
response
Property | Type | Description |
---|---|---|
keyList | Array.<string> | The list of keys. |
Leaderboard
bn.showLeaderboardPanel
Open the leaderboard panel by api. The game center.
payload
Property | Type | Default Value | Required | Description |
---|---|---|---|---|
leaderboardId | string | ✓ | Id for the leaderboard |
response
Property | Type | Default Value | Required | Description |
---|
Share
bn.showSharePanel
Pop up the sharing panel.
bn.hideShareMenu
Hide the Share button on the current page.