How to display one Chrome notification at a time? - javascript

I'm creating a Chrome Extension right now, and I'm running into a problem where the same notification is created and displayed a bunch of times. I was wondering if there is a solution on how to check and make sure that if there is already a notification, to not create a new one. Here's my code on how the notifications are created:
async function alert() {
console.log("Alert getting created");
var result = await getExpiredIndices();
var numberOfExpiredTabs = result.expiredTabArray.length;
var id = uuidv4();
var msg = `Ta daa! Your tab(s) are ready.`;
chrome.notifications.create(
id,
{
type: "basic",
iconUrl: "assets/icons/pondr_128.png",
title: "Pondr",
message: msg,
priority: 2,
requireInteraction: true,
buttons: [
{
//get indexes from storage pop them when user re-opens tabs
title: "Open",
},
{
title: "Later",
//get indexes, shift all times, pop them since they are no longer in the outdated subarray
},
],
}
);
}
chrome.notifications.onButtonClicked.addListener(async function (
notifId,
btnIdx
) {
var result1 = await getExpiredIndices();
var result2 = await getAllTabsArray();
var expiredTabArray = await result1.expiredTabArray;
var allTabsArray = await result2.allTabsArray;
if (btnIdx === 0) {
//if yes open tabs
console.log("hit yes");
console.log("Before popping allTabsArray: ", allTabsArray);
console.log("Before popping expiredTabsArray: ", expiredTabArray);
openTabsNow(expiredTabArray, allTabsArray);
} else if (btnIdx === 1) {
console.log("hit later");
console.log("Before popping allTabsArray: ", allTabsArray);
console.log("Before popping expiredTabsArray: ", expiredTabArray);
openTabsLater(expiredTabArray, allTabsArray);
//if no reapply reminder-setting
//FOR TIME BEING: will be hardcoded to push all items 3 hrs forward
}
});

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

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

SweetAlert2 Update Counter for User Feedback

Is there a way to update the text on SweetAlert2 alert to show the number of rows that have been processed in a a really long javascript loop? Unfortunately people have been leaving the page and then only half the rows get saved.
I thought I might be able to use jQuery type syntax, but not sure what the proper select might be.
$('#rowsprocessed').text(count);
swal({
title: 'Save Order.',
input: 'checkbox',
inputValue: 0,
inputPlaceholder: 'Remove Zero(s) Quantity Item(s) Before Saving the Order?',
html: 'For large templates this may take a few moments. This message will automatically close when the process is complete.',
type: 'info',
showCancelButton: true,
confirmButtonText: 'Submit',
showLoaderOnConfirm: true,
preConfirm: function(checkbox) {
return new Promise(function(resolve, reject) {
removeZeros = checkbox;
setTimeout(function() {
swal.showLoading();
$.post("/components/com_sails/views/neworderform/saveOrderHeader.php",
{
orderid: orderid,
accountid: accountid,
buyerid: buyerid,
vendorid: vendorid,
ponumber: ponumber,
specialinstr: specialinstr,
orderDate: orderDate,
shipDate: shipDate,
cancelDate: cancelDate
},
function (result) {
if (result.return == 1) {
// assign order id to holder field
$('#orderInput').jqxInput('val', result.ordernbr);
// loop through our rows and save depending on the removeZero marker
var rows = $('#jqxgrid').jqxGrid('getdisplayrows');
var rowsToRemove = [];
var linessaved = 0;
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
// get row info for delete
if ((removeZeros == 1) && row['quantity'] == 0) {
rowsToRemove.push(row.uid);
}
// run database update
$.ajax({
type: 'POST',
url: '/components/com_sails/views/neworderform/saveOrderLine.php',
data: {
orderid: result.ordernbr,
removezeros: removeZeros,
rowdata: row
},
success: function (rowSaveData) {
// alert('rowSaveData ' + rowSaveData.return + " " + rowSaveData.isbn + " " + rowSaveData.action + " " + rowSaveData.msg + " row.uid: " + row.uid);
// if there is a problem what do we do????
if (rowSaveData.return == 1) {
$('#rowsprocessed').text(i);
}
if (rowSaveData.return == -1) {
// add to error message?
}
},
datatype: 'json',
async: false});
}
if (removeZeros == 1) {
// delete our zero rows
var commit = $("#jqxgrid").jqxGrid('deleterow', rowsToRemove);
$('#jqxgrid').jqxGrid('render');
lastselectedrow = -1;
}
// set save marker??
isDirty = false;
}
else {
// there was an error saving the header
// need to get this logged
alert('Error Saving Order. Details: ' + result.msg);
}
}, "json");
resolve();
}, 2000);
});
},
allowOutsideClick: false
}).then(function() {
swal({
type: 'success',
title: 'Order saved',
html: '<b><div id="rowsprocessed">0</div></b> rows saved.',
timer: 4000
});
})
Absolutely you can, you just pass in an additional element with your {html: "..."} that you can use as a means of updating the user.
Something Like:
{
...
html: 'For large templates this may take a few moments. This message will automatically close when the process is complete.<br/><span class="swal2- status"></span>',
...
}
And then use this syntax to update:
var $status = $('.swal2-status');
$status.html("I'm an update");
See the example here:
https://jsfiddle.net/1mvnxp3L/

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

Parse Backgroundjob Matching

I'm currently programming a background job for my Parse Database.
The Database contains lots of users in the User class. All user have a 'location' column and an 'offer' and 'search' column. 'offer' and 'search' store an array of strings.
What it should do is the following:
The background job should go through all the users and check for users close to them and then check if these users match on specific skills. So if someone has "example" in 'search' and someone else has "example" in 'offer' these user match and both get a notification.
The location query does not choose users close to each other
If a user does not "offer" anything, but "searches" for something he does not get a notification
It should not constantly send push notifications when two users are close to each other (only once)
-
Parse.Cloud.job("backgroundJob", function(request, status) {
var queryAllUser = new Parse.Query(Parse.User);
Parse.Cloud.useMasterKey();
var targetList = []; //new Array();
queryAllUser.each(function(user) {
var queryMatch = new Parse.Query(Parse.User);
queryMatch.withinKilometers("location", user.get("location"), 0.1);
//if(user.get("search") != null){
queryMatch.containedIn("offer", user.get("search"));
// }
return queryMatch.first().then(function(firstUser) {
if (firstUser != null) {
console.error("THIS IS THE FIRST USER: " + firstUser.get("name"));
}
if (firstUser) {
targetList.push(user);
}
});
}).then(function() {
console.error("Length of TargetList: " + targetList.length);
if (targetList[0] != null && targetList.length != 1) {
var queryTarget = new Parse.Query(Parse.Installation);
queryTarget.containedIn('user', targetList);
return Parse.Push.send({
where: queryTarget,
data: {
alert: "Found a Match!",
badge: "Increment",
pushType: "1",
}
}, {
success: function() {
status.success("Send the Pushes!");
},
error: function(error) {
status.error(error);
}
});
}
status.success("did the job!");
},
function(error) {
status.error("error:" + error.message);
});
});

Categories

Resources