Skip to content

Basics

canIUse

TIP

The API usage is as follows:Boolean wx.canIUse(string schema)

  • Functional description: Determine whether the API, callback, parameters, components, etc. of the mini program are available in the current version.
  • Parameters and descriptions: String schema
    • Use ${API}.${method}.${param}.${options} or ${component}.${attribute}.${option} to call.
    • Parameter description:
      Parameter description:Description
      ${API}Represents the API name
      ${method}Represents the calling method, valid values
      ${param}Represents the parameter or return value
      ${options}Represents the optional value of the parameter
      ${component}Represents the component name
      ${attribute}Represents the component attribute
      ${option}Represents the optional value of the component attribute
  • Return value: Boolean, Indicates whether the current version is available.
  • Sample code:
js
wx.canIUse("openBluetoothAdapter");
wx.canIUse("getSystemInfoSync.return.screenWidth");
wx.canIUse("getSystemInfo.success.screenWidth");
wx.canIUse("showToast.object.image");
wx.canIUse("onCompassChange.callback.direction");
wx.canIUse("request.object.method.GET");

wx.canIUse("live-player");
wx.canIUse("text.selectable");
wx.canIUse("button.open-type.contact");

env

TIP

The API usage is as follows: wx.env

  • Functional description: Environment variables
  • Parameters and descriptions: string USER_DATA_PATH,User directory path in the file system (local path).

base64ToArrayBuffer

TIP

The API usage is as follows: ArrayBuffer wx.base64ToArrayBuffer(string base64)

  • Functional description: Convert Base64 string to ArrayBuffer object
  • Parameters and descriptions: string base64,Base64 string to be converted into ArrayBuffer object.
  • Return value: ArrayBuffer, ArrayBuffer object.
  • Sample code:
js
const base64 = "CxYh";
const arrayBuffer = wx.base64ToArrayBuffer(base64);

arrayBufferToBase64

TIP

The API usage is as follows: string wx.arrayBufferToBase64(ArrayBuffer arrayBuffer)
This API is supported by mini programs, but not by mini games.

  • Functional description: Convert ArrayBuffer object to Base64 string
  • Parameters and descriptions: ArrayBuffer arrayBuffer, ArrayBuffer object to be converted into Base64 string.
  • Return value: string, Base64 string.
  • Sample code:
js
const arrayBuffer = new Uint8Array([11, 22, 33]);
const base64 = wx.arrayBufferToBase64(arrayBuffer);

System

getSystemInfo

TIP

The API usage is as follows: wx.getSystemInfo(Object object)

  • Functional description: Get system information

  • Parameters and descriptions: Object Object

    PropertiesTypeDefault valueRequiredDescription
    successFunction-NoCallback function for successful interface call
    failFunction-NoCallback function for failed interface call
    completeFunction-NoCallback function for interface call completion (executed regardless of success or failure)
    • res callback result of Object.success

      PropertiesTypeDescription
      brandStringDevice brand
      modelStringDevice model
      pixelRatioNumberDevice pixel ratio
      screenWidthNumberScreen width, unit px
      screenHeightNumberScreen height, unit px
      windowWidthNumberUsable window width, unit px
      windowHeightNumberUsable window height, unit px
      statusBarHeightNumberStatus bar height, unit px
      languageStringLanguage
      versionStringVersion number
      systemStringOperating system and version
      platformStringClient platform, its legal values
      1. ios: iOS client (including iPhone, iPad)
      2. android: Android client
      3. devtools: Luffa Cloud developer tools
      fontSizeSettingnumberUser font size, unit px
      SDKVersionStringClient base library version
      AppPlatformStringApp platform
      safeAreaObjectThe safe area in the positive direction of the vertical screen
      themeStringThe current theme of the system, the value is light or dark, which can only be obtained when the global configuration 'darkmode':true, otherwise it is undefined
    • The structure of res.safeArea:

      PropertiesTypeDescription
      leftNumberThe horizontal coordinate of the upper left corner of the safe area
      rightNumberThe horizontal coordinate of the lower right corner of the safe area
      topNumberThe vertical coordinate of the upper left corner of the safe area
      bottomNumberThe vertical coordinate of the lower right corner of the safe area
      widthNumberThe width of the safe area, unit logical pixel
      heightNumberThe height of the safe area, unit logical pixel
  • Sample code:

js
wx.getSystemInfo({
  success(res) {
    console.log(res.model);
    console.log(res.pixelRatio);
    console.log(res.windowWidth);
    console.log(res.windowHeight);
    console.log(res.language);
    console.log(res.version);
    console.log(res.platform);
  },
});
js
try {
  const res = wx.getSystemInfoSync();
  console.log(res.model);
  console.log(res.pixelRatio);
  console.log(res.windowWidth);
  console.log(res.windowHeight);
  console.log(res.language);
  console.log(res.version);
  console.log(res.platform);
} catch (e) {
  // Do something when catch error
}

getSystemInfoSync

TIP

The API usage is as follows: Object wx.getSystemInfoSync()

  • Functional description: wx.getSystemInfo The synchronous version
  • res callback result of Object.success
PropertiesTypeDescription
brandStringDevice brand
modelStringDevice model
pixelRatioNumberDevice pixel ratio
screenWidthNumberScreen width, unit px
screenHeightNumberScreen height, unit px
windowWidthNumberUsable window width, unit px
windowHeightNumberUsable window height, unit px
statusBarHeightNumberStatus bar height, unit px
languageStringLanguage
versionStringVersion number
systemStringOperating system and version
platformStringClient platform, its legal values
1. ios: iOS client (including iPhone, iPad)
2. android: Android client
3. devtools: Luffa Cloud developer tools
fontSizeSettingnumberUser font size, unit px
SDKVersionStringClient base library version
AppPlatformStringApp platform
safeAreaObjectThe safe area in the positive direction of the vertical screen
themeStringThe current theme of the system, the value is light or dark, which can only be obtained when the global configuration 'darkmode':true, otherwise it is undefined
  • The structure of res.safeArea:
PropertiesTypeDescription
leftNumberThe horizontal coordinate of the upper left corner of the safe area
rightNumberThe horizontal coordinate of the lower right corner of the safe area
topNumberThe vertical coordinate of the upper left corner of the safe area
bottomNumberThe vertical coordinate of the lower right corner of the safe area
widthNumberThe width of the safe area, unit logical pixel
heightNumberThe height of the safe area, unit logical pixel
  • Sample code:
