Skip to main content

Tools/Interaction Methods

General Methods

$w.utils.showToast

$w.utils.showToast(options):void

Feature Description

Display the alert box.

Input Parameters

options: object

PropertyTypeDefault ValueRequiredDescription
titletitleRequiredPrompt content
iconstring'success'NoIcon
imagestringNoLocal path or url for the custom icon. image has higher priority than icon.
durationnumber1500NoDelay time for the prompt (milliseconds)

Valid values for object.icon:

ValueDescription
successDisplays the success icon, with the title text limited to a maximum of 7 Chinese characters.
errorDisplays the error icon, with the title text limited to a maximum of 7 Chinese characters.
loadingDisplays the loading icon, with the title text limited to a maximum of 7 Chinese characters.
noneDoes not display an icon. The title text can display up to two lines, supported in version 1.9.0 and above

Example

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

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

$w.utils.showLoading

Feature Description

Displays a loading prompt box. The prompt box must be closed by actively calling $w.utils.hideLoading.

Input Parameters

options: object

PropertyTypeDefault ValueRequiredDescription
titlestringfalsePrompt content
maskbooleanfalseWhether to display a transparent mask on mobile (displaying the mask prevents touch penetration on mobile, and this setting does not affect PC).

Example

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

showLoading Dialog Style

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

classNameDescription
.wd-toastCan set styles for the root node
.wd-toast__maskCan set styles for the transparent mask
.wd-toast__bodyCan set styles for the main content
.wd-toast__iconCan set styles for the loading icon
.wd-toast__titleCan set styles for the loading title

$w.utils.hideLoading

Feature Description

Hide the loading prompt box.

Example

$w.utils.hideLoading();

$w.utils.showModal

$w.utils.showModal(options):void

Feature Description

Show the modal dialog.

Input Parameters

options: object

PropertyTypeDefault ValueRequiredDescription
titlestringNoPrompt title
PropertyTypeDefault ValueRequiredDescription
showCancelbooleantrueNoWhether to show the cancel button
cancelTextstring'Cancel'NoText for the cancel button, up to 4 characters
cancelColorstring#000000NoText color of the cancel button, must be a hexadecimal color string
confirmTextstring'Confirm'NoText for the confirm button, up to 4 characters
confirmColorstring#576B95NoText color of the confirm button, must be a hexadecimal color string
successfunctionNoCallback function for successful API invocation
failfunctionNoCallback function for failed API invocation
completefunctionNoCallback function executed upon API invocation completion (executed regardless of success or failure)

object.success callback function parameters:

PropertyTypeDescription
contentstringText entered by the user when editable is true
confirmbooleanIndicates that the user clicked the confirm button when true
cancelbooleanIndicates that the user clicked cancel when true

Example

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

$w.utils.callPhone

Feature Description

Dial the phone

Input Parameters

options: object

PropertyTypeDefault ValueRequiredDescription
telstringRequiredPhone Number

Example

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

$w.utils.scanCode

Feature Description

Launch the QR code scanning interface to scan.

Input Parameters

options: object

PropertyTypeDefault ValueRequiredDescription
onlyFromCamerabooleanfalseNoWhether scanning is only allowed from the camera, and selecting images from the album is not allowed.
scanTypestring[]['barCode', 'qrCode']NoScanning types
successfunctionNoCallback function for successful API invocation
failfunctionNoCallback function for failed API invocation
completefunctionNoCallback function executed upon API invocation completion (executed regardless of success or failure)

Valid values for scanType:

ValueDescription
barCodebarcode
qrCodeQR code

Output Parameters

Callback function parameters:

PropertyTypeDescription
resultstringScanned content
scanTypestring[]Scanning 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. It is only effective during a window period activated by interactive events such as clicks. For example: calls during the page load lifecycle are invalid. If an asynchronous API request is made after a component click event and then the clipboard is set, it may also fail (when the asynchronous request takes too long, the click-triggered activation expires, making the clipboard inaccessible).

Mini Programs have no special restrictions.

Input Parameters

options: object

PropertyTypeDefault ValueRequiredDescription
datastring''YesContent of the clipboard

Example

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

$w.utils.navigateTo

Feature Description

Keep the current page and navigate to a specific page within the app, but it is not allowed to navigate to tabbar pages.

Input Parameters

options: object

PropertyTypeDefault ValueRequiredDescription
pageIdstring''NoPage id
packageNamestring''NoSub-application package address, e.g., packages/subapp
paramsobject{}NoRepresents a query 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 on the web/mini-program sides.

Example

Basic usage:

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

Protocol-based redirection method:

// Redirect to internal page 
$w.utils.navigateTo({
url: 'weda-page://main/index?tt=2323',
options: {
target: target: '_blank' // Supports opening a new window on the web
}
});

// Redirect to external page. Only supported on the web for external links
$w.utils.navigateTo({
url: 'https://docs.cloudbase.net/lowcode/components/wedaUI/src/docs/compsdocs/show/WdLink'
});

