Web Notification Display Duration - javascript

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

Related

Check if notification exists in JavaScript

Chrome browser.
The script is executed every time the page is refreshed.
Is it possible to verify the existence of a notification so as not to duplicate it.
if ($('.snippet__title').length) {
var titles = document.querySelectorAll('.snippet__title')
titles.forEach((title) => {
if (title.textContent.includes('searchString')) {
var msg = title.textContent.trim()
var notification = new Notification('Element found', {
body: msg,
dir: 'auto',
icon: 'icon.jpg'
});
}
})
}
Thanks mplungjan. So I thought to do it, but I thought there are still some solutions.
Working solution using localStorage
var NotifyShowed = localStorage.getItem('NotifyShowed')
if (!NotifyShowed) {
if ($('.snippet__title').length) {
var titles = document.querySelectorAll('.snippet__title')
titles.forEach((title) => {
if (title.textContent.includes('searchString')) {
var msg = title.textContent.trim()
var notification = new Notification('Element found', {
body: msg,
dir: 'auto',
icon: 'icon.jpg'
});
localStorage.setItem('NotifyShowed', true);
}
})
}
}

How do I add a URL to a notification when using the notification API?

I have created a simple notification in a standard index.html file by adding the following script to the bottom of the page. However, my goal is to add a URL to the notification, so that when the user clicks on the notification they are taken to a specific URL (window.open). I know this can be done as when searching for an answer on Google many sites have notifications that when clicked navigate to a different page or website. Nevertheless, I have not found a solution that I can get working. Any help welcome.
Notification.requestPermission();
Notification.requestPermission((permission) => {
switch (permission) {
case 'granted': {
console.log('Now we can send notifications!');
doNotify();
break;
}
case 'denied': {
console.log('User close the request pop-up!')
}
}
});
function doNotify(){
const title = "Test notification";
const img = "https://via.placeholder.com/600x400";
const text = Lorem ipsum;
const options = {
body: text,
icon: "https://via.placeholder.com/600x400",
data: {
},
vibrate: [200, 100, 200],
tag: "new-product",
image: img,
badge: "https://via.placeholder.com/128x128",
};
notification.onclick = function(event) {
event.preventDefault(); // prevent the browser from focusing the Notification's tab
window.open('http://www.mozilla.org', '_blank');
}
navigator.serviceWorker.ready.then(function(serviceWorker) {
serviceWorker.showNotification(title, options);
});
// setTimeout( n.close.bind(n), 9000); //close notification after 3 seconds
}
You missed a line that is very important for this to work. Define a notification with the Notification constructor in which you enter the title and options variables.
function doNotify() {
const title = "Test notification";
const img = "https://via.placeholder.com/600x400";
const text = "Lorem ipsum";
const options = {
body: text,
icon: "https://via.placeholder.com/600x400",
data: {},
vibrate: [200, 100, 200],
tag: "new-product",
image: img,
badge: "https://via.placeholder.com/128x128",
};
// Add this line.
const notification = new Notification(title, options);
notification.onclick = function(event) {
event.preventDefault(); // prevent the browser from focusing the Notification's tab
window.open('http://www.mozilla.org', '_blank');
}
navigator.serviceWorker.ready.then(function(serviceWorker) {
serviceWorker.showNotification(title, options);
});
}

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

Ionic LocalStorage

I'm building an app at the moment, where you have a To Do List.
These Task should be saved. I don't know why it doenst work :(
Every time you click on Create Task the task should automatically be saved.
And every time you open the app it should be displayed.
Here is the Popup with the Create task button
Popup
$scope.newTask = function() {
$ionicPopup.prompt({
title: "New Task",
template: "Enter Task:",
inputPlaceholder: "What do you need to do?",
okText: 'Create Task'
}).then(function(res) { // promise
if (res) $scope.tasks.push({title: res, completed: false});
})
};
You need to use LocalStorage. See if it's helpful: http://learn.ionicframework.com/formulas/localstorage/
You need to save it using localStorage like this:
$scope.newTask = function() {
$ionicPopup.prompt({
title: "New Task",
template: "Enter Task:",
inputPlaceholder: "What do you need to do?",
okText: 'Create Task'
}).then(function(res) { // promise
if (res)
var randomNumber = Math.floor((Math.random() * 100) + 1);
var task = {title: res, completed: false};
window.localStorage.setItem("Task" + randomNumber, JSON.stringify(testObject));
})
};
Then in your controller you need to retrieve them
$scope.readTasks = function() {
for (var a in localStorage) {
$scope.tasks.push(JSON.parse(localStorage[a]));
}
};
In your view you can call the function like this:
<ion-content ng-init="readTasks()">

Categories

Resources