Using setInterval and JavaScript - javascript

I'm working with Notification API but i can't make it work with SetInterval(), can somebody point out what i'm doing wrong. As long as i click the event, the notification only displays once. Here is my code:
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('notifyBtn').addEventListener('click', function() {
if (!('Notification' in window)) {
alert('Web Notification is not supported');
return;
} else {
setInterval(Notification.requestPermission(function(permission) {
var notification = new Notification("Hi there!", {
body: 'I am here to talk about HTML5 Web Notification API',
icon: 'icon.png',
dir: 'auto'
});
setTimeout(function() {
notification.close();
}, 2000);
}),5000);
}
;
});
});
I'm really stucked here, please halp.

You need to pass valid callback to setInterval(). Instead, you are passing the result of some method. Try this:
setInterval(function () {
Notification.requestPermission(function(permission) {
var notification = new Notification("Hi there!", {
body: 'I am here to talk about HTML5 Web Notification API',
icon: 'icon.png',
dir: 'auto'
});
setTimeout(notification.close, 2000);
})}, 5000);
Bonus: see how I simplified your setTimeout callback, by just passing the notification.close method itself, instead of calling it in anonymous function. Much cleaner.

Wrap your method in anonymous function
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('notifyBtn').addEventListener('click', function() {
if (!('Notification' in window)) {
alert('Web Notification is not supported');
return;
} else {
setInterval(function(){Notification.requestPermission(function(permission) {
var notification = new Notification("Hi there!", {
body: 'I am here to talk about HTML5 Web Notification API',
icon: 'icon.png',
dir: 'auto'
});
setTimeout(function() {
notification.close();
}, 2000);
})},5000);
}
;
});
});

I found something like this :
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('notifyBtn').addEventListener('click', function() {
if (!('Notification' in window)) {
alert('Web Notification is not supported');
return;
} else {
setInterval(notify, 5000);
}
});
function notify() {
Notification.requestPermission(function(permission) {
var n = new Notification("Hi there!", {
body: 'I am here to talk about HTML5 Web Notification API',
icon: 'icon.png',
dir: 'auto'
})
setTimeout(function(){n.close()}, 2000)
})
}

Related

Web Notification Display Duration

I am sending a notification web. I want to display up to ten minutes if the user does not click on the notification.
I used setTimeout, but it is displayed for about 15 seconds and then hidden.
please guide me.
This is my code:
function notify(title, message, link) {
var option = {
body: message,
dir: 'rtl',
title: title,
icon: '/Images/notification.png',
}
var notify = new Notification(title, option);
notify.onclick = function () {
window.open(link, '_blank');
notify.close();
};
notification.onshow = function () {
setTimeout(notification.close, 600000);
}
}
i have update your code. May this helps you !
var options = {
body: "My notification message",
dir : "ltr",
requireInteraction: true
};
var notify = new Notification('Hello User', options);
notify.onclick = function () {
notify.close();
};
notify.onshow = function () {
setTimeout(()=>{
notify.close();
}, 15000);
}
Just add the property requireInteraction.
var option = {
body: message,
dir: 'rtl',
title: title,
icon: '/Images/notification.png',
requireInteraction: true,
}
The requireInteraction read-only property of the Notification
interface returns a Boolean indicating that a notification should
remain active until the user clicks or dismisses it, rather than
closing automatically.
See here: https://developer.mozilla.org/en-US/docs/Web/API/notification/requireInteraction

Redirect after the flash message disappears in Angular2

