JavaScript-对通过websocket.onmessage接收的消息执行某些操作
简而言之,我试图通过从后端通过websocket向网页发送消息来操纵我的网页。当我的页面加载时,websocket连接就建立起来了。当我的页面关闭或刷新时,我的页面会切断连接。我的想法是,我的后端(aws lambda fn)将通过websocket向我的HTML页面发送一条消息,然后我将处理该消息。下面是一段代码片段,解释了这段简单但麻烦的代码:JavaScript-对通过websocket.onmessage接收的消息执行某些操作,javascript,api,websocket,Javascript,Api,Websocket,简而言之,我试图通过从后端通过websocket向网页发送消息来操纵我的网页。当我的页面加载时,websocket连接就建立起来了。当我的页面关闭或刷新时,我的页面会切断连接。我的想法是,我的后端(aws lambda fn)将通过websocket向我的HTML页面发送一条消息,然后我将处理该消息。下面是一段代码片段,解释了这段简单但麻烦的代码: window.onload = function() { socket = setupWebSocket(); }; windo
window.onload = function() {
socket = setupWebSocket();
};
window.addEventListener('beforeunload', function(event) {
socket.close()
})
function setupWebSocket() {
socket = new WebSocket("wss://*****.amazonaws.com/dev");
socket.onmessage = function(event) {
console.log(event) // This logs out fine
// I want to now run this function with the event data
// However, it won't let me. It says event is undefined
showTheList(event.data.urls);
}
return socket;
}
function showTheList(url_list) {
// Do something with the list of urls
}
log(事件)生成以下日志
MessageEvent {isTrusted: true, data: "{"action": "show_images", "urls": ["https://*****"]}", origin: "wss://******.amazonaws.com", lastEventId: "", source: null, …}
bubbles: false
cancelBubble: false
cancelable: false
composed: false
currentTarget: WebSocket {url: "wss://********.amazonaws.com/dev", readyState: 1, bufferedAmount: 0, onopen: null, onerror: null, …}
data: "{"action": "show_images", "urls": ["https://*****/show?id=1020010095886C00", "https://*****/show?id=102001008CB55900", "https://*****/show?id=102001008E367000", "https://*****/show?id=103001009CAF3400", "https://*****/show?id=10400100534ADC00", "https://*****/show?id=102001008C81F600"]}"
defaultPrevented: false
eventPhase: 0
isTrusted: true
lastEventId: ""
origin: "wss://*****.amazonaws.com"
path: []
ports: []
returnValue: true
source: null
srcElement: WebSocket {url: "wss://*****.amazonaws.com/", readyState: 1, bufferedAmount: 0, onopen: null, onerror: null, …}
target: WebSocket {url: "wss://*****.amazonaws.com/", readyState: 1, bufferedAmount: 0, onopen: null, onerror: null, …}
timeStamp: 9330.839999951422
type: "message"
userActivation: null
__proto__: MessageEvent
您的数据似乎是字符串格式的 尝试替换:
showTheList(event.data.urls);
与:
showTheList(JSON.parse(event.data).urls);