Hi, I’m currently working on a browser based private message system. Sending messages works fine so far but now I would like to add a ding-sound when a user receives a new message. In my thinking process I believe I need an event for that that fires without user interaction but I couldn’t find anything about it.
Right now I’m using a button with the class “.test” to fire the event to test it.
Here is how I did it so far:
Here I get the current count of unread messages. If you get on the page it waits a second, then looks for your PNs and then sets a session with the current count.
PN.find({
userGet: Meteor.user().username,
isSeen: false,
isTrash: false,
isFav: false,
},
{ sort: { createdAt: -1 } }
).observeChanges({
added() {
var audio = new Audio('sounds/blep.wav');
audio.play();
console.log('Testlog: There is a new pn');
},
});
Alternatively you could use an autorun to re-run a function anytime your query changes, but that kinda ends up being more code.
Not that an interval is a bad idea, traditional apps often use this kind of polling with HTTP requests to check for new notifications. The resource use is even lower in a Meteor app, where the data is pushed over the web-socket instead of polled from the client. So your solution is perfectly fine, just a little more complicated than using observeChanges
Thank you! That really would be more comfortable. Although there’s a problem that occurse if I use observeChanges or the method with interval.
On some pages it works fine, on others there’s this error-message in the console:
Uncaught (in promise) DOMException
It appears somewhat random to me when it comes to the pages that work or those who don’t. The nav is inside a template and always on the top of the page. My sound-folder is inside the nav-component-directory on that path: /imports/ui/components/nav/sounds/blep.wav This is also where my nav-template is. Later I put this nav-template inside body.html in /imports/ui/layout/body/body.html.
My guess is that DOMException is coming from the call to audio.play(). If you try to play sounds or videos with js before the user has ‘interacted’ with the page, it will throw. Try loading the page and leaving it alone and see if it errors, then try clicking some things and see if that stops the error from happening
If that’s the case, you can just wrap it in a try/catch and ignore