js
wx.getSystemInfo({
  success(res) {
    console.log(res.model);
    console.log(res.pixelRatio);
    console.log(res.windowWidth);
    console.log(res.windowHeight);
    console.log(res.language);
    console.log(res.version);
    console.log(res.platform);
  },
});
js
try {
  const res = wx.getSystemInfoSync();
  console.log(res.model);
  console.log(res.pixelRatio);
  console.log(res.windowWidth);
  console.log(res.windowHeight);
  console.log(res.language);
  console.log(res.version);
  console.log(res.platform);
} catch (e) {
  // Do something when catch error
}

getSystemInfoAsync

TIP

The API usage is as follows: wx.getSystemInfoAsync(Object object)

  • Functional description: Asynchronously obtains system information. It requires certain host client version support. On unsupported clients, it will use synchronous implementation to return.

  • Parameters and descriptions: Object Object。

    PropertiesTypeDefault valueRequiredDescription
    successFunction-NoCallback function for successful interface call
    failFunction-NoCallback function for failed interface call
    completeFunction-NoCallback function for interface call completion (executed regardless of success or failure)
    • object.success callback function parameters: Object res

      PropertiesTypeDescription
      brandStringDevice brand
      modelStringDevice model
      pixelRatioNumberDevice pixel ratio
      screenWidthNumberScreen width, unit px
      screenHeightNumberScreen height, unit px
      windowWidthNumberUsable window width, unit px
      windowHeightNumberUsable window height, unit px
      statusBarHeightNumberStatus bar height, unit px
      languageStringLanguage
      versionStringVersion number
      systemStringOperating system and version
      platformStringClient platform, its legal values
      1. ios: iOS client (including iPhone, iPad)
      2. android: Android client
      3. devtools: Luffa Cloud developer tools
      fontSizeSettingnumberUser font size, unit px
      SDKVersionStringClient base library version
      safeAreaObjectIn the safe area under the positive direction of the vertical screen, some models do not have the concept of safe area and will not return the safeArea field. Developers need to be compatible by themselves. For the return value, please refer to the following table safeArea return value
      themeStringThe current theme of the system, the value is light or dark, which can only be obtained when the global configuration 'darkmode':true, otherwise it is undefined
      light:Bright
      dark:Dark
    • The structure of res.safeArea:

      PropertiesTypeDescription
      leftNumberThe horizontal coordinate of the upper left corner of the safe area
      rightNumberThe horizontal coordinate of the lower right corner of the safe area
      topNumberThe vertical coordinate of the upper left corner of the safe area
      bottomNumberThe vertical coordinate of the lower right corner of the safe area
      widthNumberThe width of the safe area, unit logical pixel
      heightNumberThe height of the safe area, unit logical pixel
  • Sample code:

js
wx.getSystemInfoAsync({
  success(res) {
    console.log(res.model);
    console.log(res.pixelRatio);
    console.log(res.windowWidth);
    console.log(res.windowHeight);
    console.log(res.language);
    console.log(res.version);
    console.log(res.platform);
  },
});

getWindowInfo

TIP

The API usage is as follows: Object wx.getWindowInfo()

  • Functional description: Get window information
  • Parameters and descriptions: Object。
PropertiesTypeDescription
pixelRatioNumberDevice pixel ratio
screenWidthNumberScreen width, unit px
screenHeightNumberScreen height, unit px
windowWidthNumberUsable window width, unit px
windowHeightNumberUsable window height, unit px
statusBarHeightNumberStatus bar height, unit px
safeAreaObjectIn the safe area under the positive direction of the vertical screen, some models do not have the concept of safe area and will not return the safeArea field. Developers need to be compatible by themselves. For the return value, please refer to the following table safeArea return value
screenTopnumberThe y value of the upper edge of the window
  • safeArea return value
PropertiesTypeDescription
leftNumberThe horizontal coordinate of the upper left corner of the safe area
rightNumberThe horizontal coordinate of the lower right corner of the safe area
topNumberThe vertical coordinate of the upper left corner of the safe area
bottomNumberThe vertical coordinate of the lower right corner of the safe area
widthNumberThe width of the safe area, unit logical pixel
heightNumberThe height of the safe area, unit logical pixel
  • Sample code:
js
const windowInfo = wx.getWindowInfo();

console.log(windowInfo.pixelRatio);
console.log(windowInfo.screenWidth);
console.log(windowInfo.screenHeight);
console.log(windowInfo.windowWidth);
console.log(windowInfo.windowHeight);
console.log(windowInfo.statusBarHeight);
console.log(windowInfo.safeArea);
console.log(windowInfo.screenTop);

getSystemSetting

TIP

The API usage is as follows: Object wx.getSystemSetting()
This API is supported by mini programs, but not by mini games.

  • Functional description: Get device settings
  • Parameters and descriptions: Object。
PropertiesTypeDescription
bluetoothEnabledbooleanBluetooth system switch
locationEnabledbooleanGeographic location system switch
wifiEnabledbooleanWi-Fi system switch
deviceOrientationstringDevice direction, its legal values
1.portrait:Portrait screen
2.landscape:Landscape screen
  • Sample code:
js
const systemSetting = wx.getSystemSetting();

console.log(systemSetting.bluetoothEnabled);
console.log(systemSetting.deviceOrientation);
console.log(systemSetting.locationEnabled);
console.log(systemSetting.wifiEnabled);

openSystemBluetoothSetting

TIP

The API usage is as follows: wx.openSystemBluetoothSetting(Object object)
This API is supported by mini programs, but not by mini games.

  • Functional description: Jump to the system Bluetooth settings page. Only supports Android.

  • Parameters and descriptions: Object object。

    PropertiesTypeDefault valueRequiredDescription
    successFunction-NoCallback function for successful interface call
    failFunction-NoCallback function for failed interface call
    completeFunction-NoCallback function for interface call completion (executed regardless of success or failure)
  • Sample code:

js
wx.openSystemBluetoothSetting({
  success(res) {
    console.log(res);
  },
});

openAppAuthorizeSetting

TIP

