Skip to content

基礎

canIUse

TIP

該API使用方法為:Boolean wx.canIUse(string schema)

  • 功能說明: 判斷小程序的API,回檔,參數,組件等是否在當前版本可用。
  • 參數及說明: String schema
    • 使用 ${API}.${method}.${param}.${options} 或 ${component}.${attribute}.${option} 方式來呼叫。
    • 參數說明:
      參數說明:說明
      ${API}代表API名字
      ${method}代表調用管道,有效值為return, success,object,callback
      ${param}代表參數或者返回值
      ${options}代表參數的可選值
      ${component}代表組件名字
      ${attribute}代表組件内容
      ${option}代表組件内容的可選值
  • 返回值: Boolean, 表達當前版本是否可用。
  • 示例代碼:
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

該API使用方法為: wx.env

  • 功能說明: 環境變量
  • 參數及說明: string USER_DATA_PATH,文件系統中的用戶目錄路徑(本地路徑)。

base64ToArrayBuffer

TIP

該API使用方法為: ArrayBuffer wx.base64ToArrayBuffer(string base64)

  • 功能說明: 將Base64字串轉成ArrayBuffer對象
  • 參數及說明: string base64,要轉化成ArrayBuffer對象的Base64字串。
  • 返回值: ArrayBuffer, ArrayBuffer對象。
  • 示例代碼:
js
const base64 = "CxYh";
const arrayBuffer = wx.base64ToArrayBuffer(base64);

arrayBufferToBase64

TIP

該API使用方法為: string wx.arrayBufferToBase64(ArrayBuffer arrayBuffer)
該API小程序支持,小遊戲暫不支持

  • 功能說明: 將ArrayBuffer對象轉成Base64字串
  • 參數及說明: ArrayBuffer arrayBuffer, 要轉換成Base64字串的ArrayBuffer對象。
  • 返回值: string,Base64字串。
  • 示例代碼:
js
const arrayBuffer = new Uint8Array([11, 22, 33]);
const base64 = wx.arrayBufferToBase64(arrayBuffer);

系統

getSystemInfo

TIP

該API使用方法為: wx.getSystemInfo(Object object)

  • 功能說明: 獲取系統資訊

  • 參數及說明: Object Object

    内容類型預設值必填說明
    successFunction-接口調用成功的回呼函數
    failFunction-接口調用失敗的回呼函數
    completeFunction-接口調用結束的回呼函數(無論成功與否都執行)
    • Object.success的res回檔結果

      内容類型說明
      brandString設備品牌
      modelString設備型號
      pixelRatioNumber設備點數比
      screenWidthNumber荧幕寬度,單位px
      screenHeightNumber荧幕高度,單位px
      windowWidthNumber可使用視窗寬度,單位px
      windowHeightNumber可使用視窗高度,單位px
      statusBarHeightNumber狀態列的高度,單位px
      languageString語言
      versionString版本號
      systemString作業系統及版本
      platformString用戶端平臺,其合法值如下
      1. ios:iOS用戶端(包含iPhone、iPad)
      2. android:Android用戶端
      3. devtools:Luffa Cloud開發者工具
      fontSizeSettingnumber用戶字體大小,單位px
      SDKVersionString用戶端基礎庫版本
      AppPlatformStringApp平臺
      safeAreaObject在豎屏正方向下的安全區域
      themeString系統當前主題,取值為light或dark,全局配置'darkmode':true時才能獲取,否則為undefined
    • res.safeArea的結構:

      内容類型說明
      leftNumber安全區域左上角橫坐標
      rightNumber安全區域右下角橫坐標
      topNumber安全區域左上角縱坐標
      bottomNumber安全區域右下角縱坐標
      widthNumber安全區域的寬度,單位邏輯點數
      heightNumber安全區域的高度,單位邏輯點數
  • 示例代碼:

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

該API使用方法為: Object wx.getSystemInfoSync()

  • 功能說明: wx.getSystemInfo 的同步版本
  • Object.success的res回檔結果
内容類型說明
brandString設備品牌
modelString設備型號
pixelRatioNumber設備點數比
screenWidthNumber荧幕寬度,單位px
screenHeightNumber荧幕高度,單位px
windowWidthNumber可使用視窗寬度,單位px
windowHeightNumber可使用視窗高度,單位px
statusBarHeightNumber狀態列的高度,單位px
languageString語言
versionString版本號
systemString作業系統及版本
platformString用戶端平臺,其合法值如下
1. ios:iOS用戶端(包含iPhone、iPad)
2. android:Android用戶端
3. devtools:Luffa Cloud開發者工具
fontSizeSettingnumber用戶字體大小,單位px
SDKVersionString用戶端基礎庫版本
AppPlatformStringApp平臺
safeAreaObject在豎屏正方向下的安全區域
themeString系統當前主題,取值為light或dark,全局配置'darkmode':true時才能獲取,否則為undefined
  • res.safeArea的結構:
内容類型說明
leftNumber安全區域左上角橫坐標
rightNumber安全區域右下角橫坐標
topNumber安全區域左上角縱坐標
bottomNumber安全區域右下角縱坐標
widthNumber安全區域的寬度,單位邏輯點數
heightNumber安全區域的高度,單位邏輯點數
  • 示例代碼:
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

