微信小程序不支持
EventSource(SSE)是一種HTML5標(biāo)準(zhǔn),旨在提供一種方式來在Web應(yīng)用中實(shí)現(xiàn)異步通信和事件處理。
然而,根據(jù)現(xiàn)有的信息,uni-app并沒有直接支持EventSource,這意味著開發(fā)者需要尋找其他技術(shù)或替代方案來實(shí)現(xiàn)類似的效果。文章來源:http://www.zghlxwxcb.cn/news/detail-853665.html
盡管有些主流瀏覽器支持SSE,但小程序目前還不能兼容這個(gè)API,這可能是由于微信平臺(tái)對(duì)新技術(shù)的兼容性考慮或是開發(fā)生態(tài)的限制。文章來源地址http://www.zghlxwxcb.cn/news/detail-853665.html
一個(gè)替代實(shí)現(xiàn)方式
class EventSource {
constructor(url, retryTime = 0) {
this.url = url;
this.retryTime = retryTime;
this.listeners = {};
this.requestTask = null
this.connect()
}
connect() {
this.requestTask = wx.request({
url: this.url,
enableChunked: true,
responseType: 'text',
method: 'GET',
timeout: 300e3,
success: res => {
this.emit('success', res)
if (this.retryTime > 0) {
setTimeout(() => {
this.connect()
}, this.retryTime)
}
},
fail: () => {
}
});
this.requestTask.onHeadersReceived(res => {
this.emit('open', res);
})
this.requestTask.onChunkReceived(res => this.handleChunk(res))
}
handleChunk(res) {
const arrayBuffer = res.data;
const uint8Array = new Uint8Array(arrayBuffer);
let data = uni.arrayBufferToBase64(uint8Array)
data = new Buffer(data, 'base64')
data = data.toString('utf8')
const lines = data.split("\n\n")
// console.log('data', data, lines)
lines.forEach(line => {
if (!line.trim()) {
return
}
const [key, value] = line.trim().split(':');
if (key === 'data') {
const data = line.substring(5).trim();
try {
const json = JSON.parse(data);
this.emit('message', {
data: JSON.stringify(json)
})
} catch (e) {
this.emit('error', 'Api.EventSource.ParseError:' + e)
}
} else {
this.emit('error', 'Api.EventSource.ParseFail:' + line)
}
})
}
addEventListener(event, callback) {
if (!this.listeners[event]) {
this.listeners[event] = []
}
this.listeners[event].push(callback)
}
emit(event, data) {
if (this.listeners[event]) {
this.listeners[event].forEach(callback => {
callback(data)
});
}
}
close() {
if (this.requestTask) {
this.requestTask.abort()
}
}
}
到了這里,關(guān)于分享一個(gè)讓 uniapp 微信小程序支持 EventSource 的方法的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!