The API usage is as follows: wx.openAppAuthorizeSetting(Object object)
This API is supported by mini programs, but not by mini games.

  • Functional description: Jump to system host client authorization management page.

  • Parameters and descriptions: Object object。

    PropertiesTypeDefault valueRequiredDescription
    successFunction-NoCallback function for successful interface call
    failFunction-NoCallback function for failed interface call
    completeFunction-NoCallback function for interface call completion (executed regardless of success or failure)
  • Sample code:

js
wx.openAppAuthorizeSetting({
  success(res) {
    console.log(res);
  },
});

getRendererUserAgent

TIP

The API usage is as follows: Promise wx.getRendererUserAgent(Object object)
This API is supported by mini programs, but not by mini games.

  • Functional description: Get the UserAgent of Webview applet.

  • Parameters and descriptions: Object object。

    PropertiesTypeDefault valueRequiredDescription
    successFunction-NoCallback function for successful interface call
    failFunction-NoCallback function for failed interface call
    completeFunction-NoCallback function for interface call completion (executed regardless of success or failure)
  • object.success callback function parameters: string userAgent,UserAgent。

  • Return value: Promise.<string>。

  • Sample code:

js
wx.getRendererUserAgent().then((userAgent) => console.log(userAgent));
wx.getRendererUserAgent({
  success(res) {
    console.log(res.userAgent);
  },
});

getDeviceInfo

TIP

The API usage is as follows: Object wx.getDeviceInfo()
This API is supported by mini programs, but not by mini games.

  • Functional description: Get basic device information.

  • Return value: Object。

    PropertiesTypeDescription
    abistringHost App binary interface type (only supported by Android)
    deviceAbistringDevice performance level (only supported by Android), legal values
    -2 or 0: The device cannot run mini games
    -1: unknown performance
    >=1: Device performance value, the higher the value, the better the device performance, currently the highest is less than 54
    benchmarkLevelnumberWi-Fi system switch
    brandstringDevice brand
    modelstringDevice model
    systemstringOperating system and version
    platformstringClient platform
    cpuTypestringDevice CPU model (only supported by Android) GPU model can be obtained through WebGLRenderingContext.getExtension('WEBGL_debug_renderer_info')
    menorySizestringDevice memory size, in MB
    • Sample code:
js
const deviceInfo = wx.getDeviceInfo();

console.log(deviceInfo.abi);
console.log(deviceInfo.benchmarkLevel);
console.log(deviceInfo.brand);
console.log(deviceInfo.model);
console.log(deviceInfo.platform);
console.log(deviceInfo.system);

getAppBaseInfo

TIP

The API usage is as follows: Object wx.getAppBaseInfo()
This API is supported by mini programs, but not by mini games.

  • Functional description: Get basic host client information

  • Parameters and descriptions: Object。

    PropertiesTypeDescription
    SDKVersionstringHost client base library version
    enableDebugbooleanWhether debugging is turned on. You can use the upper right menu orwx.setEnableDebugTurn on debugging
    hostObjectThe host environment where the current mini program is running
    languagestringThe language set by the host client
    versionstringHost client version number
    themestringThe current system theme, the value is `light: bright mode` or `dark: dark mode`, which can only be obtained when the global configuration `'darkmode':true` is used, otherwise it is undefined (mini games are not supported)
    • Sample code:
js
const appBaseInfo = wx.getAppBaseInfo();

console.log(appBaseInfo.SDKVersion);
console.log(appBaseInfo.enableDebug);
console.log(appBaseInfo.host);
console.log(appBaseInfo.language);
console.log(appBaseInfo.version);
console.log(appBaseInfo.theme);

getAppAuthorizeSetting

TIP

The API usage is as follows: Object wx.getAppAuthorizeSetting()
This API is supported by mini programs, but not by mini games.

  • Functional description: Get host client authorization settings

  • Parameters and descriptions: Object。

    PropertiesTypeDescription
    albumAuthorized'authorized'/'denied'/'not determined'The switch that allows the host client to use the album (only valid for iOS)
    bluetoothAuthorized'authorized'/'denied'/'not determined'The switch that allows the host client to use Bluetooth (only valid for iOS)
    cameraAuthorized'authorized'/'denied'/'not determined'The switch that allows the host client to use the camera
    locationAuthorized'authorized'/'denied'/'not determined'The switch that allows the host client to use positioning
    locationReducedAccuracybooleanPositioning accuracy. true indicates fuzzy positioning, false indicates precise positioning (only valid for iOS)
    microphoneAuthorized'authorized'/'denied'/'not determined'Switch to allow host client to use microphone
    notificationAuthorized'authorized'/'denied'/'not determined'Switch to allow host client to notify
    notificationAlertAuthorized'authorized'/'denied'/'not determined'Switch to allow host client to notify with reminders (only valid for iOS)
    notificationBadgeAuthorized'authorized'/'denied'/'not determined'Switch to allow host client to notify with tags (only valid for iOS)
    notificationSoundAuthorized'authorized'/'denied'/'not determined'Switch to allow host client to notify with sound (only valid for iOS)
    phoneCalendarAuthorized'authorized'/'denied'/'not determined'Switch to allow host client to read and write calendar
    • Sample code:
js
const appAuthorizeSetting = wx.getAppAuthorizeSetting();

console.log(appAuthorizeSetting.albumAuthorized);
console.log(appAuthorizeSetting.bluetoothAuthorized);
console.log(appAuthorizeSetting.cameraAuthorized);
console.log(appAuthorizeSetting.locationAuthorized);
console.log(appAuthorizeSetting.locationReducedAccuracy);
console.log(appAuthorizeSetting.microphoneAuthorized);
console.log(appAuthorizeSetting.notificationAlertAuthorized);
console.log(appAuthorizeSetting.notificationAuthorized);
console.log(appAuthorizeSetting.notificationBadgeAuthorized);
console.log(appAuthorizeSetting.notificationSoundAuthorized);
console.log(appAuthorizeSetting.phoneCalendarAuthorized);

Update

getUpdateManager

TIP

The API usage is as follows: UpdateManager wx.getUpdateManager()

  • Functional description: Get the globally unique version update manager for managing mini program updates, using UpdateManager wx.getUpdateManager.
  • Return value: UpdateManager,Update manager object

UpdateManager

.applyUpdate

TIP

The API usage is as follows: UpdateManager.applyUpdate()

  • Functional description: Force the mini program to restart and use the new version. Called after the new version of the mini program is downloaded (i.e., receiving the onUpdateReady callback).