該API使用方法為: wx.getSystemInfoAsync(Object object)

  • 功能說明: 非同步獲取系統資訊。 需要一定的宿主用戶端版本支持,在不支持的用戶端上,會使用同步實現來返回。

  • 參數及說明: Object Object。

    内容類型預設值必填說明
    successFunction-接口調用成功的回呼函數
    failFunction-接口調用失敗的回呼函數
    completeFunction-接口調用結束的回呼函數(無論成功與否都執行)
    • object.success回呼函數參數: Object res

      内容類型說明
      brandString設備品牌
      modelString設備型號
      pixelRatioNumber設備點數比
      screenWidthNumber荧幕寬度,單位px
      screenHeightNumber荧幕高度,單位px
      windowWidthNumber可使用視窗寬度,單位px
      windowHeightNumber可使用視窗高度,單位px
      statusBarHeightNumber狀態列的高度,單位px
      languageString語言
      versionString版本號
      systemString作業系統及版本
      platformString用戶端平臺,其合法值如下
      1. ios:iOS用戶端(包含iPhone、iPad)
      2. android:Android用戶端
      3. devtools:Luffa Cloud開發者工具
      fontSizeSettingnumber用戶字體大小,單位px
      SDKVersionString用戶端基礎庫版本
      safeAreaObject在豎屏正方向下的安全區域,部分機型沒有安全區域概念,也不會返回safeArea欄位,開發者需自行相容,返回值請參攷下錶safeArea返回值
      themeString系統當前主題,取值為light或dark,全局配置'darkmode':true時才能獲取,否則為undefined
      light:明亮
      dark:黑暗
    • res.safeArea的結構:

      内容類型說明
      leftNumber安全區域左上角橫坐標
      rightNumber安全區域右下角橫坐標
      topNumber安全區域左上角縱坐標
      bottomNumber安全區域右下角縱坐標
      widthNumber安全區域的寬度,單位邏輯點數
      heightNumber安全區域的高度,單位邏輯點數
  • 示例代碼:

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

該API使用方法為: Object wx.getWindowInfo()

  • 功能說明: 獲取視窗資訊
  • 參數及說明: Object。
内容類型說明
pixelRatioNumber設備點數比
screenWidthNumber荧幕寬度,單位px
screenHeightNumber荧幕高度,單位px
windowWidthNumber可使用視窗寬度,單位px
windowHeightNumber可使用視窗高度,單位px
statusBarHeightNumber狀態列的高度,單位px
safeAreaObject在豎屏正方向下的安全區域,部分機型沒有安全區域概念,也不會返回safeArea欄位,開發者需自行相容,返回值請參攷下錶safeArea返回值
screenTopnumber視窗上邊緣的y值
  • safeArea返回值
内容類型說明
leftNumber安全區域左上角橫坐標
rightNumber安全區域右下角橫坐標
topNumber安全區域左上角縱坐標
bottomNumber安全區域右下角縱坐標
widthNumber安全區域的寬度,單位邏輯點數
heightNumber安全區域的高度,單位邏輯點數
  • 示例代碼:
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

該API使用方法為: Object wx.getSystemSetting()
該API小程序支持,小遊戲暫不支持

  • 功能說明: 獲取設備設定
  • 參數及說明: Object。
内容類型說明
bluetoothEnabledboolean藍牙的系統開關
locationEnabledboolean地理位置的系統開關
wifiEnabledbooleanWi-Fi的系統開關
deviceOrientationstring設備方向,其合法值為:
1.portrait:豎屏
2.landscape:橫屏
  • 示例代碼:
js
const systemSetting = wx.getSystemSetting();

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

openSystemBluetoothSetting

TIP

該API使用方法為: wx.openSystemBluetoothSetting(Object object)
該API小程序支持,小遊戲暫不支持

  • 功能說明: 跳轉系統藍牙設定頁。 僅支持Android。

  • 參數及說明: Object object。

    内容類型預設值必填說明
    successFunction-接口調用成功的回呼函數
    failFunction-接口調用失敗的回呼函數
    completeFunction-接口調用結束的回呼函數(無論成功與否都執行)
  • 示例代碼:

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

openAppAuthorizeSetting

TIP

該API使用方法為: wx.openAppAuthorizeSetting(Object object)
該API小程序支持,小遊戲暫不支持

  • 功能說明: 跳轉系統宿主用戶端授權管理頁。

  • 參數及說明: Object object。

    内容類型預設值必填說明
    successFunction-接口調用成功的回呼函數
    failFunction-接口調用失敗的回呼函數
    completeFunction-接口調用結束的回呼函數(無論成功與否都執行)
  • 示例代碼:

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

getRendererUserAgent

TIP

該API使用方法為: Promise wx.getRendererUserAgent(Object object)
該API小程序支持,小遊戲暫不支持

  • 功能說明: 獲取Webview小程序的UserAgent。

  • 參數及說明: Object object。

    内容類型預設值必填說明
    successFunction-接口調用成功的回呼函數
    failFunction-接口調用失敗的回呼函數
    completeFunction-接口調用結束的回呼函數(無論成功與否都執行)
  • object.success回呼函數參數: string userAgent,UserAgent。

  • 返回值: Promise.<string>。

  • 示例代碼:

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

