This page is translated by Cloud Translation API
Switch to Chinese
This page is translated by Cloud Translation API
Switch to Chinese

The js API of Mini App consists of two parts: the standard ECMAScript js API and the uni extension API.

The js of standard ECMAScript is only the most basic js. The browser extends window, document, navigator and other objects based on it.

Mini App extends the uni object based on ECMAScript.

# Difference between standard js and browser js

The js code of Mini App, the web side runs in the browser. For the non-web side , the Android platform runs in the v8 engine, the iOS platform runs in the jscore engine that comes with iOS, and neither runs in the browser or webview.

On the non-web side, although it does not support the js API of browsers such as window, document, and navigator, it also supports standard ECMAScript.

Be careful not to equate in-browser js with standard js.

Therefore, the web side of Mini App also supports standard js, supports syntax such as if and for, and supports variable types such as strings, numbers, time, Boolean values, arrays, custom objects, and various processing methods. It's just that browser-specific objects such as window, document, and navigator are not supported.

# Instruction

  • The APIs beginning with uni.on are used as API interfaces to listen to certain events and accept a CALLBACK function as a parameter. When that event is triggered, the CALLBACK function is called.
  • Unless otherwise specified, other API interfaces accept an OBJECT as a parameter.
  • In the OBJECT, success, fail and complete can be specified in the reception of the interface call result.
  • Async APIs will return the errMsg field, synchronous APIs will not. For example: getSystemInfoSync will not have errMsg in the returned result.

# API Promisify

  1. Specific strategy of API Promisify:

    • For the asynchronous method, if no callback parameter such as success, fail or complete is passed in, the data will be returned as Promise. E.g.: uni.getImageInfo()

    • For asynchronous method with return object, at least one callback parameter of success, fail or complete should be passed in to obtain the return object. E.g.:

       // Normal use
       const task = uni.connectSocket(
        success(res){
         console.log(res)
        }
       )
      
       // Promise
       uni.connectSocket().then(res => {
         // Here is the res of the success callback in normal use
         // uni.connectSocket() will return the task object when used normally. If you want to get the task, don't use Promise
         console.log(res)
       })
      
  2. API that does not proceed Promisify:

    • Synchronization method (ended with sync). E.g.: uni.getSystemInfoSync()
    • Method beginning with create. E.g.: uni.createMapContext()
    • Method ending with manager. E.g.: uni.getBackgroundAudioManager()

# Vue 3 API promise

  • Vue3 encapsulates some APIs with promises, and the call will enter the then method callback if the call is successful. If the call fails, it will enter the catch method callback

Use example:

Vue 3

// default method
uni.request({
  url: "https://www.example.com/request",
  success: (res) => {
    console.log(res.data);
  },
  fail: (err) => {
    console.error(err);
  },
});

// call using Promise then/catch
uni
  .request({
    url: "https://www.example.com/request",
  })
  .then((res) => {
    // The res parameter here is the same as the res parameter in the success callback when the default method is used
    console.log(res.data);
  })
  .catch((err) => {
    // The err parameter here is the same as the err parameter in the fail callback when the default method is used
    console.error(err);
  });

// use Async/Await method to call
async function request() {
  try {
    var res = await uni.request({
      url: "https://www.example.com/request",
    });
    // The res parameter here is the same as the res parameter in the success callback when the default method is used
    console.log(res);
  } catch (err) {
    // The err parameter here is the same as the err parameter in the fail callback when the default method is used
    console.error(err);
  }
}
  • Convert between return formats

Vue3

function isPromise(obj) {
  return (
    !!obj &&
    (typeof obj === "object" || typeof obj === "function") &&
    typeof obj.then === "function"
  );
}

uni.addInterceptor({
  returnValue(res) {
    if (!isPromise(res)) {
      return res;
    }
    const returnValue = [undefined, undefined];
    return res
      .then((res) => {
        returnValue[1] = res;
      })
      .catch((err) => {
        returnValue[0] = err;
      })
      .then(() => returnValue);
  },
});

# API list

# Base

# log print
API Description
Log print Print log information to the console
timer Execute the registered callback function after the timer expires
uni.base64ToArrayBuffer Convert Base64 string to ArrayBuffer object
uni.arrayBufferToBase64 Convert ArrayBuffer object to Base64 string
Interceptor Intercept calls such as Api and execute callbacks

# Network

# Initiating request
API Description
uni.request Initiate a network request
# WebSocket
API Description
uni.connectSocket Create a WebSocket connection
uni.onSocketOpen Listen for WebSocket open
uni.onSocketError Listen for WebSocket errors
uni.sendSocketMessage Send WebSocket message
uni.onSocketMessage Accept WebSocket messages
uni.closeSocket Close WebSocket connection
uni.onSocketClose Listen for WebSocket close
# SocketTask
API Description
SocketTask.send Send data via WebSocket connection
SocketTask.close Close WebSocket connection
SocketTask.onOpen Listen for WebSocket connection open events
SocketTask.onClose Listen for WebSocket connection close events
SocketTask.onError Listen for WebSocket error events
SocketTask.onMessage Listen for the message event received by the WebSocket server