.onCheckForUpdate

TIP

The API usage is as follows: UpdateManager.onCheckForUpdate(function listener)

  • Functional description: Listen to the background request to check the update result event. Automatically check for updates when the mini program is cold started, without the developer's active trigger.

  • Parameters and descriptions: function callback, Callback function for requesting the background to check the update result event.

    PropertiesTypeDescription
    hasUpdateBooleanIs there a new version

.onUpdateFailed

TIP

The API usage is as follows: UpdateManager.onUpdateFailed(function listener)

  • Functional description: Listen for the mini program update failure event. The mini program has a new version, the client actively triggers the download (without the developer triggering it), and the callback is called after the download fails (may be due to network reasons, etc.).
  • Parameters and descriptions: function callback, Callback function for the mini program update failure event.

.onUpdateReady

TIP

The API usage is as follows: UpdateManager.onUpdateReady(function listener)

  • Functional description: Listen for the mini program version update event. The client actively triggers the download (without the developer triggering it), and the callback is called after the download is successful.

  • Parameters and descriptions: function callback, Callback function for the mini program new version update event

  • Sample code:

js
const updateManager = wx.getUpdateManager();

updateManager.onCheckForUpdate(function (res) {
  // Callback upon requesting new version information
  console.log(res.hasUpdate);
});

updateManager.onUpdateReady(function () {
  wx.showModal({
    title: "Update prompt",
    content:
      "The new version is ready. Do you want to restart the application?",
    success(res) {
      if (res.confirm) {
        // The new version has been downloaded. Call applyUpdate to apply the new version and restart.
        updateManager.applyUpdate();
      }
    },
  });
});

updateManager.onUpdateFailed(function () {
  // New version download failed
});

Mini program

Lifecycle

getLaunchOptionsSync

TIP

The API usage is as follows: Object wx.getLaunchOptionsSync()
Some versions will return undefined when there is no referrerInfo, it is recommended to use options.referrerInfo && options.referrerInfo.appId to judge.

  • Functional description: Get the parameters when the mini program is started

  • Return value: Object Startup parameters.

    PropertiesTypeDescription
    pathStringThe path to start the mini program (Only supported by mini programs.)
    sceneNumberThe scene value for starting the mini program, the default is 1005
    queryObjectThe query parameter for starting the mini program
    referrerInfoObjectSource information, returned when entering a mini program from another mini program or App. Otherwise, returns {}
    forwardMaterialsArray.<Object>Opened file information array
    • referrerInfo structure

      PropertiesTypeDescription
      appIdStringSource applet or App's appId
      extraDataObjectData passed from the source applet

TIP

The extraData field here is the extended parameter passed in by calling the native startup applet.

iOS:Incoming paramsStr

js
  [[TMFMiniAppSDKManager sharedInstance] startUpMiniAppWithAppID:@"mpbz0uqwzddj5zbt" scene:TMAEntrySceneNone firstPage:nil paramsStr:@"a=1&b=2" parentVC:self completion:^(NSError * _Nullable err) {

  }];

Android:The params field of the MiniStartLinkOptions object

js

MiniStartLinkOptions miniStartOptions = new MiniStartLinkOptions();
miniStartOptions.params = (String) options.get("params");
public static void startMiniApp(Activity activity, String appId, MiniStartOptions options) {
    startMiniApp(activity, appId, 1001, 0, options);
}
  • forwardMaterials structure

    PropertiesTypeDescription
    typeStringMimetype type of the file
    nameObjectFile name
    pathstringFile path
    sizenumberFile size
  • Scenario for returning valid referrerInfo

    PropertiesTypeDescription
    1037Mini Program Open Mini ProgramSource Mini Program
    1038Returned from another Mini ProgramSource Mini Program

getEnterOptionsSync

TIP

The API usage is as follows: Object wx.getEnterOptionsSync()

TIP

Some versions will return undefined when there is no referrerInfo, it is recommended to use options.referrerInfo && options.referrerInfo.appId to judge.

  • Functional description: Get the parameters when the Mini Program is started this time. If the current is a cold start, the return value is consistent with the callback parameter of App.onLaunch ; if the current is a hot start, the return value is consistent with App.onShow same.

  • Return value: Object

    PropertiesTypeDescription
    pathStringThe path (code package path) of the Mini Program
    sceneNumberThe scene value of the Mini Program
    queryObjectThe query parameter of the Mini Program
    shareTicketStringshareTicket
    referrerInfoObjectSource information. Returned when entering a mini program from another mini program or app. Otherwise returns {}. For details, see the note in the previous table.
    forwardMaterialsArray.<Object>Opened file information array
    • referrerInfo structure

      PropertiesTypeDescription
      appIdStringSource applet or App's appId
      extraDataObjectData passed from the source applet
    • forwardMaterials structure

      PropertiesTypeDescription
      typeStringMimetype type of the file
      nameObjectFile name
      pathstringFile path
      sizenumberFile size
  • Scenario for returning valid referrerInfo

    PropertiesTypeDescription
    1037Mini Program Open Mini ProgramSource Mini Program
    1038Returned from another Mini ProgramSource Mini Program

Application-level events

onError

TIP

The API usage is as follows: wx.onError(function callback)
This API is supported by mini programs, but not by mini games.

  • Functional description: Listen for Mini Program error events. Such as script errors or API call errors.
  • Parameters and descriptions: function callback, Callback function of Mini Program error events.
  • Return value: string error, Error information, including stack.

offError

TIP

The API usage is as follows: wx.offError(function callback)
This API is supported by mini programs, but not by mini games.

  • Functional description: Cancel listening for Mini Program error events.
  • Parameters and descriptions: function callback, Callback function of Mini Program error events.

onThemeChange

TIP

The API usage is as follows: wx.onThemeChange(function listener)
This API is supported by mini programs, but not by mini games.

Description

This event is triggered only when darkmode is configured globally: true

  • Functional description: Listen for system theme change events

  • Parameters and descriptions: function listener, Listener function for system theme change events

  • Return value: Object res

    PropertiesLegal valuesTypeDescription
    theme1.dark:Dark theme
    1.light:Light theme
    StringThe current system theme, value is light or dark

offThemeChange

TIP

