Skip to main content

Tools/Interaction Methods

General Methods

$w.utils.showToast

$w.utils.showToast(options):void

Feature Description

Show tooltip

Input Parameters

options: object
PropertyTypeDefault ValueRequiredDescription
titletitleYesThe content of the tooltip
iconstring'success'NoIcon
imagestringNoThe local path or url of the custom icon. The priority of image is higher than that of icon.
durationnumber1500NoDelay duration of the tooltip (milliseconds)

Valid values for the input parameter object.icon:

ValueDescription
successDisplays a success icon. In this case, the title text can display up to 7 Chinese characters.
errorDisplays an error icon. In this case, the title text can display up to 7 Chinese characters.
loadingDisplays a loading icon. In this case, the title text can display up to 7 Chinese characters.
noneDoes not display an icon. In this case, the title text can display up to two lines. Supported in version 1.9.0 and above.

Example

$w.utils.showToast({
title: 'Success',
icon: 'success',
duration: 2000 // 2 seconds
});
$w.utils.showToast({
title: 'Failure',
icon: 'error',
duration: 2000 // 2 seconds
});

$w.utils.showLoading

Feature Description

Display a loading toast. It can only be closed by actively calling $w.utils.hideLoading.

Input Parameters

options: object
PropertyTypeDefault ValueRequiredDescription
titlestringfalseContent of the prompt
maskbooleanfalseWhether to display a transparent mask on mobile (displaying a transparent mask on mobile prevents touch penetration, while PC end is unaffected by this configuration)

Example

$w.utils.showLoading({
title: 'Loading',
mask: false
});

showLoading Toast Style

The showLoading toast provides relevant className that can be used to customize the toast's styles (not supported in WeChat Mini Programs), as follows:

classNameDescription
.wd-toastCan be used to style the root node
.wd-toast__maskCan be used to style the transparent mask
.wd-toast__bodyCan be used to style the main body
.wd-toast__iconCan style the loading icon
.wd-toast__titleCan style the loading title

$w.utils.hideLoading

Feature Description

Hide the loading toast.

Example

$w.utils.hideLoading();

$w.utils.showModal

$w.utils.showModal(options):void

Feature Description

Show modal dialog.

Input Parameters

options: object
PropertyTypeDefault ValueRequiredDescription
titlestringfalsePrompt title
contentstringNoContent of the prompt
showCancelbooleantrueNoWhether to display the cancel button
cancelTextstring'Cancel'NoText for the cancel button, up to 4 characters
cancelColorstring#000000NoText color for the cancel button, must be a hexadecimal color string
confirmTextstring'Confirm'NoText for the confirm button, up to 4 characters
confirmColorstring#576B95NoText color for the confirm button, must be a hexadecimal color string
successfunctionNoCallback function for successful API calls
failfunctionNoCallback function for failed API calls
completefunctionNoCallback function for API call completion (executed for both successful and failed calls)

Input parameter object.success callback function:

PropertyTypeDescription
contentstringthe text input by the user when editable is true
confirmbooleantrue when the user has clicked the confirm button
cancelbooleantrue when the user has clicked the cancel button

Example

$w.utils.showModal({
title: 'Prompt',
content: 'This is a modal dialog',
success(res) {
if (res.confirm) {
console.log('User clicked confirm');
} else if (res.cancel) {
console.log('User clicked cancel');
}
}
});

$w.utils.callPhone

Feature Description

Call phone

Input Parameters

options: object
PropertyTypeDefault ValueRequiredDescription
telstringRequiredPhone number

Example

$w.utils.callPhone({
tel: '18718573322'
});

$w.utils.scanCode

Feature Description

Launch the scanning interface to scan

Input Parameters

options: object
PropertyTypeDefault ValueRequiredDescription
onlyFromCamerabooleanfalseNoOnly allow scanning from the camera; disallow selecting images from the album
scanTypestring[]['barCode', 'qrCode']NoScan type
successfunctionNoCallback function for successful API calls
failfunctionNoCallback function for failed API calls
completefunctionNoCallback function for API call completion (executed for both successful and failed calls)

The possible values for scanType are:

Valid ValuesDescription
barCodeBarcode
qrCodeQR code

