0

I'd like to receive messages from websocket connection and show them as push notifications, like this:

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);

}

However I'm seem to be unable to extract title and body from received messages.

Here are the console log results:

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 

What could be wrong here? How can I fix it?

2
  • Your data comes as string "{"sender":"tomtom","body":"Hi there"}". To get it deserialized I think your data should be like this {"sender":"tomtom","body":"Hi there"} , If that's not possible, then you have to deserialize the string itself into an object. Commented Jan 17, 2020 at 12:39
  • Well what I see is that the message is an objcet: type of message: object. Anyway I don't have control over the message coming from server. How can I extract the data from it? Commented Jan 17, 2020 at 12:48

1 Answer 1

2

MessageEvent.data looks like a JSON string, as @chg already pointed out, so you need to convert it to an object.

let data = JSON.parse(msg.data);
let title = "Message from " +  data.sender;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.