The API usage is as follows: wx.offThemeChange(function listener)
This API is supported by mini programs, but not by mini games.

  • Functional description: Remove the listener function for system theme change events

  • Parameters and descriptions: function listener, Listener function passed in by onThemeChange. If this parameter is not passed, all listeners are removed.

  • Sample code:

js
const listener = function (res) {
  console.log(res);
};

wx.onThemeChange(listener);
wx.offThemeChange(listener); // Pass the same function object used for listening.

onPageNotFound

TIP

The API usage is as follows: wx.onPageNotFound(function listener)
This API is supported by mini programs, but not by mini games.

TIP

  • Developers can redirect pages in callbacks, but they must be processed synchronously in callbacks. Asynchronous processing (such as setTimeout asynchronous execution) is invalid.
  • If the developer does not call wx.onPageNotFound to bind the listener, and does not declare App.onPageNotFound, when the jump page does not exist, the host client's native page does not exist prompt page will be pushed in.
  • If the callback redirects to another non-existent page, the host client's native page does not exist prompt page will be pushed in, and no second callback will be made.
  • Functional description: Listen for the event that the page to be opened by the applet does not exist. This event is related to App.onPageNotFound The callback timing is consistent.
  • Parameters and descriptions: Object res parameter, function listener, listener function for the event that the page to be opened by the mini program does not exist.
PropertiesTypeDescription
pathStringPath of the non-existent page (code package path)
queryObjectQuery parameter for opening a non-existent page
isEntryPagebooleanIs it the first page launched this time (for example, from the sharing entrance, the first page is the sharing page configured by the developer)

offPageNotFound

TIP

The API usage is as follows: wx.offPageNotFound(function listener)
This API is supported by mini programs, but not by mini games.

  • Functional description: Remove the listener function for the event that the page to be opened by the mini program does not exist.
  • Parameters and descriptions: function listener,onPageNotFound The listening function passed in. If this parameter is not passed, all listening functions will be removed.
  • Sample code:
js
const listener = function (res) {
  console.log(res);
};

wx.onPageNotFound(listener);
wx.offPageNotFound(listener); // Pass the same function object used for listening.

onAppShow

TIP

The API usage is as follows: wx.onAppShow(function listener)
This API is supported by mini programs, but not by mini games.

TIP

Some versions will return undefined when there is no referrerInfo. It is recommended to use options.referrerInfo && options.referrerInfo.appId to judge.

  • Functional description: Listen for the mini program to switch to the foreground event. This event is related to App.onShowThe callback parameters are consistent.

  • Parameters and descriptions: Object res parameter, function listener, listener function for the mini program switching to the foreground event.

    PropertiesTypeDescription
    pathStringThe path (code package path) of the Mini Program
    sceneNumberThe scene value of the Mini Program
    queryObjectThe query parameter of the Mini Program
    shareTicketStringshareTicket
    referrerInfoObjectSource information. Returned when entering a mini program from another mini program or app. Otherwise returns {}. For details, see the note in the previous table.
    forwardMaterialsArray.<Object>Opened file information array
    • referrerInfo structure

      PropertiesTypeDescription
      appIdStringSource applet or App's appId
      extraDataObjectData passed from the source applet
    • forwardMaterials structure

      PropertiesTypeDescription
      typeStringMimetype type of the file
      nameObjectFile name
      pathstringFile path
      sizenumberFile size
  • Scenario for returning valid referrerInfo

    PropertiesTypeDescription
    1037Mini Program Open Mini ProgramSource Mini Program
    1038Returned from another Mini ProgramSource Mini Program

offAppShow

TIP

The API usage is as follows: wx.offAppShow(function listener)
This API is supported by mini programs, but not by mini games.

  • Functional description: Remove the listener function for the event that the page to be opened by the mini program does not exist.

  • Parameters and descriptions: function listener,Listener function passed in onAppShow. If this parameter is not passed, all listeners will be removed.

  • Sample code:

js
const listener = function (res) {
  console.log(res);
};

wx.onAppShow(listener);
wx.offAppShow(listener); // Pass the same function object used for listening.

onAppHide

TIP

The API usage is as follows: wx.onAppHide(function listener)
This API is supported by mini programs, but not by mini games.

  • Functional description: Listen for the mini program switching to the background event. This event is related to App.onHide The callback parameters are consistent.
  • Parameters and descriptions: function listener,Listener function for the mini program switching to the background event.

offAppHide

TIP

The API usage is as follows: wx.offAppHide(function listener)
This API is supported by mini programs, but not by mini games.

  • Functional description: Remove the listener function for the mini program switching to the foreground event
  • Parameters and descriptions: function listener,Listener function passed in onAppHide. If this parameter is not passed, all listeners will be removed.
js
const listener = function (res) {
  console.log(res);
};

wx.onAppHide(listener);
wx.offAppHide(listener); //  the same function object used for listening.

onShow

TIP

The API usage is as follows: wx.onShow(function listener)
This API is only supported by mini-games.

  • Functional description: Event listener function for mini-games returning to the foreground.
  • Parameters and descriptions:Object res parameter, function listener, listener function for mini-games returning to the foreground.
PropertiesTypeDescription
scenenumberScene value
queryObjectQuery parameter
shareTicketstringshareTicket
referrerInfoObjectSource information. This field is returned when entering a mini-program from another mini-program or App.
  • referrerInfo structure
PropertiesTypeDescription
appIdstringSource applet or App's appId
extraDataObjectData passed from the source applet

offShow

TIP

The API usage is as follows: wx.offShow(function listener)
This API is only supported by mini-games.

  • Functional description: Remove the listener function for the mini-game returning to the foreground.
  • Parameters and descriptions:function listener, the listener function passed in by onShow. If this parameter is not passed, all listeners are removed.
  • Subpackage example code:
js
const listener = function (res) { console.log(res) }

wx.onShow(listener)
wx.offShow(listener) // Must  the same function object used in onShow

onHide

TIP

The API usage is as follows: wx.onHide(function listener)
This API is only supported by mini-games.

  • Functional description: Listen for mini-games hiding in the background. This event is triggered by operations such as locking the screen and pressing the HOME key to exit to the desktop.
  • Parameters and descriptions:function listener, the listener function for mini-games hiding in the background.
  • Subpackage example code:

offHide

TIP