getDeviceInfo

TIP

該API使用方法為: Object wx.getDeviceInfo()
該API小程序支持,小遊戲暫不支持

  • 功能說明: 獲取設備基礎資訊。

  • 返回值: Object。

    内容類型說明
    abistring宿主App二進位接口類別型(僅Android支持)
    deviceAbistring設備效能等級(僅Android支持),合法值為:
    -2或0:該設備無法運行小遊戲
    -1:效能未知
    >=1:設備效能值,該值越高,設備效能越好,現時最高不到50
    benchmarkLevelnumberWi-Fi的系統開關
    brandstring設備品牌
    modelstring設備型號
    systemstring作業系統及版本
    platformstring用戶端平臺
    cpuTypestring設備CPU型號(僅Android支持) GPU型號可通過WebGLRenderingContext.getExtension('WEBGL_debug_renderer_info')來獲取
    menorySizestring設備記憶體大小,單位為MB
    • 示例代碼:
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

該API使用方法為: Object wx.getAppBaseInfo()
該API小程序支持,小遊戲暫不支持

  • 功能說明: 獲取宿主用戶端基礎資訊

  • 參數及說明: Object。

    内容類型說明
    SDKVersionstring宿主用戶端基礎庫版本
    enableDebugboolean是否已打開調試。 可通過右上角選單或wx.setEnableDebug打開調試
    hostObject當前小程序運行的宿主環境
    languagestring宿主用戶端設定的語言
    versionstring宿主用戶端版本號
    themestring系統當前主題,取值為`light:明亮模式`或`dark:暗黑模式`,全局配置`'darkmode':true`時才能獲取,否則為undefined(不支持小遊戲)
    • 示例代碼:
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

該API使用方法為: Object wx.getAppAuthorizeSetting()
該API小程序支持,小遊戲暫不支持

  • 功能說明: 獲取宿主用戶端授權設定

  • 參數及說明: Object。

    内容類型說明
    albumAuthorized'authorized'/'denied'/'not determined'允許宿主用戶端使用相册的開關(僅iOS有效)
    bluetoothAuthorized'authorized'/'denied'/'not determined'允許宿主用戶端使用藍牙的開關(僅iOS有效)
    cameraAuthorized'authorized'/'denied'/'not determined'允許宿主用戶端使用監視器的開關
    locationAuthorized'authorized'/'denied'/'not determined'允許宿主用戶端使用定位的開關
    locationReducedAccuracyboolean定位準確度。 true表示模糊定位,false表示精確定位(僅iOS有效)
    microphoneAuthorized'authorized'/'denied'/'not determined'允許宿主用戶端使用麥克風的開關
    notificationAuthorized'authorized'/'denied'/'not determined'允許宿主用戶端通知的開關
    notificationAlertAuthorized'authorized'/'denied'/'not determined'允許宿主用戶端通知帶有提醒的開關(僅iOS有效)
    notificationBadgeAuthorized'authorized'/'denied'/'not determined'允許宿主用戶端通知帶有標記的開關(僅iOS有效)
    notificationSoundAuthorized'authorized'/'denied'/'not determined'允許宿主用戶端通知帶有聲音的開關(僅iOS有效)
    phoneCalendarAuthorized'authorized'/'denied'/'not determined'允許宿主用戶端讀寫行事曆的開關
    • 示例代碼:
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);

更新

getUpdateManager

TIP

該API使用方法為: UpdateManager wx.getUpdateManager()

  • 功能說明: 獲取全域唯一的版本更新管理器,用於管理小程序更新,使用方法為UpdateManager wx.getUpdateManager。
  • 返回值: UpdateManager,更新管理器對象

UpdateManager

.applyUpdate

TIP

該API使用方法為: UpdateManager.applyUpdate()

  • 功能說明: 強制小程序重啓並使用新版本。 在小程序新版本下載完成後(即收到onUpdateReady回檔)調用。

.onCheckForUpdate

TIP

該API使用方法為: UpdateManager.onCheckForUpdate(function listener)

  • 功能說明: 監聽向後臺請求檢查更新結果事件。 在小程序冷開機時自動檢查更新,不需由開發者主動觸發。

  • 參數及說明: function callback, 向後臺請求檢查更新結果事件的回呼函數。

    内容類型說明
    hasUpdateBoolean是否有新版本

.onUpdateFailed

TIP

該API使用方法為: UpdateManager.onUpdateFailed(function listener)

  • 功能說明: 監聽小程序更新失敗事件。 小程序有新版本,用戶端主動觸發下載(無需開發者觸發),下載失敗(可能是網絡原因等)後回檔。
  • 參數及說明: function callback, 小程序更新失敗事件的回呼函數。

.onUpdateReady

TIP

該API使用方法為: UpdateManager.onUpdateReady(function listener)

  • 功能說明: 監聽小程序有版本更新事件。 用戶端主動觸發下載(無需開發者觸發),下載成功後回檔。

  • 參數及說明: function callback, 小程序有新版本更新事件的回呼函數

  • 示例代碼:

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