I have a function which calls a service.
submitPost(value:any)
{
this._adminLogin.postAdminLogin(this.adminLoginmodel).subscribe(
data => {
this.responseStatus = data;
if(this.responseStatus.status == 1)
{
localStorage.setItem('admin_id', this.responseStatus.detail.id);
this._flashMessagesService.show(this.responseStatus.message, { cssClass: 'alert-success', timeout: 5000 });
top.location.href = 'admin/dashboard';
}
else
{
this._flashMessagesService.show(this.responseStatus.message, { cssClass: 'alert-danger', timeout: 2000 });
}
},
err => {
console.log(err)
},
() => {}
);
this.status = true;
}
My concern is with this section of code:-
if(this.responseStatus.status == 1)
{
localStorage.setItem('admin_id', this.responseStatus.detail.id);
this._flashMessagesService.show(this.responseStatus.message, { cssClass: 'alert-success', timeout: 5000 });
top.location.href = 'admin/dashboard';
}
Is there any way by which the redirect action could take place after the flash message disappears after 5000 ms? Something like this:-
if(this.responseStatus.status == 1)
{
localStorage.setItem('admin_id', this.responseStatus.detail.id);
this._flashMessagesService.show(this.responseStatus.message, { cssClass: 'alert-success', timeout: {function(){ top.location.href = 'admin/dashboard'; }, 5000 });
}
The following code should navigate after the message disappears. Yout flashMessage will be displayed for 5000 ms and your navigate should happen after 7000ms
if(this.responseStatus.status == 1)
{
localStorage.setItem('admin_id', this.responseStatus.detail.id);
this._flashMessagesService.show(this.responseStatus.message, { cssClass: 'alert-success', timeout: 5000 });
setTimeout(()=>{
top.location.href = 'admin/dashboard';
},7000);
}
I would do this by having the _flashMessagesService.show() return an Observable.
In the _flashMessageService, something like this:
myObserver : Observer<any>
function show(){
// do stuff
return Observable.create(observer =>{
this.myObserver =observer;
});
}
When you're ready to resolve the Observable, you can do:
this.myObserver.next('Possibly some value here');
this.myObserver.complete();
In your invoking code
this._flashMessagesService.show()
.subscribe(result=> { top.location.href = 'admin/dashboard'});}
I have been working on something similar.
An alternate approach, perhaps simpler is to just use Observable.timer in your main component:
Observable.timer(5000).subscribe(result=> { top.location.href = 'admin/dashboard'});
I prefer the first way, because it is contingent on the flashMessage service deciding when the flash message goes away, not on a hard coded time value.

socket.emit doesn't work inside setTimeout() nodejs