# Media

# Image
API Description
uni.chooseImage Choose an image from the album, or take a photo
uni.previewImage Preview image
uni.closePreviewImage Close preview image
uni.getImageInfo Get image information
uni.saveImageToPhotosAlbum Save image to system album
# Document
API Description
uni.chooseFile Choose file from local
# Recording Management
API Description
uni.getRecorderManager Recording management
# Background audio playback management
API Description
uni.getBackgroundAudioManager Background audio playback management -->
# Audio component management
API Description
uni.createInnerAudioContext Audio component management
# Video
API Description
uni.chooseVideo Choose video from album, or shoot
uni.chooseMedia Capture or select a picture or video from your phone's camera roll.
uni.saveVideoToPhotosAlbum Save video to system album
uni.createVideoContext Video component management

# Document

API Description
uni.saveFile save file -->
uni.getSavedFileList Get the list of saved files -->
uni.getSavedFileInfo Get saved file information -->
uni.removeSavedFile Delete saved file information -->
uni.getFileInfo Get file information
uni.openDocument Open file

# Data cache

API Description
uni.getStorage Get local data cache
uni.getStorageSync Get local data cache
uni.setStorage Set local data cache
uni.setStorageSync Set local data cache
uni.getStorageInfo Get information about local cache
uni.getStorageInfoSync Get information about local cache
uni.removeStorage Remove local cache content
uni.removeStorageSync Delete local cache content
uni.clearStorage Clear local data cache
uni.clearStorageSync Clear local data cache

# Location

# Get location
API Description
uni.getLocation Get current location
uni.chooseLocation Open the map and choose the location
# View location
API Description
uni.openLocation Open built-in map
# Map component control
API Description
uni.createMapContext Map component control

# Device

# System message
API Description
uni.getSystemInfo Get system information
uni.getSystemInfoSync Get system information
uni.getDeviceInfo Get basic device information
uni.getWindowInfo Get window information
uni.getAppBaseInfo Get base information
uni.getAppBaseInfo Get base information
uni.getHostLanguage Get the host App language
uni.getHostFontSize Get the host App font size

| uni.canIUse | Determine whether the application's API, callback, parameters, components, etc. are available in the current version |

# Network status
API Description
uni.getNetworkType Get network type
uni.onNetworkStatusChange Monitor network status changes
uni.offNetworkStatusChange Cancel monitoring network status changes
# Accelerometer
API Description
uni.onAccelerometerChange Monitor acceleration data
uni.offAccelerometerChange Cancel monitoring acceleration data
uni.startAccelerometer Start monitoring acceleration data
uni.stopAccelerometer Stop monitoring acceleration data
# Compass
API Description
uni.onCompassChange Monitor compass data
uni.offCompassChange Cancel monitoring compass data
uni.startCompass Start listening for compass data
uni.stopCompass Stop monitoring compass data
# Dial number
API Description
uni.makePhoneCall make a call
# Scan code
API Description
uni.scanCode Scan code -->
# Clipboard
API Description
uni.setClipboardData Set clipboard content
uni.getClipboardData Get clipboard content
# Screen brightness
API Description
uni.setScreenBrightness Set screen brightness
uni.getScreenBrightness Get screen brightness
uni.setKeepScreenOn Set whether to keep the always-on state
# Vibration
API Description
uni.vibrate Vibrate phone
uni.vibrateLong Make the phone vibrate for a long time
uni.vibrateShort Make the phone vibrate for a short time
# Mobile phone contact
API Description
uni.addPhoneContact Add phone contacts
# Bluetooth
API Description
uni.openBluetoothAdapter Initialize the Bluetooth module
uni.startBluetoothDevicesDiscovery Discover nearby Bluetooth peripherals
uni.onBluetoothDeviceFound Listen for new device found events
uni.stopBluetoothDevicesDiscovery stop discovery
uni.onBluetoothAdapterStateChange Listen for bluetooth adapter state change events
uni.getConnectedBluetoothDevices Get connected devices by uuid
uni.getBluetoothDevices Get discovered bluetooth devices
uni.getBluetoothAdapterState Get the state of the native Bluetooth adapter
uni.closeBluetoothAdapter Close the bluetooth module
# Bluetooth Low Energy
API Description
uni.writeBLECharacteristicValue Write binary data to Bluetooth low energy device characteristic value
uni.readBLECharacteristicValue Read the binary data value of the characteristic value of the Bluetooth low energy device
uni.onBLEConnectionStateChange Listen for Bluetooth Low Energy connection state change events
uni.onBLECharacteristicValueChange Monitor the characteristic value change event of Bluetooth low energy devices
uni.notifyBLECharacteristicValueChange Enable the notify function when the characteristic value of a Bluetooth low energy device changes, subscribe to the characteristic
uni.getBLEDeviceServices Get all Bluetooth device services (service)
uni.getBLEDeviceCharacteristics Get all the characteristic values (characteristic) in a service of a Bluetooth device
uni.createBLEConnection Connect to a Bluetooth Low Energy device
uni.closeBLEConnection Disconnect from a Bluetooth Low Energy device
# iBeacon
API Description
uni.onBeaconServiceChange Listen for iBeacon service status change events
uni.onBeaconUpdate Listen for iBeacon device update events
uni.getBeacons Get all searched iBeacon devices
uni.startBeaconDiscovery Stop searching for nearby iBeacon devices
uni.stopBeaconDiscovery Start searching for iBeacon devices nearby
# Biometric authentication
API Description
uni.startSoterAuthentication Start biometric authentication
uni.checkIsSupportSoterAuthentication Get the supported biometric authentication methods
uni.checkIsSoterEnrolledInDevice The interface to obtain whether biometric information such as fingerprints is entered in the device -->