Response Parameters

Input parameter is of type object:

PropertyTypeDescription
resultstringScanned content
scanTypestring[]Scan type

Example

// Only allow scanning from the camera
$w.utils.scanCode({
onlyFromCamera: true,
success: (res) => {
console.log(res);
}
});

$w.utils.setClipboardData

Feature Description

Set the content of the system clipboard

Browser security restrictions

Due to browser security restrictions, this method cannot be triggered completely silently and is only effective during a window period initiated by interactive events like clicks. For example: invocations during the page load lifecycle are invalid. If an asynchronous request is made after a component click event, subsequent clipboard settings may also fail (when the asynchronous data request takes too long, the click-triggered activation expires, making clipboard access unavailable).

Mini programs have no special restrictions.

Input Parameters

options: object
PropertyTypeDefault ValueRequiredDescription
datastring''RequiredContent of the clipboard

Example

$w.utils.setClipboardData({
data: 'Copy content to clipboard'
});

$w.utils.navigateTo

Feature Description

Keep the current page and navigate to a page within the app. However, navigation to tabbar pages is not allowed.

Input Parameters

options: object
PropertyTypeDefault ValueRequiredDescription
pageIdstring''NoPage id
packageNamestring''NoSub-application package address, e.g., packages/subapp
paramsobject{}Noquery object
urlstring''NoSupports protocol-based redirection. When a URL is passed, pageId is parsed as the page path and does not need to be passed separately.
optionsobject{}NoSupports passing extended parameters from the web/Mini Program side

Example

$w.utils.navigateTo({
pageId: 'index', // Page Id
params: { key: 'value' }
});

Example of protocol-based redirection:

// When redirecting to an internal page, use the weda-page:// prefix in the url, e.g., weda-page://PACKAGE_NAME/PAGE_PATH. When the subpackage feature is disabled, the package name is 'main'; when enabled, it becomes the subpackage name, for example:
$w.utils.navigateTo({
url: 'weda-page://main/index?tt=2323',
options: {
target: '_blank' // Supports opening a new window in the web environment
}
});

// When redirecting to external pages, the url supports http/https protocols.
$w.utils.navigateTo({
url: 'https://docs.cloudbase.net/lowcode/components/wedaUI/src/docs/compsdocs/show/WdLink'
});

// When redirecting to other Mini Program pages, use the miniprogram:// prefix in the url, e.g., miniprogram://appId/PAGE_PATH
$w.utils.navigateTo({
url: 'miniprogram://wx1574617e567497e1/pages/register_start/index?foo=bar',
options: {
env_version: '_blank' // The Mini Program version to open: 'release' for official version, 'trial' for trial version, 'develop' for development version. This only takes effect when opening outside WeChat. Note: If left blank, the official version will be opened by default.
}
});

// When redirecting to a Mini Program plugin page, use the plugin:// prefix in the url, e.g., plugin://PLUGIN_NAME/PLUGIN_PAGE
$w.utils.navigateTo({
url: 'plugin://myPlugin/index'
});

$w.utils.redirectTo

Feature Description

Close the current page and navigate to a page within the app.

Input Parameters

Input parameter is of type object:

PropertyTypeDefault ValueRequiredDescription
pageIdstring''YesPage id
packageNamestring''NoSub-application name
paramsobject{}Noquery object

Example

$w.utils.redirectTo({
pageId: 'home', // Page Id
packageName: '', // For the main application, leave empty or unset; for submodules, enter the subpackage directory. Location: Subpackage Editor --- Page --- Subpackage Directory
params: { key: 'value' }
});

$w.utils.reLaunch

Feature Description

Close all pages and open a specific page within the application (due to browser limitations, in the web environment users can navigate back to pages).

Input Parameters

options: object
PropertyTypeDefault ValueRequiredDescription
pageIdstring''YesPage id
packageNamestring''NoSub-application name
paramsobject{}Noquery object

Example

$w.utils.reLaunch({
pageId: 'home', // Page Id
packageName: '', // For the main application, leave empty or unset; for submodules, enter the subpackage directory. Location: Subpackage Editor --- Page --- Subpackage Directory
params: {}
});

