【发布时间】:2020-01-17 12:26:47
【问题描述】:
我想从 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);
}
但是,我似乎无法从收到的消息中提取 title 和 body。
以下是控制台日志结果:
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
这里有什么问题?我该如何解决?
【问题讨论】:
-
您的
data以字符串"{"sender":"tomtom","body":"Hi there"}"的形式出现。为了使其反序列化,我认为您的data应该是这样的{"sender":"tomtom","body":"Hi there"},如果这不可能,那么您必须将字符串本身反序列化为一个对象。 -
嗯,我看到的是消息是一个对象:
type of message: object。无论如何,我无法控制来自服务器的消息。如何从中提取数据?
标签: javascript json websocket