小程序

生命週期

getLaunchOptionsSync

TIP

該API使用方法為: Object wx.getLaunchOptionsSync()
部分版本在無referrerInfo的時候會返回undefined,建議使用options.referrerInfo && options.referrerInfo.appId進行判斷。

  • 功能說明: 獲取小程序啟動時的參數

  • 返回值: Object 啟動參數。

    内容類型說明
    pathString啟動小程序的路徑 (僅小程序支援。)
    sceneNumber啟動小程序的場景值,默認為1001
    queryObject啟動小程序的query參數
    referrerInfoObject來源訊息,從另一個小程序或 App 進入小程序時返回。否則返回{}
    forwardMaterialsArray.<Object>打開的文件資訊數組
    • referrerInfo的結構

      内容類型說明
      appIdString來源小程序或App的appId
      extraDataObject來源小程序傳過來的數據

TIP

這裡的extraData欄位是由調用原生啟動小程序傳入的擴展參數。

iOS:傳入的paramsStr

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

  }];

Android:MiniStartLinkOptions對象的params欄位

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的結構

    内容類型說明
    typeString文件的mimetype類型
    nameObject檔名
    pathstring文件路徑
    sizenumber文件大小
  • 返回有效referrerInfo的場景

    内容類型說明
    1037小程序打開小程序來源小程序
    1038從另一個小程序返回來源小程序

getEnterOptionsSync

TIP

該API使用方法為: Object wx.getEnterOptionsSync()

TIP

部分版本在無referrerInfo的時候會返回undefined,建議使用options.referrerInfo && options.referrerInfo.appId進行判斷。

  • 功能說明: 獲取本次小程序啟動時的參數。 如果當前是冷開機,則返回值與 App.onLaunch 的回檔參數一致; 如果當前是暖開機,則返回值與 App.onShow 一致。

  • 返回值: Object

    内容類型說明
    pathString啟動小程序的路徑(代碼包路徑)
    sceneNumber啟動小程序的場景值
    queryObject啟動小程序的query參數
    shareTicketStringshareTicket
    referrerInfoObject來源資訊。從另一個小程序 或 App 進入小程序時返回。否則回傳 {},具體參見表格前文的注意
    forwardMaterialsArray.<Object>打開的文件資訊數組
    • referrerInfo的結構

      内容類型說明
      appIdString來源小程序或App的appId
      extraDataObject來源小程序傳過來的數據
    • forwardMaterials的結構

      内容類型說明
      typeString文件的mimetype類型
      nameObject檔名
      pathstring文件路徑
      sizenumber文件大小
  • 返回有效referrerInfo的場景

    内容類型說明
    1037小程序打開小程序來源小程序
    1038從另一個小程序返回來源小程序

應用級事件

onError

TIP

該API使用方法為: wx.onError(function callback)
該API小程序支持,小遊戲暫不支持

  • 功能說明: 監聽小程序錯誤事件。 如腳本錯誤或API調用報錯等。
  • 參數及說明: function callback, 小程序錯誤事件的回呼函數。
  • 返回值: string error, 錯誤資訊,包含堆棧。

offError

TIP

該API使用方法為: wx.offError(function callback)
該API小程序支持,小遊戲暫不支持

  • 功能說明: 取消監聽小程序錯誤事件。
  • 參數及說明: function callback, 小程序錯誤事件的回呼函數。

onThemeChange

TIP

該API使用方法為: wx.onThemeChange(function listener)
該API小程序支持,小遊戲暫不支持

說明

只有在全局配置darkmode:true時才會觸發此事件

  • 功能說明: 監聽系統主題改變事件

  • 參數及說明: function listener, 系統主題改變事件的監聽函數

  • 返回值: Object res

    内容合法值及說明類型說明
    theme1.dark:深色主題
    1.light:淺色主題
    String系統當前的主題,取值為light或dark

offThemeChange

TIP

該API使用方法為: wx.offThemeChange(function listener)
該API小程序支持,小遊戲暫不支持

  • 功能說明: 移除系統主題改變事件的監聽函數

  • 參數及說明: function listener, onThemeChange傳入的監聽函數。 不傳此參數則移除所有監聽函數。

  • 示例代碼:

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

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

onPageNotFound

TIP

該API使用方法為: wx.onPageNotFound(function listener)
該API小程序支持,小遊戲暫不支持

TIP

  • 開發者可以在回檔中進行頁面重定向,但必須在回檔中同步處理,非同步處理(例如setTimeout非同步執行)無效。
  • 若開發者沒有調用wx.onPageNotFound綁定監聽,也沒有聲明App.onPageNotFound,當跳轉頁面不存在時,將推入宿主用戶端原生的頁面不存在提示頁面。
  • 如果回檔中又重定向到另一個不存在的頁面,將推入宿主用戶端原生的頁面不存在提示頁面,並且不再第二次回檔。
  • 功能說明: 監聽小程序要打開的頁面不存在事件。 該事件與 App.onPageNotFound 的回檔時機一致。
  • 參數及說明: Object res參數, function listener, 小程序要打開的頁面不存在事件的監聽函數。