// Navigate to other Mini Program pages. Only supported on mobile for opening Mini Program pages.
$w.utils.navigateTo({
url: 'miniprogram://wx1574617e567497e1/pages/register_start/index?foo=bar',
options: {
env_version: env_version: 'release' // The version of the Mini Program to open. Production version is 'release', trial version is 'trial', development version is 'develop'. Only effective when opened outside WeChat.
}
});

// Redirect to Mini Program plugin page. Only supported in the Mini Program environment for opening plugin pages.
$w.utils.navigateTo({
url: 'plugin://myPlugin/index'
});

$w.utils.redirectTo

Feature Description

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

Input Parameters

options: object

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

Example

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

$w.utils.reLaunch

Feature Description

Close all pages and open to a specific page within the app. (Due to browser limitations, you can navigate back in web environments.)

Input Parameters

options: object

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

Example

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

$w.utils.relaunchHome

Feature Description

Return to Home

Input Parameters

None

Output Parameters

None

Example

$w.utils.relaunchHome();

$w.utils.navigateBack

Feature Description

Close the current page and return to the previous page or multiple levels.

Input Parameters

options: object

PropertyTypeDefault ValueRequiredDescription
deltanumber1NoThe number of pages to return. If delta is greater than the existing number of pages, return to the home page.

Example

$w.utils.navigateBack();

$w.utils.getEnumValue

Feature Description

Obtain the enum value by calling the method getEnumValue({ enumOptions, optionSetName, key })

Input Parameters

params: object