$w.utils.relaunchHome

Feature Description

Return to Home

Input Parameters

None

Response Parameters

None

Example

$w.utils.relaunchHome();

$w.utils.navigateBack

Feature Description

Close the current page and return to the previous page or navigate back multiple pages.

Input Parameters

options: object
PropertyTypeDefault ValueRequiredDescription
deltanumber1NoNumber of pages to return. If delta is greater than the current number of pages, it returns to the home page.

Example

$w.utils.navigateBack();

$w.utils.getEnumValue

Feature Description

To get the enumeration value, call the method getEnumValue({ enumOptions, optionSetName, key })

Input Parameters

params: object
PropertyTypeDefault ValueRequiredDescription
enumOptions{ key: any; value: any }[] | { response: { data: { items: any[] } }YesEnumeration list or return value of a generic option set interface
optionSetNamestringNoOption set identifier used to query the corresponding option set list in enumOptions.
keyanyNoThe key or list of keys corresponding to the option value to be retrieved. Returns all values in the option set by default when not passed.

Response Parameters

result: object
PropertyTypeDescription
resultany | any[]Retrieved option set value

Example

/**
* Custom Enumeration List Query
*/
const enumOptions = [
{ key: '1', value: 'aa' },
{ key: '2', value: 'bb' }
];
// If optionSetName and key are not passed, the enumeration list is returned.
$w.utils.getEnumValue({ enumOptions }); // result: [{label: 'aa', value: '1'}, {label: 'bb', value: '2'}]
// If optionSetName is not passed but key is passed, the value corresponding to the key is returned.
$w.utils.getEnumValue({ enumOptions, key: '1' }); // result: 'aa'

/**
* Return value of the generic option set interface as the input parameter for enumOptions
*/
const enumOptions = $w.query1.data;
// If optionSetName and key are not passed, the option set list object is returned.
$w.utils.getEnumValue({ enumOptions }); // result: { sex: [{label: 'Female', value: '1'}, {label: 'Male', value: '2'}]}
// If optionSetName is passed and key is not passed, the option set list corresponding to the option identifier is returned.
$w.utils.getEnumValue({ enumOptions, optionSetName: 'sex' }); // result: [{label: 'Female', value: '1'}, {label: 'Male', value: '2'}]
// If optionSetName and key are passed, the value corresponding to the key in the option set list of the corresponding option identifier is returned.
$w.utils.getEnumValue({ enumOptions, optionSetName: 'sex', key: '1' }); // result: 'Female'

$w.utils.getStorage

async getStorage(options: IGetStorageOptions): Promise<IGetStorageRes>

Feature Description

Asynchronously fetches the content of the specified key from the local cache. Returns a Promise object.

Input Parameters

params: IGetStorageOptions
PropertyTypeDefault ValueRequiredDescription
keystringYesThe specified key in the local cache

Response Parameters

result: IGetStorageRes
PropertyTypeDescription
dataanyContent corresponding to the key

Example

$w.utils.getStorage({ key: 'cache_kay' }); // result: { data: xxx }

$w.utils.setStorage

async setStorage(options: ISetStorageOptions): Promise<void>

Feature Description

Stores data in the specified key in the local cache. This overwrites any existing content associated with the key. The data remains available unless actively deleted by the user or cleared by the system due to storage space limitations. A single key supports a maximum data length of 1MB, with a total storage limit of 10MB for all data.

Input Parameters

params: ISetStorageOptions
PropertyTypeDefault ValueRequiredDescription
keystringYesThe specified key in the local cache
dataanyYesThe content to be stored. Only supports primitive types, Date, and objects that can be serialized via JSON.stringify.

Example

$w.utils.setStorage({ key: 'cache_kay', data: { test: 10 } });

$w.utils.removeStorage

async removeStorage(options: IRemoveStorageOptions): Promise<void>

Feature Description

Removes the specified key from the local cache. The method to call is removeStorage({ key })

Input Parameters

params: IRemoveStorageOptions
PropertyTypeDefault ValueRequiredDescription
keystringYesThe specified key in the local cache

Example

$w.utils.removeStorage({ key: 'cache_kay' });

WEB-Specific Methods

$w.utils.exportData

Feature Description

Export data to a file

Input Parameters

options: object
PropertyTypeDefault ValueRequiredDescription
dataObject[][]YesThe data to be exported, e.g., [{name: 'sam', age: 18}]
fileNameString'download'OptionalExport file name
fileTypeString'csv'OptionalExport file type, supports csv and xlsx
optionsObject{}OptionalAdditional export options
options.options object
PropertyTypeDefault ValueRequiredDescription
sheetNamestringundefinedOptionalSpecifies the sheet name for the exported data when the file type is xlsx

Example

$w.utils.exportData({
data: [{ name: 'sam', age: 18 }],
fileName: 'filename',
fileType: 'xlsx',
options: { sheetName: 'sheet1' }
});

Mini Program Exclusive Method

$w.utils.requestSubscribeMessage

Feature Description

Invokes the client-side mini program's subscription message interface and returns the user's subscription operation result.

Input Parameters

options: object
PropertyTypeDefault ValueRequiredDescription
tmplIdsArrayYesThe collection of message template IDs to be subscribed. A single call can subscribe to up to 3 messages.

Response Parameters

options: object
PropertyTypeDescription
resobjectSubscription result
Subscription result res: object
PropertyTypeDescription
[TEMPLATE_ID: string]String[TEMPLATE_ID] is a dynamic key representing the template ID. The value can be 'accept', 'reject', 'ban', 'filter', or 'acceptWithAudio'. 'accept' indicates the user agreed to subscribe to the template message corresponding to that ID. 'reject' indicates the user refused to subscribe to the template message corresponding to that ID. 'ban' indicates the template has been banned by the backend. 'acceptWithAudio' indicates the user accepted the subscription message and enabled voice reminders. 'filter' indicates the template was filtered by the backend due to duplicate template titles. For example, { errMsg: 'requestSubscribeMessage:ok', zun-LzcQyW-edafCVvzPkK4de2Rllr1fFpw2A_x0oXE: 'accept'} indicates the user agreed to subscribe to the message with ID zun-LzcQyW-edafCVvzPkK4de2Rllr1fFpw2A_x0oXE.
errMsgStringWhen the API call is successful, the value of errMsg is 'requestSubscribeMessage:ok'.

Example

$w.utils.requestSubscribeMessage({
params: {
tmplIds: ['zun-LzcQyW-edafCVvzPkK4de2Rllr1fFpw2A_x0oXE']
}
});
// can only be triggered by the tap event
// Returns after successful execution
// {
// res: {
// errMsg: 'requestSubscribeMessage:ok',
// zun-LzcQyW-edafCVvzPkK4de2Rllr1fFpw2A_x0oXE: 'accept'
// }
// }

$w.utils.openLocation

Feature Description

Use the WeChat built-in map to view locations

Input Parameters

options: object
PropertyTypeDefault ValueRequiredDescription
latitudenumberRequiredLatitude, ranging from -90 to 90. Negative values indicate south latitude. Uses the GCJ-02 coordinate system.
longitudenumberRequiredLongitude, ranging from -180 to 180. Negative values indicate west longitude. Uses the GCJ-02 coordinate system.
scalenumber18NoScale, range 5~18
namenumberNoLocation name
addressnumberNoDetailed address description

Response Parameters

None

Example

$w.utils.openLocation({
latitude: 39.92,
longitude: 116.46,
scale: 18,
name: 'Beijing',
address: 'Beijing'
});

$w.utils.reserveChannelsLive

Feature Description

Reserve Channels live

Input Parameters

options: object
PropertyTypeDefault ValueRequiredDescription
noticeIdstringRequiredNotice id, obtained via the getChannelsLiveNoticeInfo interface

Response Parameters

options: object
PropertyTypeDescription
statenumberThe user's reservation result: state = 1, live in progress, user clicked "Cancel" to decline going to the live stream; state = 2, live in progress, user clicked "Allow" to go to the live stream; state = 3, notice has been canceled; state = 4, live stream has ended; state = 5, user had not reserved before, directly closed the pop-up without reserving; state = 6, user had not reserved before, reserved the live stream in the pop-up; state = 7, user had reserved before, canceled the reservation in the pop-up; state = 8, user had reserved before, directly closed the pop-up; state = 9, user canceled directly before the pop-up was invoked; state = 10, live stream reservation has expired

Example

$w.utils.reserveChannelsLive({
params: {
noticeId: 'xxxxxxxxxxxxx'
}
});

$w.utils.openChannelsUserProfile

Feature Description

Open Channels Profile

Input Parameters

options: object
PropertyTypeDefault ValueRequiredDescription
finderUserNamestringRequiredChannels id

Response Parameters

None

Example

$w.utils.openChannelsUserProfile({
finderUserName: 'sphxxxxxxxxxxxxx'
});

$w.utils.openChannelsLive

Feature Description

Open Channels Live Stream

Input Parameters

options: object
PropertyTypeDefault ValueRequiredDescription
finderUserNamestringRequiredChannels id
feedIdstringNoLive feedId, obtained via the getChannelsLiveInfo interface
nonceIdstringNoLive nonceId, obtained via the getChannelsLiveInfo interface

Response Parameters

None

Example

$w.utils.openChannelsLive({
finderUserName: 'sphxxxxxxxxxxxxx'
});

$w.utils.openChannelsEvent

Feature Description

Open Channels Event Page

Input Parameters

options: object
PropertyTypeDefault ValueRequiredDescription
finderUserNamestringRequiredChannels id
eventIdstringRequiredEvent id

Response Parameters

None

Example

$w.utils.openChannelsEvent({
finderUserName: 'sphxxxxxxxxxxxxx',
eventId: 'event/ULEZgBPE26EcB1M9DtqAzNPgMJqg8sGefrd7RCKj5fFUerYjasdasdasd'
});

$w.utils.openChannelsActivity

Feature Description

Open Channels Video

Input Parameters

options: object
PropertyTypeDefault ValueRequiredDescription
finderUserNamestringRequiredChannels id
feedIdstringRequiredvideo feedId

Response Parameters

None

Example

$w.utils.openChannelsActivity({
finderUserName: 'sphxxxxxxxxxxxxx',
feedId: 'xxxxxxx'
});

$w.utils.getChannelsLiveNoticeInfo

Feature Description

Get Channels live schedule information

Input Parameters

options: object
PropertyTypeDefault ValueRequiredDescription
finderUserNamestringRequiredChannels id

Response Parameters

options: object
PropertyTypeDescription
noticeIdstringNotice id
statusnumberNotice status: 0 (Available), 1 (Cancelled), 2 (Used)
startTimestringStart time
headUrlstringLive cover
nicknamestringChannels nickname
reservablebooleanReservable
otherInfosArrayList of other notices except the most recent one (Note: a maximum of 15 notices are returned each time in ascending timestamp order; the latest notice is displayed in other API response parameters, while the remaining notices are displayed in this field).

Example

$w.utils.getChannelsLiveNoticeInfo({
params: { finderUserName: 'sphxxxxxxxxxxxxx' }
});

$w.utils.getChannelsLiveInfo

Feature Description

Get Channels live information

Input Parameters

options: object
PropertyTypeDefault ValueRequiredDescription
finderUserNamestringRequiredChannels id
startTimenumberOptionalStart time to filter live streams within a specified time period. If endTime is provided without startTime, startTime defaults to 0.
endTimenumberOptionalEnd time to filter live streams within a specified time period. If startTime is provided without endTime, endTime defaults to the current time.

Response Parameters

options: object
PropertyTypeDescription
feedIdstringlive feedId
noticeIdstringlive id
descriptionstringLive Stream Topic
statusnumberLive status: 2 (Live streaming), 3 (Live ended)
headUrlstringChannels avatar
nicknamestringChannels nickname
replayStatusstringLive replay status: 0 (Not generated), 1 (Generated), 3 (Generating), 6 (Expired)
otherInfosArrayList of other live streams except the most recent one (Note: a maximum of 15 live streams are returned each time in ascending timestamp order; the latest live stream is displayed in other response parameters of the interface, while the remaining live streams are displayed in this field).

Example

$w.utils.getChannelsLiveInfo({
params: { finderUserName: 'sphxxxxxxxxxxxxx' }
});