javascript - 无法从 websocket 消息对象获取 json 值

标签 javascript json websocket

我想从 websocket 连接接收消息并将其显示为推送通知,如下所示:

socket.onmessage = msg => {
  if( 'Notification' in window){
    if (Notification.permission === 'granted') {
        navigator.serviceWorker.ready.then(function(registration) {
        doNotify(msg);
        });
    }
    else{
        Notification.requestPermission()
            .then(function(result) {
                console.log(result);  //granted || denied
                if( Notification.permission == 'granted'){ 
                    doNotify();
                }
            })
            .catch( (err) => {
                console.log(err);
            });
    }

}
};

function doNotify(msg) {
  console.log('msg to deal with  is:', msg) ;
  console.log('type of message: ', typeof msg);
  let msgJ = JSON.stringify(msg);
  console.log('msg in json format:', msgJ) ;
  console.log('type of msgJ: ', typeof msgJ);
  console.log('sender:', msgJ.data.sender) ;
  console.log(' body:', msgJ.data.body) ;

  let title = "Message from" +  msgJ.data.sender;
  let body = msgJ.data.body;
  let options = {
    title:  title,
    body:   body,
    vibrate: [100, 200, 100]
  }
  let n = new Notification(title, options);

}

但是我似乎无法从收到的消息中提取titlebody

以下是控制台日志结果:

msg to deal with  is: MessageEvent {isTrusted: true, data: "{"sender":"tomtom","body":"Hi there"}↵", origin: "ws://127.0.0.1:8080", lastEventId: "", source: null, …}
type of message:  object
msg in json format: {"isTrusted":true}
type of msgJ:  string
socket.js?1579263492:52 Uncaught (in promise) TypeError: Cannot read property 'sender' of undefined
    at doNotify (socket.js?1579263492:52)
    at socket.js?1579263492:17 

这里可能出了什么问题?我该如何修复它?

最佳答案

MessageEvent.data 看起来像一个 JSON 字符串,正如 @chg 已经指出的那样,因此您需要将其转换为对象。

let data = JSON.parse(msg.data);
let title = "Message from " +  data.sender;

关于javascript - 无法从 websocket 消息对象获取 json 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59787337/

相关文章:

javascript - 为什么在 Firefox 中调用这个 jQuery 函数会失败?

websocket - 无法使用 wscat 连接到 Ruby on Rails 5 Beta 上的 ActionCable WebSocket

javascript - 使用node-http-proxy在同一子域下代理 Node 服务器和websocket服务器

json - 如何通过billboard API获取 "billboard hot 100"图表列表

c# - 导出到 JSON 时使用无效的 C# 关键字名称

Android org.json.JSONObject 在单元测试中返回 null

javascript - 我将如何通过 Javascript 中的 WebSocket 发送和接收数据包

javascript - 尝试运行 Selenium 时出现问题

javascript - 如何从父实体获取选项设置值并在子实体的选项集中设置该值。

javascript - 具有模型拦截/过滤功能的 Angular Directive(指令)