The API usage is as follows: wx.offHide(function listener)
This API is only supported by mini-games.

  • Functional description: Remove the listener function for the mini-game hiding in the background event
  • Parameters and descriptions:function listener, the listener function passed in by onHide. If this parameter is not passed, all listeners are removed.
js
const listener = function (res) { console.log(res) }

wx.onHide(listener)
wx.offHide(listener) // Must pass the same function object used in onHide

onUnhandledRejection

TIP

The API usage is as follows: wx.onUnhandledRejection(function listener)
This API is supported by mini programs, but not by mini games.

TIP

All unhandledRejection can be captured by this listener, but only the Error type will trigger an alarm in the mini program background.

  • Functional description: Listen for unhandled Promise rejection events.
  • Parameters and descriptions: Object res parameter, function listener, listener function for unhandled Promise rejection events.
PropertiesTypeDescription
reasonStringReason for rejection, usually an Error object
promisePromise.<any>Rejected Promise object

offUnhandledRejection

TIP

The API usage is as follows: wx.offUnhandledRejection(function listener)
This API is supported by mini programs, but not by mini games.

  • Functional description: Remove the listener function for unhandled Promise rejection events

  • Parameters and descriptions: function listener,Listener function passed in onUnhandledRejection. If this parameter is not passed, all listeners will be removed.

  • Sample code:

js
const listener = function (res) {
  console.log(res);
};

wx.onUnhandledRejection(listener);
wx.offUnhandledRejection(listener); // Pass the same function object used for listening.

Debugging

setEnableDebug

TIP

The API usage is as follows: wx.setEnableDebug(Object object)
This API is supported by mini programs, but not by mini games.

  • Functional description: Set whether to turn on the debug switch. This switch is also effective for the official version.

  • Parameters and descriptions: Object object。

    PropertiesTypeDefault valueRequiredDescription
    enableDebugboolean-NoWhether to open debugging
    successFunction-NoCallback function for successful interface call
    failFunction-NoCallback function for failed interface call
    completeFunction-NoCallback function for interface call completion (executed regardless of success or failure)
  • Sample code:

js
// open
wx.setEnableDebug({
  enableDebug: true,
});

// close
wx.setEnableDebug({
  enableDebug: false,
});

Description

To open debugging in the official version, you can also open debugging in the development version or experience version first, and then switch to the official version to see vConsole.

getRealtimeLogManager

TIP

The API usage is as follows: RealtimeLogManager wx.getRealtimeLogManager().
This API is supported by mini programs, but not by mini games.

  • Functional description: Gets the real-time log manager object.

  • Return value: RealtimeLogManager

  • Sample code:

js
// For the mini program
const logger = wx.getRealtimeLogManager();
logger.info({ str: "hello world" }, "info log", 100, [1, 2, 3]);
logger.error({ str: "hello world" }, "error log", 100, [1, 2, 3]);
logger.warn({ str: "hello world" }, "warn log", 100, [1, 2, 3]);

// For the plugin. Supported on the basic library 2.16.0 and later versions, and only reporting in the new key-value format is allowed.
const logManager = wx.getRealtimeLogManager();
const logger = logManager.tag("plugin-log1");
logger.info("key1", "value1");
logger.error("key2", { str: "value2" });
logger.warn("key3", "value3");

getLogManager

TIP

The API usage is as follows: LogManager wx.getLogManager(Object object)
This API is supported by mini programs, but not by mini games.

  • Functional description: Get the log manager object.

  • Parameters and descriptions: Object object。

    PropertiesTypeDefault valueRequiredDescription
    levelnumber0NoThe value is 0/1. The value of 0 means that the life cycle functions of App and Page and the function calls under the namespace will be written to the log. The value of 1 means not. The default value is 4
  • Return value: LogManager

  • Sample code:

js
const logger = wx.getLogManager({ level: 1 });
logger.log({ str: "hello world" }, "basic log", 100, [1, 2, 3]);
logger.info({ str: "hello world" }, "info log", 100, [1, 2, 3]);
logger.debug({ str: "hello world" }, "debug log", 100, [1, 2, 3]);
logger.warn({ str: "hello world" }, "warn log", 100, [1, 2, 3]);

console

console is a global object that can be directly accessed. Its specific method set is as follows. You can print logs in the IDE debug panel and use vConsole to output logs in the client.

debug

TIP

The API usage is as follows: console.debug()

  • Functional description: Print debug logs to the debug panel.
  • Parameters and descriptions: any ... args, log content, can be any number.
error

TIP

The API usage is as follows: console.error()

  • Functional description: Print error to the debug panel.
  • Parameters and descriptions: any ... args, log content, can be any number.
group

TIP

The API usage is as follows: console.group()

Description

Only valid in the tool, in vConsole, it is implemented as an empty function.

  • Functional description: Create a new group in the debug panel. The content output later will be added with an indent, indicating that the content belongs to the current group. The group ends after calling console.groupEnd.
  • Parameters and descriptions: string label,Group marker, optional.
groupEnd

TIP

The API usage is as follows: console.groupEnd()

Description

Only valid in the tool, in vConsole, it is implemented as an empty function.

  • Functional description: End the group created by console.group.
info

TIP

The API usage is as follows: console.info

  • Functional description: Print info to the debug panel.
  • Parameters and descriptions: any ... args, log content, can be any number.
log

TIP

The API usage is as follows: console.log()

  • Functional description: Print log to the debug panel.
  • Parameters and descriptions: any ... args, log content, can be any number.
warn

TIP

The API usage is as follows: console.warn()

Description

Due to the limited functionality of vConsole and the different support for console methods by different clients, it is recommended that developers only use the methods provided in this document in mini-programs.

  • Functional description: Print warn to the debug panel.
  • Parameters and descriptions: any ... args, log content, can be any number.

LogManager

debug

TIP

The API usage is as follows: LogManager.debug()

  • Functional description: Write debug logs
  • Parameters and descriptions: Object|Array|number|string ... args, Log content, can be any number. The total size of the parameters for each call does not exceed 100Kb.
info

TIP

The API usage is as follows: LogManager.info()

  • Functional description: Write info logs
  • Parameters and descriptions: Object|Array.\ |number|string ...args, Log content, can be any number. The total size of the parameters for each call does not exceed 100Kb.
log

TIP