内容類型說明
pathString不存在頁面的路徑(代碼包路徑)
queryObject打開不存在頁面的query參數
isEntryPageboolean是否本次啟動的首個頁面(例如從分享等入口進來,首個頁面是開發者配置的分享頁面)

offPageNotFound

TIP

該API使用方法為: wx.offPageNotFound(function listener)
該API小程序支持,小遊戲暫不支持

  • 功能說明: 移除小程序要打開的頁面不存在事件的監聽函數。
  • 參數及說明: function listener,onPageNotFound傳入的監聽函數。 不傳此參數則移除所有監聽函數。
  • 示例代碼:
js
const listener = function (res) {
  console.log(res);
};

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

onAppShow

TIP

該API使用方法為: wx.onAppShow(function listener)
該API小程序支持,小遊戲暫不支持

TIP

部分版本在無referrerInfo的時候會返回undefined,建議使用options.referrerInfo && options.referrerInfo.appId進行判斷。

  • 功能說明: 監聽小程序切前臺事件。 該事件與 App.onShow的回檔參數一致。

  • 參數及說明: Object res參數, function listener, 小程序切前臺事件的監聽函數。

    内容類型說明
    pathString啟動小程序的路徑(代碼包路徑)
    sceneNumber啟動小程序的場景值
    queryObject啟動小程序的query參數
    shareTicketStringshareTicket
    referrerInfoObject來源資訊。從另一個小程序 或 App 進入小程序時返回。否則回傳 {},具體參見表格前文的注意
    forwardMaterialsArray.<Object>打開的文件資訊數組
    • referrerInfo的結構

      内容類型說明
      appIdString來源小程序或App的appId
      extraDataObject來源小程序傳過來的數據
    • forwardMaterials的結構

      内容類型說明
      typeString文件的mimetype類型
      nameObject檔名
      pathstring文件路徑
      sizenumber文件大小
  • 返回有效referrerInfo的場景

    内容類型說明
    1037小程序打開小程序來源小程序
    1038從另一個小程序返回來源小程序

offAppShow

TIP

該API使用方法為: wx.offAppShow(function listener)
該API小程序支持,小遊戲暫不支持

  • 功能說明: 移除小程序要打開的頁面不存在事件的監聽函數。

  • 參數及說明: function listener,onAppShow傳入的監聽函數,不傳此參數則移除所有監聽函數。

  • 示例代碼:

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

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

onAppHide

TIP

該API使用方法為: wx.onAppHide(function listener)
該API小程序支持,小遊戲暫不支持

  • 功能說明: 監聽小程序切後臺事件。 該事件與 App.onHide 的回檔參數一致。
  • 參數及說明: function listener,小程序切後臺事件的監聽函數。

offAppHide

TIP

該API使用方法為: wx.offAppHide(function listener)
該API小程序支持,小遊戲暫不支持

  • 功能說明: 移除小程序切前臺事件的監聽函數
  • 參數及說明: function listener,onAppHide傳入的監聽函數,不傳此參數則移除所有監聽函數。
js
const listener = function (res) {
  console.log(res);
};

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

onShow

TIP

該API使用方法為: wx.onShow(function listener)
此 API 僅小遊戲支援。

  • 功能說明: 小遊戲回到前台的事件監聽函數。
  • 參數及說明:Object res 參數,function listener,小遊戲回到前台的事件的監聽函式。
内容類型說明
scenenumber場景值
queryObject查詢參數
shareTicketstringshareTicket
referrerInfoObject來源資訊。從另一個小程序 或 App 進入小程序時返回此欄位。
  • referrerInfo的結構
内容類型說明
appIdstring來源小程序或App的appId
extraDataObject來源小程序傳過來的數據

offShow

TIP

該API使用方法為: wx.offShow(function listener)
此 API 僅小遊戲支援。

  • 功能說明: 移除小遊戲回到前台的事件的監聽函數。
  • 參數及說明:function listener,onShow 傳入的監聽函式。不傳此參數則移除所有監聽函數。
  • 分包範例程序碼:
js
const listener = function (res) { console.log(res) }

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

onHide

TIP

該API使用方法為: wx.onHide(function listener)
此 API 僅小遊戲支援。

  • 功能說明: 監聽小遊戲隱藏到後台事件。鎖定畫面、按 HOME 鍵退到桌面等操作會觸發此事件。
  • 參數及說明:function listener,小遊戲隱藏到後台事件的監聽函數。
  • 分包範例程序碼:

offHide

TIP

該API使用方法為: wx.offHide(function listener)
此 API 僅小遊戲支援。

  • 功能說明: 移除小遊戲隱藏到背景事件的監聽函數
  • 參數及說明:function listener,onHide 傳入的監聽函式。不傳此參數則移除所有監聽函數。
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

該API使用方法為: wx.onUnhandledRejection(function listener)
該API小程序支持,小遊戲暫不支持

TIP

所有的unhandledRejection都可以被這一監聽捕獲,但只有Error類型的才會在小程序後臺觸發報警。

  • 功能說明: 監聽未處理的Promise拒絕事件。
  • 參數及說明: Object res參數, function listener, 未處理的Promise拒絕事件的監聽函數。
