The js API of uni-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. The applet also extends various wx.xx, my.xx, swan.xx APIs based on standard js. Node also extends modules like fs.

uni-app extends the uni object based on ECMAScript, and the API naming remains compatible with applets.

# Difference between standard js and browser js

The js code of uni-app, the web side runs in the browser. For the non-web side (including applets and apps), 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 uni-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.

In addition to the built-in cross-end API of the uni-app framework, each end's own characteristic API can also be freely used through conditional compilation.

For the specific API specifications of each terminal, refer to the development documents of each terminal. The JS API on the App side refers to html5plus.org; uni-app also supports the extension of native plugins to enrich the development capabilities of the App side. For details, refer to Plugin Development Documentation

The API of each platform is newly added, and developers can use it directly without uni-app upgrade.

# 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.
  • Platform difference descriptionUnless otherwise specified, it means that all platforms support it.
  • 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 2 and Vue 3 API promise

The return format of API Promise in Vue 2 and Vue 3 projects is inconsistent. The following is the difference and return format conversion

  • difference

    • Vue2 encapsulates some APIs with promises. The first parameter of the returned data is the error object, and the second parameter is the return data. At this time, using catch will not get the error message, because the error is intercepted internally.
    • 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:

    Vue2

    Vue 3

    // default method
    uni.request({
      url: "https://www.example.com/request",
      success: (res) => {
        console.log(res.data);
      },
      fail: (err) => {
        console.error(err);
      },
    });
    
    // Promise
    uni
      .request({
        url: "https://www.example.com/request",
      })
      .then((data) => {
        // data is an array
        // The first item of the array is the error message, which is the fail callback
        // The second item is the return data
        var [err, res] = data;
        console.log(res.data);
      });
    
    // Await
    async function request() {
      var [err, res] = await uni.request({
        url: "https://www.example.com/request",
      });
      console.log(res.data);
    }
    
  • Convert between return formats

Vue2

Vue3

// Vue 2 to Vue 3, write the following code in main.js
function isPromise(obj) {
  return (
    !!obj &&
    (typeof obj === "object" || typeof obj === "function") &&
    typeof obj.then === "function"
  );
}

uni.addInterceptor({
  returnValue(res) {
    if (!isPromise(res)) {
      return res;
    }
    return new Promise((resolve, reject) => {
      res.then((res) => {
        if (res[0]) {
          reject(res[0]);
        } else {
          resolve(res[1]);
        }
      });
    });
  },
});

# 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
Application-level events Listen to application events
Interceptor Intercept calls such as Api and execute callbacks
Global API Api can be called globally

# Network

# Initiating request
API Description
uni.request Initiate a network request
# Upload and download
API Description
uni.uploadFile upload file
uni.downloadFile Download file
# 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
# Camera component management
API Description
uni.createCameraContext Camera component management
# Live stream component management
API Description
uni.createLivePlayerContext Live 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.canIUse Determine whether the application's API, callback, parameters, components, etc. are available in the current version
# Memory
API Description
uni.onMemoryWarning Monitor low memory warning events
# 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
# Gyro
API Description
uni.onGyroscopeChange Monitor gyroscope data
uni.startGyroscope Start monitoring gyroscope data
uni.stopGyroscope Stop monitoring gyroscope 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
# User screenshot event
API Description
uni.onUserCaptureScreen Listen for user screen capture events
# 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
# background
API Description
uni.setBackgroundColor Dynamically set the background color of the window.
uni.setBackgroundTextStyle Dynamically set the style of the drop-down background font and loading image.
# 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](/api/ui/nodes-info?id=selectorquery-%E5%AF%B9%E8%B1%A1%E7%9A%84%E6%96%B9%E6%B3%95 %E5%88%97%E8%A1%A8) Select a single node based on selector
[selectorQuery.selectAll](/api/ui/nodes-info?id=selectorquery-%E5%AF%B9%E8%B1%A1%E7%9A%84%E6%96%B9%E6%B3%95 %E5%88%97%E8%A1%A8) Select all nodes according to selector
[selectorQuery.selectViewport](/api/ui/nodes-info?id=selectorquery-%E5%AF%B9%E8%B1%A1%E7%9A%84%E6%96%B9%E6%B3%95 %E5%88%97%E8%A1%A8) Select display area
[selectorQuery.exec](/api/ui/nodes-info?id=selectorquery-%E5%AF%B9%E8%B1%A1%E7%9A%84%E6%96%B9%E6%B3%95 %E5%88%97%E8%A1%A8) Execute query request
[nodesRef.boundingClientRect](/api/ui/nodes-info?id=nodesref-%E5%AF%B9%E8%B1%A1%E7%9A%84%E6%96%B9%E6%B3%95 %E5%88%97%E8%A1%A8) Get layout position and size
[nodesRef.scrollOffset](/api/ui/nodes-info?id=nodesref-%E5%AF%B9%E8%B1%A1%E7%9A%84%E6%96%B9%E6%B3%95 %E5%88%97%E8%A1%A8) Get scroll position
[nodesRef.fields](/api/ui/nodes-info?id=nodesref-%E5%AF%B9%E8%B1%A1%E7%9A%84%E6%96%B9%E6%B3%95 %E5%88%97%E8%A1%A8) Get any field
# Node layout intersection state
API Description
uni.createIntersectionObserver Create IntersectionObserver object
[intersectionObserver.relativeTo](/api/ui/intersection-observer?id=intersectionobserver-%E5%AF%B9%E8%B1%A1%E7%9A%84%E6%96%B9%E6%B3%95 %E5%88%97%E8%A1%A8) Specify reference node
[intersectionObserver.relativeToViewport](/api/ui/intersection-observer?id=intersectionobserver-%E5%AF%B9%E8%B1%A1%E7%9A%84%E6%96%B9%E6%B3%95 %E5%88%97%E8%A1%A8) Specify the page display area as the reference area
[intersectionObserver.observe](/api/ui/intersection-observer?id=intersectionobserver-%E5%AF%B9%E8%B1%A1%E7%9A%84%E6%96%B9%E6%B3%95 %E5%88%97%E8%A1%A8) Specify the target node and start listening
[intersectionObserver.disconnect](/api/ui/intersection-observer?id=intersectionobserver-%E5%AF%B9%E8%B1%A1%E7%9A%84%E6%96%B9%E6%B3%95 %E5%88%97%E8%A1%A8) 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