The API usage is as follows: LogManager.log()

  • Functional description: Write log logs
  • Parameters and descriptions: Object|Array.\ |number|string ...args, Log content, can be any number. The total size of the parameters for each call does not exceed 100Kb.
warn

TIP

The API usage is as follows: LogManager.warn()

Description

  • Save up to 5M of log content, after exceeding 5M, the old log content will be deleted.
  • Users can upload printed logs by using open-type='feedback' of the <Button> component, and developers can view it through the 'Feedback Management' page on the left menu of the Mini Program Management Backend.
  • The basic library will write the lifecycle functions of App and Page and the function calls under the namespace into the log by default.
  • Functional description: Write warn logs
  • Parameters and descriptions: Object|Array.\ |number|string ...args, Log content, can be any number. The total size of the parameters for each call does not exceed 100Kb.
addFilterMsg

TIP

The API usage is as follows: RealtimeLogManager.addFilterMsg(string msg)
This API is supported by mini programs, but not by mini games.

  • Functional description: Add filter keywords
  • Parameters and descriptions: string msg,It is the addition interface of setFilterMsg. It is used to set multiple filter keywords.
error

TIP

The API usage is as follows: RealtimeLogManager.error()

  • Functional description: Write error logs
  • Parameters and descriptions: Object|Array.<any>|number|string ...args,Log content, can be any number. The total size of the parameters for each call does not exceed 5Kb.
getCurrentState

TIP

The API usage is as follows: Object RealtimeLogManager.getCurrentState()

TIP

The basic library will add some structured data when reporting logs. If there is a report overflow, a warning log will also be added. Therefore, the current occupancy information obtained by this method will be larger than expected.

  • Functional description: The real-time log will aggregate and report the logs cached within a certain time interval. If the cached content exceeds the limit during this time, it will be discarded. This method can obtain the current remaining cache space.

  • Parameters and descriptions: Object

    | Properties | Type | Description |
    | ------------------------------- | :----------------------------: | :-----------------------------: |
    | size                            |             number             |  The space used in the current cache, in bytes  |
    | maxSize                         |             Number             |  The maximum available space in the current cache, in bytes  |
    | logCount                        |             Number             |  The number of logs in the current cache  |
    | maxLogCount                     |             Number             |  The maximum number of logs that can be stored in the current cache  |
    
in

TIP

The API usage is as follows: RealtimeLogManager.in(Page pageInstance)

  • Functional description: Set the page where the real-time log page parameter is located.
  • Parameters and descriptions: Page pageInstance page instance.
info

TIP

The API usage is as follows: RealtimeLogManager.info()

  • Functional description: Write info logs
  • Parameters and descriptions: Object|Array.<any>|number|string ...args,Log content, can be any number. The total size of the parameters for each call does not exceed 5Kb.
setFilterMsg

TIP

The API usage is as follows: RealtimeLogManager.setFilterMsg(string msg)

  • Functional description: Set filter keywords
  • Parameters and descriptions: string msg,Filter keywords, no more than 1Kb, you can search for the corresponding logs in the applet management background according to the set content.

RealtimeLogManager

addFilterMsg

TIP

The API usage is as follows: RealtimeLogManager.addFilterMsg(string msg)
This API is supported by mini programs, but not by mini games.

  • Functional description: Add filter keywords
  • Parameters and descriptions: string msg,It is the addition interface of setFilterMsg. It is used to set multiple filter keywords.
error

TIP

The API usage is as follows: RealtimeLogManager.error()

  • Functional description: Write error logs
  • Parameters and descriptions: Object|Array.<any>|number|string ...args,Log content, can be any number. The total size of the parameters for each call does not exceed 5Kb.
getCurrentState

TIP

The API usage is as follows: Object RealtimeLogManager.getCurrentState()

TIP

The basic library will add some structured data when reporting logs. If there is a report overflow, a warning log will also be added. Therefore, the current occupancy information obtained by this method will be larger than expected.

  • Functional description: The real-time log will aggregate and report the logs cached within a certain time interval. If the cached content exceeds the limit during this time, it will be discarded. This method can obtain the current remaining cache space.

  • Parameters and descriptions: Object

    | Properties | Type | Description |
    | ------------------------------- | :----------------------------: | :-----------------------------: |
    | size                            |             number             |  The space used in the current cache, in bytes  |
    | maxSize                         |             Number             |  The maximum available space in the current cache, in bytes  |
    | logCount                        |             Number             |  The number of logs in the current cache  |
    | maxLogCount                     |             Number             |  The maximum number of logs that can be stored in the current cache  |
    
in

TIP

The API usage is as follows: RealtimeLogManager.in(Page pageInstance)

  • Functional description: Set the page where the real-time log page parameter is located.
  • Parameters and descriptions: Page pageInstance page instance.
info

TIP

The API usage is as follows: RealtimeLogManager.info()

  • Functional description: Write info logs
  • Parameters and descriptions: Object|Array.<any>|number|string ...args,Log content, can be any number. The total size of the parameters for each call does not exceed 5Kb.
setFilterMsg

TIP

The API usage is as follows: RealtimeLogManager.setFilterMsg(string msg)

  • Functional description: Set filter keywords
  • Parameters and descriptions: string msg,Filter keywords, no more than 1Kb, you can search for the corresponding logs in the applet management background according to the set content.
warn

TIP

The API usage is as follows: RealtimeLogManager.warn()

  • Functional description: Write warn logs
  • Parameters and descriptions: Object|Array.<any>|number|string ...args,Log content, can be any number. The total size of the parameters for each call does not exceed 5Kb.

RealtimeTagLogManager

addFilterMsg

TIP

The API usage is as follows: RealtimeTagLogManager.addFilterMsg(string msg)

  • Functional description: Add filter keywords
  • Parameters and descriptions: string msg,It is the addition interface of setFilterMsg. It is used to set multiple filter keywords.
error

TIP

The API usage is as follows: RealtimeTagLogManager.error(string key, Object]Array.<any> number string value)

  • Functional description: Write error logs
  • Parameters and descriptions: _ string key,Log key; _ Object|Array.<any>|number|string value,Log value, the total size of the parameters called each time does not exceed 5Kb.
info

TIP

The API usage is as follows: RealtimeTagLogManager.info(string key, Object Array.<any> number string value)

  • Functional description: Write info logs
  • Parameters and descriptions: _ string key,Log key; _ Object|Array.<any>|number|string value,Log value, the total size of the parameters called each time does not exceed 5Kb.
