【问题标题】:JavaScript - Do something with a message received through websocket.onmessageJavaScript - 对通过 websocket.onmessage 收到的消息执行操作
【发布时间】:2020-06-29 17:01:35
【问题描述】:

简而言之,我试图通过后端的 websocket 向它发送消息来操纵我的网页。当我的页面加载时,websocket 连接就建立了。当我的页面关闭或刷新时,我的页面会断开连接。这个想法是我的后端 (aws lambda fn) 将通过 websocket 向我的 HTML 页面发送一条消息,然后我将对该消息进行处理。这是一个解释这个简单但麻烦的代码的sn-p:

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
}

console.log(event) 产生以下日志

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

【问题讨论】:

    标签: javascript api websocket


    【解决方案1】:

    您的数据似乎是字符串格式。

    尝试替换:

    showTheList(event.data.urls);
    

    与:

    showTheList(JSON.parse(event.data).urls);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-23
      • 1970-01-01
      • 2014-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多