# Interface

# Interactive feedback
API Description
uni.showToast Show prompt box
uni.showLoading Show loading prompt
uni.hideToast Hide the prompt box
uni.hideLoading Hide loading prompt box
uni.showModal Show modal popup
uni.showActionSheet Show menu list
# Set navigation bar
API Description
uni.setNavigationBarTitle Set the current page title
uni.setNavigationBarColor Set page navigation bar color
uni.showNavigationBarLoading Show navigation bar loading animation
uni.hideNavigationBarLoading Hide navigation bar loading animation
# Setting TabBar
API Description
uni.setTabBarItem Dynamically set the content of a tabBar item
uni.setTabBarStyle Dynamically set the overall style of the tabBar
uni.hideTabBar hide tabBar
uni.showTabBar Show tabBar
uni.setTabBarBadge Add text to the upper right corner of a tabBar item
uni.removeTabBarBadge Remove the text in the upper right corner of a tabBar item
uni.showTabBarRedDot Show the red dot in the upper right corner of a tabBar item
uni.hideTabBarRedDot Hide the red dot in the upper right corner of a tabBar item
# Animation
API Description
uni.createAnimation Create an animation instance animation. Call the instance's method to describe the animation. Finally, the animation data is exported through the export method of the animation instance and passed to the animation property of the component.
# Scroll
API Description
uni.pageScrollTo Scroll the page to the target position.
# Painting
API Description
uni.createCanvasContext Create drawing context
uni.canvasToTempFilePath Save the canvas content to a file
uni.canvasGetImageData Get canvas image data
uni.canvasPutImageData Set canvas image data
# Pull down to refresh
API Description
onPullDownRefresh Listen to the page user pull down refresh event
uni.startPullDownRefresh Start pull down refresh
uni.stopPullDownRefresh Stop pull-down refresh of the current page
# Node information
API Description
uni.createSelectorQuery Create query request
selectorQuery.select Select a single node based on selector
selectorQuery.selectAll Select all nodes according to selector
selectorQuery.selectViewport Select display area
selectorQuery.exec Execute query request
nodesRef.boundingClientRect Get layout position and size
nodesRef.scrollOffset Get scroll position
nodesRef.fields Get any field
# Node layout intersection state
API Description
uni.createIntersectionObserver Create IntersectionObserver object
intersectionObserver.relativeTo Specify reference node
intersectionObserver.relativeToViewport Specify the page display area as the reference area
intersectionObserver.observe Specify the target node and start listening
intersectionObserver.disconnect stop listening

# Routing

API Description
uni.navigateTo Keep the current page, jump to a page in the app, use uni.navigateBack to return to the original page
uni.redirectTo Close the current page and jump to a page in the app
uni.reLaunch Close all pages, open to a page in the app
uni.switchTab Jump to the tabBar page and close all other non-tabBar pages
uni.navigateBack Close the current page and return to the previous page or multi-level page

# keyboard

API Description
uni.hideKeyboard Hide the displayed soft keyboard. If the soft keyboard is not displayed, do nothing.
uni.onKeyboardHeightChange Monitor keyboard height changes -->
uni.offKeyboardHeightChange Cancel listening for keyboard height change events -->
uni.getSelectedTextRange After input, textarea, etc. focus, get the cursor position of the input box

# Open API

API Description
uni.login Register
uni.getUserProfile Get User Info
uni.getAuthCode Get Auth Code
uni.share share
uni.shareMiniAppMessage share MiniApp to Message
uni.requestPayment Pay

# Other

API Description
uni.setEnableDebug Open the debug switch
uni.launchApp Open Other Apps
uni.restartMiniProgram Restart Mini App
uni.exitMiniProgram Exit Mini App

Due to document synchronization reasons, the APIs listed on this page may not be complete. If you do not find the relevant API in this article, you can find it in the tree on the left or use the search function in the upper right corner of the document.

About Neuxnet: Neuxnet Website