内容類型說明
reasonString拒絕原因,一般是一個Error對象
promisePromise.<any>被拒絕的Promise對象

offUnhandledRejection

TIP

該API使用方法為: wx.offUnhandledRejection(function listener)
該API小程序支持,小遊戲暫不支持

  • 功能說明: 移除未處理的Promise拒絕事件的監聽函數

  • 參數及說明: function listener,onUnhandledRejection傳入的監聽函數。 不傳此參數則移除所有監聽函數。

  • 示例代碼:

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

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

調試

setEnableDebug

TIP

該API使用方法為: wx.setEnableDebug(Object object)
該API小程序支持,小遊戲暫不支持

  • 功能說明: 設定是否打開調試開關。 此開關對正式版也能生效。

  • 參數及說明: Object object。

    内容類型預設值必填說明
    enableDebugboolean-是否打開調試
    successFunction-接口調用成功的回呼函數
    failFunction-接口調用失敗的回呼函數
    completeFunction-接口調用結束的回呼函數(無論成功與否都執行)
  • 示例代碼:

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

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

說明

在正式版打開調試還可以先在開發版或體驗版打開調試,再切到正式版就能看到vConsole。

getRealtimeLogManager

TIP

該API使用方法為: RealtimeLogManager wx.getRealtimeLogManager().
該API小程序支持,小遊戲暫不支持

  • 功能說明: Gets the real-time log manager object.

  • 返回值: RealtimeLogManager

  • 示例代碼:

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

該API使用方法為: LogManager wx.getLogManager(Object object)
該API小程序支持,小遊戲暫不支持

  • 功能說明: 獲取日誌管理器對象。

  • 參數及說明: Object object。

    内容類型預設值必填說明
    levelnumber0取值為0/1,取值為0表示會把App、Page的生命週期函數和命名空間下的函數調用寫入日誌,取值為1則不會,預設值是0
  • 返回值: LogManager

  • 示例代碼:

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是一個可以直接訪問的全域對象,其具體方法集如下。 可以在IDE調試面板中列印日誌,在用戶端中利用vConsole輸出日誌。

debug

TIP

該API使用方法為: console.debug()

  • 功能說明: 向調試面板中列印debug日誌。
  • 參數及說明: any ... args, 日誌內容,可以有任意多個。
error

TIP

該API使用方法為: console.error()

  • 功能說明: 向調試面板中列印error日誌。
  • 參數及說明: any ... args, 日誌內容,可以有任意多個。
group

TIP

該API使用方法為: console.group()

說明

僅在工具中有效,在vConsole中為空函數實現。

  • 功能說明: 在調試面板中創建一個新的分組。 隨後輸出的內容都會被添加一個縮進,表示該內容屬於當前分組。 調用console.groupEnd之後分組結束。
  • 參數及說明: string label,分組標記,可選。
groupEnd

TIP

該API使用方法為: console.groupEnd()

說明

僅在工具中有效,在vConsole中為空函數實現。

  • 功能說明: 結束由console.group創建的分組。
info

TIP

該API使用方法為: console.info

  • 功能說明: 向調試面板中列印info日誌。
  • 參數及說明: any ... args, 日誌內容,可以有任意多個。
log

TIP

該API使用方法為: console.log()

  • 功能說明: 向調試面板中列印log日誌。
  • 參數及說明: any ... args, 日誌內容,可以有任意多個。
warn

TIP

該API使用方法為: console.warn()

說明

由於vConsole功能有限,以及不同用戶端對console方法的支持情况有差异,建議開發者在小程序中只使用本文件中提供的方法。

  • 功能說明: 向調試面板中列印warn日誌。
  • 參數及說明: any ... args, 日誌內容,可以有任意多個。

LogManager

debug

TIP

該API使用方法為: LogManager.debug()

  • 功能說明: 寫debug日誌
  • 參數及說明: Object|Array|number|string ... args, 日誌內容,可以有任意多個。 每次調用的參數的總大小不超過100Kb。
info

TIP

該API使用方法為: LogManager.info()

  • 功能說明: 寫info日誌
  • 參數及說明: Object|Array.\ |number|string ...args, 日誌內容,可以有任意多個。 每次調用的參數的總大小不超過100Kb。
log

TIP

該API使用方法為: LogManager.log()

  • 功能說明: 寫log日誌
  • 參數及說明: Object|Array.\ |number|string ...args, 日誌內容,可以有任意多個。 每次調用的參數的總大小不超過100Kb。
warn

TIP

該API使用方法為: LogManager.warn()

說明

  • 最多保存5M的日誌內容,超過5M後,舊的日誌內容會被删除。
  • 用戶可以通過使用<Button>組件的open-type='feedback'來上傳列印的日誌,開發者可以通過小程序管理後臺左側選單'迴響管理'頁面查看。
  • 基礎庫默認會把App、Page的生命週期函數和命名空間下的函數調用寫入日誌。
  • 功能說明: 寫warn日誌
  • 參數及說明: Object|Array.\ |number|string ...args, 日誌內容,可以有任意多個。 每次調用的參數的總大小不超過100Kb。