# Third Party Services

API Description
uni.getProvider Get service provider
uni.login Register
uni.getUserInfo Get user information
uni.getuserprofile Get user information. An authorization window will pop up for each request. After the user agrees, return userInfo
uni.checkSession Check if login status is expired
uni.preLogin
uni.closeAuthView Close the one-click login page
uni.getCheckBoxState Get the check box state of one-click login terms
uni.getUniverifyManager Get the globally unique one-key login manager univerifyManager
uni.share
uni.shareWithSystem Use system share
uni.requestPayment payment
uni.subscribePush Enable push
uni.unsubscribePush Disable push
uni.onPush Monitor transparent data
uni.offPush Remove monitor passthrough data
API Description
Rewarded Video Ads Rewarded Video Ads are the most profitable ad format for cpm
full screen video ad full screen video ad
Content Ads Content Ads
Interstitial Interstitial
Interactive Game Interactive Game is DCloud's joint third-party service providers to provide developers with new value-added services for advertising scenarios

# Platform extension

API Description
uni.requireNativePlugin Introduce App native plugin

# other

# Authorization
API Description
uni.authorize Initiate an authorization request to the user in advance
# set up
API Description
uni.openSetting Call up the client applet setting interface and return the operation result set by the user.
uni.getSetting Get the current setting of the user.
# Shipping address
API Description
uni.chooseAddress Get the user's shipping address
# Get invoice header
API Description
uni.chooseInvoiceTitle Select the user's invoice title, which requires user authorization scope.invoiceTitle.
# Mini Program Jump
API Description
uni.navigateToMiniProgram Open another miniprogram.
uni.navigateBackMiniProgram Jump back to the previous applet, which can only be called successfully when another applet jumps to the current one.
# Template message
API Description
addTemplate Combine templates and add to the personal template library under the account.
deleteTemplate Delete a template under the account.
getTemplateLibraryById Get the keyword library under a template title of the template library.
getTemplateLibraryList Get APP template library title list
getTemplateList Get the list of existing templates under the account.
sendTemplateMessage Send template message
alipay.open.app.mini.templatemessage.send Alipay applet sends messages to users through openapi, mainly after payment (through consumption id) And the touch after the user submits the form (via formId).
# Mini Program Update
API Description
uni.getUpdateManager Returns the globally unique version update manager object: updateManager, which is used to manage applet updates.
# Debug
API Description
uni.setEnableDebug Set whether to enable debugging. This switch also works for the official version.
# Get third-party platform data
API Description
uni.getExtConfig Get data fields customized by third-party platforms.
uni.getExtConfigSync Synchronized version of uni.getExtConfig.

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.