Skip to main content
Version: Next

Taro.sendSocketMessage(option)

Sends data over WebSocket connection. Call Taro.connectSocket first and send data after the Taro.onSocketOpen callback.

Reference

Type

(option: Option) => Promise<CallbackResult>

Parameters

Option

PropertyTypeRequiredDescription
datastring | ArrayBufferYesThe data to be sent
complete(res: CallbackResult) => voidNoThe callback function used when the API call completed (always executed whether the call succeeds or fails)
fail(res: CallbackResult) => voidNoThe callback function for a failed API call
success(res: CallbackResult) => voidNoThe callback function for a successful API call

Sample Code

let socketOpen = false
const socketMsgQueue = []
Taro.connectSocket({
url: 'test.php'
})
Taro.onSocketOpen(function(res) {
socketOpen = true
for (let i = 0; i < socketMsgQueue.length; i++){
sendSocketMessage(socketMsgQueue[i])
}
socketMsgQueue = []
})
function sendSocketMessage(msg) {
if (socketOpen) {
Taro.sendSocketMessage({
data:msg
})
} else {
socketMsgQueue.push(msg)
}
}

API Support

APIWeChat Mini-ProgramBaidu Smart-ProgramAlipay Mini-ProgramH5React Native
Taro.sendSocketMessage✔️✔️✔️