addFilterMsg

TIP

該API使用方法為: RealtimeLogManager.addFilterMsg(string msg)
該API小程序支持,小遊戲暫不支持

  • 功能說明: 添加過濾關鍵字
  • 參數及說明: string msg,是setFilterMsg的添加接口。 用於設定多個過濾關鍵字。
error

TIP

該API使用方法為: RealtimeLogManager.error()

  • 功能說明: 寫error日誌
  • 參數及說明: Object|Array.<any>|number|string ...args,日誌內容,可以有任意多個。 每次調用的參數的總大小不超過5Kb。
getCurrentState

TIP

該API使用方法為: Object RealtimeLogManager.getCurrentState()

TIP

基礎庫內部在對日誌進行上報時會補充一些結構化數據,如果遇到上報溢出的情况也會補充警告日誌,所以此方法獲取到的當前佔用資訊會比預期的大一些。

  • 功能說明: 實时日誌會將一定時間間隔內緩存的日誌聚合上報,如果該時間內緩存的內容超出限制,則會被丟棄。 此方法可以獲取當前緩存剩餘空間。

  • 參數及說明: Object

    | 内容 | 類型 | 說明 |
    | ------------------------------- | :----------------------------: | :-----------------------------: |
    | size                            |             number             |  當前緩存中已使用空間,以位元組為單位  |
    | maxSize                         |             Number             |  當前緩存最大可用空間,以位元組為單位  |
    | logCount                        |             Number             |  當前緩存中的日誌條數  |
    | maxLogCount                     |             Number             |  當前緩存中最大可存日誌條數  |
    
in

TIP

該API使用方法為: RealtimeLogManager.in(Page pageInstance)

  • 功能說明: 設定實时日誌page參數所在的頁面。
  • 參數及說明: Page pageInstance page實例。
info

TIP

該API使用方法為: RealtimeLogManager.info()

  • 功能說明: 寫info日誌
  • 參數及說明: Object|Array.<any>|number|string ...args,日誌內容,可以有任意多個。 每次調用的參數的總大小不超過5Kb。
setFilterMsg

TIP

該API使用方法為: RealtimeLogManager.setFilterMsg(string msg)

  • 功能說明: 設定過濾關鍵字
  • 參數及說明: string msg,過濾關鍵字,最多不超過1Kb,可以在小程序管理後臺根據設定的內容搜索得到對應的日誌。

RealtimeLogManager

addFilterMsg

TIP

該API使用方法為: RealtimeLogManager.addFilterMsg(string msg)
該API小程序支持,小遊戲暫不支持

  • 功能說明: 添加過濾關鍵字
  • 參數及說明: string msg,是setFilterMsg的添加接口。 用於設定多個過濾關鍵字。
error

TIP

該API使用方法為: RealtimeLogManager.error()

  • 功能說明: 寫error日誌
  • 參數及說明: Object|Array.<any>|number|string ...args,日誌內容,可以有任意多個。 每次調用的參數的總大小不超過5Kb。
getCurrentState

TIP

該API使用方法為: Object RealtimeLogManager.getCurrentState()

TIP

基礎庫內部在對日誌進行上報時會補充一些結構化數據,如果遇到上報溢出的情况也會補充警告日誌,所以此方法獲取到的當前佔用資訊會比預期的大一些。

  • 功能說明: 實时日誌會將一定時間間隔內緩存的日誌聚合上報,如果該時間內緩存的內容超出限制,則會被丟棄。 此方法可以獲取當前緩存剩餘空間。

  • 參數及說明: Object

    | 内容 | 類型 | 說明 |
    | ------------------------------- | :----------------------------: | :-----------------------------: |
    | size                            |             number             |  當前緩存中已使用空間,以位元組為單位  |
    | maxSize                         |             Number             |  當前緩存最大可用空間,以位元組為單位  |
    | logCount                        |             Number             |  當前緩存中的日誌條數  |
    | maxLogCount                     |             Number             |  當前緩存中最大可存日誌條數  |
    
in

TIP

該API使用方法為: RealtimeLogManager.in(Page pageInstance)

  • 功能說明: 設定實时日誌page參數所在的頁面。
  • 參數及說明: Page pageInstance page實例。
info

TIP

該API使用方法為: RealtimeLogManager.info()

  • 功能說明: 寫info日誌
  • 參數及說明: Object|Array.<any>|number|string ...args,日誌內容,可以有任意多個。 每次調用的參數的總大小不超過5Kb。
setFilterMsg

TIP

該API使用方法為: RealtimeLogManager.setFilterMsg(string msg)

  • 功能說明: 設定過濾關鍵字
  • 參數及說明: string msg,過濾關鍵字,最多不超過1Kb,可以在小程序管理後臺根據設定的內容搜索得到對應的日誌。
warn

TIP

該API使用方法為: RealtimeLogManager.warn()

  • 功能說明: 寫warn日誌
  • 參數及說明: Object|Array.<any>|number|string ...args,日誌內容,可以有任意多個。 每次調用的參數的總大小不超過5Kb。

RealtimeTagLogManager

addFilterMsg

TIP