The first playerHandler.nextTurn() will return the first player from the player list with his corresponding socket id .But calling currsocket.emit won't do anything. I then tried io.emit which emits to all other players . Since I have max of 2 players , the event doesn't trigger inside the first player client socket.
Calling the second player currsocket.emit would work properly .
It seems there is some issue with the setTimeout() , since in my other code , this works without any issues (without timeout).
socket.on('add-player', (player) => {
//console.log('socket add player hits');
console.log("add user name :" + player.name);
//add the new player
var newPlayer = { 'id': socket.id.toString(), 'name': player.name };
//dont use this. for the var declared above
var canWeKeepHim = { value: false };
var package = playerHandler.methods.addNewPlayer(newPlayer, canWeKeepHim);
//on successful addition of new player add him to gameroom socket room
if (canWeKeepHim.value) {
socket.join('gameroom');
console.log(player.name + 'joined socket room');
}
socket.emit('add-player-message', { type: 'success-message', package: package });
io.emit('add-player-list', playerHandler.methods.getNewPlayer());
//is the async nature of socket events a problem , the start-game never seems to be true;
if (GameHandler.currentGameState == GameHandler.yetToStartGame && playerHandler.methods.doWeHaveMaxPlayers()) {
GameHandler.changeCurrentGameState(GameHandler.gameHasStarted);
var delay = 3000;
io.to('gameroom').emit('start-game', { value: true, delay: delay });
//if the game state is still gameHasStarted after delay then fire the gameplay events
GameHandler.gameArenaRedirectTimer = setTimeout(() => {
if (GameHandler.currentGameState == GameHandler.gameHasStarted) {
console.log('hey this works after 10s');
var currentPlayerTurn = playerHandler.methods.nextTurn();
currentPlayerTurn = playerHandler.methods.nextTurn();;
var currsocket = io.sockets.sockets[currentPlayerTurn.id];
currsocket.emit('next-turn', { myturn: true });
//console.log(io.sockets.so)
// io.emit('next-turn', { myturn: false, playerName: currentPlayerTurn.name });
//io.to('gameroom').emit('next-turn', { myturn: false, playerName: currentPlayerTurn.name });
}
}, delay);
}
});
I found out that moving the setTimeout out of the socket.on event listener callback and out of the io.on event listener fixed the issue.
function startCountDownToStartGame(callback, delay, arg) {
if (GameHandler.currentGameState == GameHandler.gameHasStarted) {
GameHandler.gameArenaRedirectTimer = setTimeout(callback, delay, arg);
}
};
io.on('connection', (socket) => {
console.log('user connected :' + socket.id);
socket.on('disconnect', function () {
console.log('user disconnected');
//TODO : remove player from the player list once hes disconnected
});
socket.on('add-player', (player) => {
//console.log('socket add player hits');
console.log("add user name :" + player.name);
//add the new player
var newPlayer = { 'id': socket.id.toString(), 'name': player.name };
//dont use this. for the var declared above
var canWeKeepHim = { value: false };
var package = playerHandler.methods.addNewPlayer(newPlayer, canWeKeepHim);
//on successful addition of new player add him to gameroom socket room
if (canWeKeepHim.value) {
socket.join('gameroom');
console.log(player.name + 'joined socket room');
}
socket.emit('add-player-message', { type: 'success-message', package: package });
io.emit('add-player-list', playerHandler.methods.getNewPlayer());
if (GameHandler.currentGameState == GameHandler.yetToStartGame && playerHandler.methods.doWeHaveMaxPlayers()) {
GameHandler.changeCurrentGameState(GameHandler.gameHasStarted);
var delay = 3000;
io.to('gameroom').emit('start-game', { value: true, delay: delay });
delay += 1000;// this is a temp fix
//it seems calling the settimeout within the socket.on will somehow affect the emit functions for all other socket
//other than the current socket , by placing the settimeout outside , it fixed the problem .
startCountDownToStartGame((socket) => {
var currentPlayerTurn = playerHandler.methods.nextTurn();
var currsocket = io.sockets.sockets[currentPlayerTurn.id];
currsocket.emit('next-turn', { myturn: true });
currsocket.broadcast.to('gameroom').emit('next-turn', { myturn: false, playerName: currentPlayerTurn.name });
}, delay, socket);
}
});
}
Try passing socket to your setTimout
GameHandler.gameArenaRedirectTimer = setTimeout((socket) => {
if (GameHandler.currentGameState == GameHandler.gameHasStarted) {
console.log('hey this works after 10s');
var currentPlayerTurn = playerHandler.methods.nextTurn();
currentPlayerTurn = playerHandler.methods.nextTurn();;
var currsocket = io.sockets.sockets[currentPlayerTurn.id];
currsocket.emit('next-turn', { myturn: true });
//console.log(io.sockets.so)
// io.emit('next-turn', { myturn: false, playerName: currentPlayerTurn.name });
//io.to('gameroom').emit('next-turn', { myturn: false, playerName: currentPlayerTurn.name });
}
}, delay,socket);

Javascript - prevent navigation during file upload

I have a vue component for video upload, where I am warning a user when he tries to navigate away during the video upload that he will lose the file if he does so, like this:
ready() {
window.onbeforeunload = () => {
if (this.uploading && !this.uploadingComplete && !this.failed) {
this.confirm('Are you sure you want to navigate away? Your video won't be uploaded if you do so!');
}
}
}
I am using sweetalert to alert the user about it. But how can I then make it stay on the same page, and prevent the navigation away before he confirms that he wants to navigate away?
This is the whole component:
<script>
function initialState (){
return {
uid: null,
uploading: false,
uploadingComplete: false,
failed: false,
title: null,
link: null,
description: null,
visibility: 'private',
saveStatus: null,
fileProgress: 0
}
}
export default {
data: function (){
return initialState();
},
methods: {
fileInputChange() {
this.uploading = true;
this.failed = false;
this.file = document.getElementById('video').files[0];
this.store().then(() => {
var form = new FormData();
form.append('video', this.file);
form.append('uid', this.uid);
this.$http.post('/upload', form, {
progress: (e) => {
if (e.lengthComputable) {
this.updateProgress(e)
}
}
}).then(() => {
this.uploadingComplete = true
}, () => {
this.failed = true
});
}, () => {
this.failed = true
})
},
store() {
return this.$http.post('/videos', {
title: this.title,
description: this.description,
visibility: this.visibility,
extension: this.file.name.split('.').pop()
}).then((response) => {
this.uid = response.json().data.uid;
});
},
update() {
this.saveStatus = 'Saving changes.';
return this.$http.put('/videos/' + this.uid, {
link: this.link,
title: this.title,
description: this.description,
visibility: this.visibility
}).then((response) => {
this.saveStatus = 'Changes saved.';
setTimeout(() => {
this.saveStatus = null
}, 3000)
}, () => {
this.saveStatus = 'Failed to save changes.';
});
},
updateProgress(e) {
e.percent = (e.loaded / e.total) * 100;
this.fileProgress = e.percent;
},
confirm(message) {
swal({
title: message,
text: null,
type: "warning",
showCancelButton: true,
cancelButtonText: "Cancel",
cancelButtonColor: '#FFF',
confirmButtonColor: "#2E112D",
confirmButtonText: "Yes, delete"
}).then(function(){
this.$data = initialState();
}.bind(this), function(dismiss) {
// dismiss can be 'overlay', 'cancel', 'close', 'esc', 'timer'
if (dismiss === 'cancel') { // you might also handle 'close' or 'timer' if you used those
// ignore
} else {
throw dismiss;
}
})
}
},
ready() {
window.onbeforeunload = () => {
if (this.uploading && !this.uploadingComplete && !this.failed) {
this.confirm('Are you sure you want to navigate away? Your video won't be uploaded if you do so!');
}
}
}
}
</script>
Mozilla documentation suggests
window.onbeforeunload = function(e) {
var dialogText = 'Dialog text here';
e.returnValue = dialogText;
return dialogText;
};
and also states that:
Since 25 May 2011, the HTML5 specification states that calls to window.alert(), window.confirm(), and window.prompt() methods may be ignored during this event. See the HTML5 specification for more details.
Source contains many other details regarding reasons and what to expect from modern browsers.
This question seems to be a duplicate of yours.
This answer suggests that to avoid weird browser behaviour you should set handler only when it's to prevent something (that is while navigating away should trigger a confirmation dialog)
But how can I then make it stay on the same page, and prevent the navigation away before he confirms that he wants to navigate away?
Add return false; to stop the event.
if (this.uploading && !this.uploadingComplete && !this.failed) {
this.confirm("Are you sure you want to navigate away? Your video won't be uploaded if you do so!");
return false; // <==== add this
}
return false; does 3 separate things when you call it :
event.preventDefault(); – It stops the browsers default behaviour.
event.stopPropagation(); – It prevents the event from propagating (or “bubbling up”) the DOM.
Stops callback execution and returns immediately when called.

Google Chrome extension to close notification after user click

The Chrome extension works fine. My problem is that the notification closes in 7 seconds. I want for the user click to close the notification.
function engine(){
var latestId;
var ids;
var messages = [];
var newmessage = [];
$.get('http://localhost/site/json.php',function (data){
var json = $.parseJSON(data);
messages = json;
ids = json[0].id;
if(latestId == ids){
//no update
}else if(latestId === undefined){
var run = {
type: "basic",
title: "Title",
message: "Some message",
iconUrl : "icon.png",
};
chrome.notifications.create(run);
}
});
}
First create your notification and give it a notificationID parameter to close it later.
var notification = {
type:"basic",
title:"News From Us!",
message:"Google Chrome Updated to v50!",
iconUrl:"assets/images/icon.png"
};
chrome.notifications.create("notfyId",notification);
On notification click you can close notification using its id (which is "notfyId")
function forwardNotfy(){
chrome.notifications.clear("notfyId");
window.open(url); //optional
}
chrome.notifications.onClicked.addListener(forwardNotfy);
Now, when you click your notification it'll close.
This feature is currently only implemented in the beta channel, and not in the latest version of chrome. See here for details.
When it is implemented, you will be able to use requireInteraction : True like:
var run = {
type: "basic",
title: "Title",
message: "Some message",
iconUrl : "icon.png",
requireInteraction : True,
}
to implement this.
You can use notification.close();:
setTimeout(function() {
notification.close();
}, 2000);
Demo:
// request permission on page load
document.addEventListener('DOMContentLoaded', function () {
if (Notification.permission !== "granted")
Notification.requestPermission();
});
function notifyMe() {
if (!Notification) {
alert('Desktop notifications not available in your browser. Try Chromium.');
return;
}
if (Notification.permission !== "granted")
Notification.requestPermission();
else {
var notification = new Notification('Notification title', {
icon: 'http://cdn.sstatic.net/stackexchange/img/logos/so/so-icon.png',
body: "Hey there! You've been notified!x",
});
notification.onclick = function () {
window.open("http://stackoverflow.com/a/13328397/1269037");
};
setTimeout(function() {
notification.close();
}, 2000);
}
}
<button onclick="notifyMe()">
Notify me!
</button>
JSBin Demo
notification.close() is used to close any notification.
For more information please see the below code-
To create the notification:
var notification = new Notification('OnlineOfferPrice', {
icon: 'icon.png',
body: "Test Message",
});
If you want to perform operation on notification click please use the below code. After your business logic it will automatically close-
notification.onclick = function () {
//write your business logic here.
notification.close();
};
If notification is not clicked and you want to close it automatically after 6 seconds-
setTimeout(function() { notification.close(); }, 6000);

Categories

Resources