PropertyTypeDefault ValueRequiredDescription
enumOptions{ key: any; value: any }[] | { response: { data: { items: any[] } }YesEnumeration list or common option set interface return value
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 obtained. If not passed, all values in the option set are returned by default.

Output Parameters

result: object

PropertyTypeDescription
resultany | any[]Obtained option set value

Example

// Custom enum list query
const enumOptions = [
{ key: '1', value: 'aa' },
{ key: '2', value: 'bb' }
];

// Returns the enum list if neither optionSetName nor key is passed
$w.utils.getEnumValue({ enumOptions });
// Result: [{label: 'aa', value: '1'}, {label: 'bb', value: '2'}]

// If optionSetName is not passed but key is passed, returns the value corresponding to the key
$w.utils.getEnumValue({ enumOptions, key: '1' });
// Result: 'aa'

// Common option set interface return value as the input parameter for enumOptions
const enumOptions = $w.query1.data;

// Returns the option set list object if neither optionSetName nor key is passed
$w.utils.getEnumValue({ enumOptions });
// Result: { sex: [{label: 'Female', value: '1'}, {label: 'Male', value: '2'}]}

// If optionSetName is passed but key is not passed, returns the option set list corresponding to the passed optionSetName
$w.utils.getEnumValue({ enumOptions, optionSetName: 'sex' });
// Result: [{label: 'Female', value: '1'}, {label: 'Male', value: '2'}]

// If optionSetName and key are passed, returns the value corresponding to the key in the option set list corresponding to the option identifier
$w.utils.getEnumValue({ enumOptions, optionSetName: 'sex', key: '1' });
// Result: 'Female'

$w.utils.getStorage

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

Feature Description

Asynchronously obtain the content of the specified key from the local cache, returning a Promise object

Input Parameters

options: IGetStorageOptions

PropertyTypeDefault ValueRequiredDescription
keystringRequiredThe specified key in the local cache

Output Parameters

result: IGetStorageRes

PropertyTypeDescription
dataanyThe content 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, overwriting the original content corresponding to that key. The data remains available until the user actively deletes it or the system clears it due to storage space limitations. The maximum data length for a single key is 1MB, and the total storage limit is 10MB.

Input Parameters

options: ISetStorageOptions

PropertyTypeDefault ValueRequiredDescription
keystringRequiredThe specified key in the local cache
dataanyRequiredThe content to be stored. Only native types, Date, and objects that can be serialized via JSON.stringify are supported.

Example

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

$w.utils.removeStorage

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

Feature Description

Remove the specified key from the local cache

Input Parameters

options: IRemoveStorageOptions

PropertyTypeDefault ValueRequiredDescription
keystringRequiredThe specified key in the local cache

Example

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

WEB Dedicated Methods

$w.utils.exportData

Feature Description

Export data to a file

Input Parameters

options: object

PropertyTypeDefault ValueRequiredDescription
dataObject[][]RequiredThe data to be exported, e.g.: [{name: 'sam', age: 18}]
fileNameString'download'NoExport file name
fileTypeString'csv'NoExport file type, supports csv and xlsx
optionsObject{}NoOther export options

`options.options parameter:

PropertyTypeDefault ValueRequiredDescription
sheetNamestringundefinedNoWhen the export type is xlsx, specifies the sheet name for the exported data

Example

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

Mini Program Dedicated Methods

$w.utils.requestSubscribeMessage

Feature Description

Invoke the client mini program's subscription message interface and return the result of the user's subscription operation.

Input Parameters

options: object

PropertyTypeDefault ValueRequiredDescription
tmplIdsArrayYesList of message template IDs to subscribe to. A single call can subscribe to up to 3 messages.

Output Parameters

result: object

PropertyTypeDescription
resobjectSubscription result

Subscription result res object:

PropertyTypeDescription
[TEMPLATE_ID: string]String[TEMPLATE_ID] is a dynamic key, i.e., the template id. The values include:
- 'accept': The user agrees to subscribe to this template message
- 'reject': The user refuses to subscribe to this template message
- 'ban': Indicates that it has been banned by the backend
- 'acceptWithAudio': The user accepts the subscription message and has enabled voice reminders
- 'filter': This template is filtered by the backend due to duplicate template titles
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
// After being executed successfully, return
// {
// res: {
// errMsg: 'requestSubscribeMessage:ok',
// zun-LzcQyW-edafCVvzPkK4de2Rllr1fFpw2A_x0oXE: 'accept'
// }
// }

$w.utils.openLocation

Feature Description

Use the WeChat built-in map to view location

Input Parameters

options: object

PropertyTypeDefault ValueRequiredDescription
latitudenumberYesLatitude, ranging from -90 to 90. Negative values indicate south latitude. Uses the GCJ-02 coordinate system.
longitudenumberYesLongitude, ranging from -180 to 180. Negative values indicate west longitude. Uses the GCJ-02 coordinate system.
scalenumber18NoScale, ranging from 5 to 18
namestringNoLocation name
addressstringNoDetailed description of the address

Output Parameters

None

Example

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

$w.utils.reserveChannelsLive

Feature Description

Schedule a Channels Live

Input Parameters

options: object

PropertyTypeDefault ValueRequiredDescription
noticeIdstringRequiredNotice id, obtained via the getChannelsLiveNoticeInfo interface

Output Parameters

result: object

PropertyTypeDescription
statenumberUser'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 has ended
- state = 5: User had not reserved previously, closed the pop-up directly without reserving
- state = 6: User had not reserved previously, reserved the live stream in the pop-up
- state = 7: User had reserved previously, canceled the reservation in the pop-up
- state = 8: User had reserved previously, closed the pop-up directly
- state = 9: User canceled directly before the pop-up was triggered
- state = 10: Live reservation has expired

Example

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

$w.utils.openChannelsUserProfile

Feature Description

Open the Channels Live homepage

Input Parameters

options: object

PropertyTypeDefault ValueRequiredDescription
finderUserNamestringRequiredChannels id

Output Parameters

None

Example

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

$w.utils.openChannelsLive

Feature Description

Open the 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

Output Parameters

None

Example

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

$w.utils.openChannelsEvent

Feature Description

Open the Channels Live Activity page

Input Parameters

options: object

PropertyTypeDefault ValueRequiredDescription
finderUserNamestringRequiredChannels id
eventIdstringRequiredActivity id

Output Parameters

None

Example

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

$w.utils.openChannelsActivity

Feature Description

Open the Channels video

Input Parameters

options: object

PropertyTypeDefault ValueRequiredDescription
finderUserNamestringRequiredChannels id
feedIdstringRequiredVideo feedId

Output Parameters

None

Example

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

$w.utils.getChannelsLiveNoticeInfo

Feature Description

Retrieve Channels livestream preview information

Input Parameters

options: object

PropertyTypeDefault ValueRequiredDescription
finderUserNamestringRequiredChannels id

Output Parameters

result: object

PropertyTypeDescription
noticeIdstringNotice id
statusnumberNotice status: 0 Available, 1 Cancelled, 2 Used
startTimestringStart time
headUrlstringCover
nicknamestringChannels nickname
reservablebooleanReservable
otherInfosArrayThe list of other notice information except the most recent one. Note: At most 15 notice entries are returned in ascending order by timestamp each time. The most recent notice is displayed in other response parameters of the interface, and the remaining notices are displayed in this field.

Example

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

$w.utils.getChannelsLiveInfo

Feature Description

Obtain Channels livestream information

Input Parameters

options: object

PropertyTypeDefault ValueRequiredDescription
finderUserNamestringRequiredChannels id
startTimenumberNoStart time, which filters livestreams within a specified time range. If endTime is provided but startTime is not, startTime defaults to 0.
endTimenumberNoEnd time, which filters livestreams within a specified time range. If startTime is provided but endTime is not, endTime defaults to the current time.

Output Parameters

result: object

PropertyTypeDescription
feedIdstringLivestream feedId
noticeIdstringLivestream id
descriptionstringLivestream topic

Output Parameters | headUrl | string | Channels avatar | | nickname | string | Channels nickname | | replayStatus | string | Livestream replay status: 0: Not generated, 1: Generated, 3: Generating, 6: Expired | | otherInfos | Array | The list of other livestreams except the most recent one. Note: At most 15 livestream entries are returned in ascending order by timestamp each time. The most recent livestream is displayed in other response parameters of the interface, and the remaining livestreams are displayed in this field. |

Example

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