該API使用方法為: RealtimeTagLogManager.addFilterMsg(string msg)

  • 功能說明: 添加過濾關鍵字
  • 參數及說明: string msg,是setFilterMsg的添加接口。 用於設定多個過濾關鍵字。
error

TIP

該API使用方法為: RealtimeTagLogManager.error(string key, Object]Array.<any> number string value)

  • 功能說明: 寫error日誌
  • 參數及說明: _ string key,日誌的key; _ Object|Array.<any>|number|string value,日誌的值,每次調用的參數的總大小不超過5Kb。
info

TIP

該API使用方法為: RealtimeTagLogManager.info(string key, Object Array.<any> number string value)

  • 功能說明: 寫info日誌
  • 參數及說明: _ string key,日誌的key; _ Object|Array.<any>|number|string value,日誌的值,每次調用的參數的總大小不超過5Kb。
setFilterMsg

TIP

該API使用方法為: RealtimeTagLogManager.setFilterMsg(string msg)

  • 功能說明: 設定過濾關鍵字
  • 參數及說明: string msg,過濾關鍵字,最多不超過1Kb,可以在小程序管理後臺根據設定的內容搜索得到對應的日誌。
info

TIP

該API使用方法為: RealtimeTagLogManager.warn(string key, ObjectJArray.<any> number string value)

  • 功能說明: 寫warn日誌
  • 參數及說明: _ string key,日誌的key; _ Object|Array.<any>|number|string value,日誌的值,每次調用的參數的總大小不超過5Kb。

效能

TIP

此 API 僅小遊戲支援。

triggerGC

TIP

該API使用方法為: wx.triggerGC()

  • 功能說明: 加快觸發 JavaScriptCore 垃圾回收(Garbage Collection)。 GC 時機是由 JavaScriptCore 控制的,並不能保證在呼叫後會馬上觸發 GC。

getPerformance

TIP

該API使用方法為: wx.getPerformance()

  • 功能說明: 取得效能管理器
  • 返回值: Performance,一個性能管理器對象

Performance

.now

TIP

該API使用方法為: Performance.now()

  • 功能說明: 可以取得目前時間以微秒為單位的時間戳記。
  • 返回值: number,時間戳

分包加載

TIP

此 API 僅小遊戲支援。

preDownloadSubpackage

TIP

該API使用方法為: wx.preDownloadSubpackage(Object object)

  • 功能說明: 觸發分包預下載
  • 參數及說明: Object object。
内容類型預設值必填說明
packageTypestring'normal'分包的類型,填寫 "workers" 後 name 欄位失效。
namestring分包的名字,可以填 name 或 root。在獨立分包內,填 __GAME__ 表示載入主包。
successfunction分包加載成功回調事件
failfunction分包加載失敗回呼事件
completefunction分包加載結束回呼事件(載入成功、失敗都會執行)
  • 返回值: PreDownloadSubpackageTask ,預先下載分包任務實例,用於取得分包預下載狀態。
  • 注意事項: wx.preDownloadSubpackage 與 wx.loadSubpackage 的差異: wx.preDownloadSubpackage 只下載程序碼包,不自動執行程序碼;wx.loadSubpackage 下載完碼包後會自動執行程序碼。
  • 示例代碼:

worker分包範例程序碼:

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

普通分包範例程序碼:

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

該API使用方法為: PreDownloadSubpackageTask.onProgressUpdate(function listener)

  • 功能說明: 監聽分包加載進度變更事件。
  • 參數及說明: function listener,,分包載入進度變更事件的監聽函數,參數 Object.res 如下:
内容類型說明
progressnumber分包下載進度百分比
totalBytesWrittennumber已經下載的資料長度,單位 Bytes
totalBytesExpectedToWritenumber預期需要下載的資料總長度,單位 Bytes

loadSubpackage

TIP

該API使用方法為: wx.loadSubpackage(Object object)

  • 功能說明: 觸發分包加載。
  • 參數及說明: Object object。
内容類型預設值必填說明
packageTypestring'normal'分包的類型,填寫 "workers" 後 name 欄位失效。
namestring分包的名字,可以填 name 或 root。在獨立分包內,填 __GAME__ 表示載入主包。
successfunction分包加載成功回調事件
failfunction分包加載失敗回呼事件
completefunction分包加載結束回呼事件(載入成功、失敗都會執行)
  • 返回值: LoadSubpackageTask 載入分包任務實例,用於取得分包載入狀態。
  • 注意事項: wx.preDownloadSubpackage 與 wx.loadSubpackage 的差異: wx.preDownloadSubpackage 只下載程序碼包,不自動執行程序碼;wx.loadSubpackage 下載完碼包後會自動執行程序碼。

LoadSubpackageTask

.onProgressUpdate

TIP

該API使用方法為: LoadSubpackageTask.onProgressUpdate(function listener)

  • 功能說明: 監聽分包加載進度變更事件。
  • 參數及說明: function listener,,分包載入進度變更事件的監聽函數,參數 Object.res 如下:
内容類型說明
progressnumber分包下載進度百分比
totalBytesWrittennumber已經下載的資料長度,單位 Bytes
totalBytesExpectedToWritenumber預期需要下載的資料總長度,單位 Bytes