setFilterMsg

TIP

The API usage is as follows: RealtimeTagLogManager.setFilterMsg(string msg)

  • Functional description: Set filter keywords
  • Parameters and descriptions: string msg,Filter keywords, no more than 1Kb, you can search for the corresponding logs in the applet management background according to the set content.
info

TIP

The API usage is as follows: RealtimeTagLogManager.warn(string key, ObjectJArray.<any> number string value)

  • Functional description: Write warn logs
  • Parameters and descriptions: _ string key,Log key; _ Object|Array.<any>|number|string value,Log value, the total size of the parameters called each time does not exceed 5Kb.

Performance

TIP

This API is only supported by mini-games.

triggerGC

TIP

The API usage is as follows: wx.triggerGC()

  • Functional description: Speed ​​up the triggering of JavaScriptCore Garbage Collection. The GC timing is controlled by JavaScriptCore, and it cannot be guaranteed that GC will be triggered immediately after the call.

getPerformance

TIP

The API usage is as follows: wx.getPerformance()

  • Functional description: Get the performance manager
  • Return value: Performance, a performance manager object

Performance

.now

TIP

The API usage is as follows: Performance.now()

  • Functional description: You can get the timestamp of the current time in microseconds.
  • Return value: number, timestamp

Subpackage loading

TIP

This API is only supported by mini-games.

preDownloadSubpackage

TIP

The API usage is as follows: wx.preDownloadSubpackage(Object object)

  • Functional description: Trigger subpackage pre-download
  • Parameters and descriptions: Object object。
PropertiesTypeDefault valueRequiredDescription
packageTypestring'normal'NoSubpackage type, after filling in "workers", the name field becomes invalid.
namestringYesSubpackage name, you can fill in name or root. In an independent subpackage, fill in __GAME__ to load the main package.
successfunctionYesSubpackage loading success callback event
failfunctionYesSubpackage loading failure callback event
completefunctionYesSubpackage loading end callback event (both successful and failed loading will be executed)
  • Return value: PreDownloadSubpackageTask , pre-download subpackage task instance, used to obtain the subpackage pre-download status.
  • Things To Note: The difference between wx.preDownloadSubpackage and wx.loadSubpackage: wx.preDownloadSubpackage only downloads the code package and does not automatically execute the code; wx.loadSubpackage automatically executes the code after downloading the code package.
  • Sample code:

workerSubpackage example code:

js
 // Configure workers as a subpackage in app.json / game.json first
{
  "workers": {
    "path": "myWorkersFolder",
    "isSubpackage": true // true means the worker is packaged as a subpackage Default value: False. If false, it is equivalent to { "workers": "myWorkersFolder" }
  }
}
js
// Call wx.preDownloadSubpackage to download the worker subpackage. Only after the download is successful can you create the worker
var task = wx.preDownloadSubpackage({
  packageType: "workers",
  success(res) {
    console.log("load worker success", res);
    wx.createWorker("myWorkersFolder/request/index.js"); // Create worker. If the worker subpackage is not fully downloaded, calling createWorker will result in an error.
  },
  fail(res) {
    console.log("load worker fail", res);
  },
});

task.onProgressUpdate((res) => {
  console.log(res.progress); // Listen to download progress using onProgressUpdate
  console.log(res.totalBytesWritten);
  console.log(res.totalBytesExpectedToWrite);
});

Ordinary subpackage example code:

js
  // Configure the subpackage in app.json / game.json first
{
    "subPackages": [
      {
        "name": "ModuleA",
        "root": "/ModuleA/"
      }
    ]
}
js
var task = wx.preDownloadSubpackage({
  name: "ModuleA",
  success(res) {
    console.log("load subpackage success", res);
    // Execute the subpackage code
    wx.loadSubpackage({
      name: "ModuleA",
      success(res) {
        console.log(res);
      },
    });
  },
  fail(res) {
    console.log("load subpackage fail", res);
  },
});

task.onProgressUpdate((res) => {
  console.log(res.progress); // Listen to download progress using onProgressUpdate
  console.log(res.totalBytesWritten);
  console.log(res.totalBytesExpectedToWrite);
});

PreDownloadSubpackageTask

.onProgressUpdate

TIP

The API usage is as follows: PreDownloadSubpackageTask.onProgressUpdate(function listener)

  • Functional description: Listen to subpackage loading progress change events.
  • Parameters and descriptions: function listener,, the listener function of subpackage loading progress change events, the parameter Object.res is as follows:
PropertiesTypeDescription
progressnumberSubpackage download progress percentage
totalBytesWrittennumberDownloaded data length, unit Bytes
totalBytesExpectedToWritenumberExpected total length of data to be downloaded, unit Bytes

loadSubpackage

TIP

The API usage is as follows: wx.loadSubpackage(Object object)

  • Functional description: Trigger subpackage loading.
  • Parameters and descriptions: Object object。
PropertiesTypeDefault valueRequiredDescription
packageTypestring'normal'NoSubpackage type, after filling in "workers", the name field becomes invalid.
namestringYesSubpackage name, you can fill in name or root. In an independent subpackage, fill in __GAME__ to load the main package.
successfunctionYesSubpackage loading success callback event
failfunctionYesSubpackage loading failure callback event
completefunctionYesSubpackage loading end callback event (both successful and failed loading will be executed)
  • Return value: LoadSubpackageTask Load subpackage task instance, used to get subpackage loading status。
  • Things To Note: The difference between wx.preDownloadSubpackage and wx.loadSubpackage: wx.preDownloadSubpackage only downloads the code package and does not automatically execute the code; wx.loadSubpackage automatically executes the code after downloading the code package.

LoadSubpackageTask

.onProgressUpdate

TIP

The API usage is as follows: LoadSubpackageTask.onProgressUpdate(function listener)

  • Functional description: Listen to subpackage loading progress change events.
  • Parameters and descriptions: function listener,, the listener function of subpackage loading progress change events, the parameter Object.res is as follows:
PropertiesTypeDescription
progressnumberSubpackage download progress percentage
totalBytesWrittennumberDownloaded data length, unit Bytes
totalBytesExpectedToWritenumberExpected total length of data to be downloaded, unit Bytes