Let HTML5 Notification disappear after a delay? - javascript

I want to use HTML5 notifications which work great.
The problem is that they never disappear.
How can I set a delay after which the HTML5 notification disappear?

You can just call the .close() method:
var n = new Notification("Hello");
setTimeout(n.close.bind(n), 2000);
See here on MDN for details.

The notification should have a built in close button, no?
HTML
Notify me!
JS
<script>
var Notification = window.Notification || window.mozNotification || window.webkitNotification;
Notification.requestPermission(function (permission) {
// console.log(permission);
});
function show() {
var instance = new Notification(
"Hey", {
body: "this is a message"
}
);
instance.onclick = function () {
// Something to do
};
instance.onerror = function () {
// Something to do
};
instance.onshow = function () {
// Something to do
};
instance.onclose = function () {
// Something to do
};
return false;
}
</script>

Related

How would a nested function look like in this clickHandler()?

I'm stalled with this clicHandler() from this question:
function clickHandler(evt) {
// Activate the circle
activateCircle(evt.target.id);
// Remember which one was clicked, so that we can
// highlight the right one when we get to the subpage
sessionStorage.setItem("selectedMenuId", evt.target.id);
}
The problem is that there are 5 different circles, and I need the clickHandler() to know which one has been clicked and return the correct activateCircle(evt.target.id).
I was thinking about something like this (I might be wrong):
getElementById("c1").onclick = goTransdisciplinary () {
location.href = "/trans-disciplinary";
};
getElementById("c2").onclick = goDatademocracy () {
location.href = "/data-democracy";
};
getElementById("c3").onclick = goCryptography () {
location.href = "/cryptography-and-math";
};
getElementById("c4").onclick = goTranslation () {
location.href = "/translation";
};
getElementById("c5").onclick = goApplication () {
location.href = "/application";
};
But how would a nested function look like?

How can I trigger modal boxes using the following javascript code?

Hey guys I need just a little bit of help with this.
So I have modal boxes hiding on my page and when I click on them using the video platform VERSE they work perfectly.
My questions is: How can I call the same modal boxes if I wan to call them from a regular link or button on the page.
Here is the sample:
http://digitalfeast.com/clients/nccv/ncc-verse.html
Here is my Javascript code:
(function() {
(function() {
window.onload = function() {
var frame = document.getElementsByName("verse-iframe")[0].contentWindow;
// Variables below (i.e. "menu-1") reference div id from your markup
function receiveMessage(event) {
var data = (typeof event.data === "String") ? JSON.parse(event.data) : event
var modalWindow1 = document.getElementById("ruben-1");
var modalWindow2 = document.getElementById("ruben-2");
var modalWindow3 = document.getElementById("menu-3");
var modalWindow4 = document.getElementById("menu-4");
// Variables below (i.e. "menu-1") reference the unique callback names entered for your hotspots in the Verse editor
if (data.data["identifier"] === "ruben-1") {
modalWindow1.style.display = "block";
}
if (data.data["identifier"] === "ruben-2") {
modalWindow2.style.display = "block";
}
if (data.data["identifier"] === "menu-3") {
modalWindow3.style.display = "block";
}
if (data.data["identifier"] === "menu-4") {
modalWindow4.style.display = "block";
}
}
var closeBtns = document.getElementsByClassName("modal-close");
for (var i = 0; i < closeBtns.length; i++) {
var btn = closeBtns[i];
btn.onclick = function (event) {
event.target.parentNode.parentNode.style.display = "none";
frame.postMessage({action: "play"}, "*");
};
}
window.addEventListener('message', receiveMessage);
var frame = document.getElementsByName("verse-iframe")[0].contentWindow;
};
}());
}());
Given your code, all you need to do is send the window a message using the Messaging API inside your button click handler.
Your event listener will then execute the receiveMessage function and open your model for ruben-1.
window.onload = () => {
document.querySelector('[data-modal="ruben-1"]').addEventListener("click", (e) => {
let postData = {
identifier: e.target.dataset.modal
};
window.postMessage(postData, "*");
});
window.addEventListener('message', m => {
alert(m.data.identifier);
});
}
<button data-modal="ruben-1">Ruben-1 Video</button>

javascript alert box close automatically

I need a function, which close the alert box (window) in few seconds automatically:
$("#upload-btn").on('click', function() {
var dt = canvas.toDataURL('image/jpeg');
if (window.Lollipop) {
window.Lollipop.save(dt);
}
$.post('saveImage.php',
{
img : dt
}, function(data) {
if(data){
alert("Image Saved");
}
});
There is no web api function to close the opened alert.
It's NOT possible via standard Web API to close the standard alert box, but you can define your own function or override the alert() function (which is the bad way, better to define own).
const temporaryAlert = function( text, duration ) {
console.assert(typeof text === "string");
console.assert(text.length > 0);
console.assert(typeof duration === "number");
const item = document.createElement("div");
item.innerText = text;
// item.style - add some CSS-stuff to customize the box style
window.setTimeout(() => item.parentNode.removeChild(item), duration);
return document.body.appendChild(item);
};

JS - Window Focus and Bring to front in Firefox

I am trying to set up a tiny script for Firefox that runs in a javascript add-on (Greasemonkey). We have a queue that we monitor for arriving tickets, I coded something that is supposed to refresh the page every 2 minutes and do the following:
if tickets are found by this condition
if (isEmpty($('#incident_table > tbody'))&isEmpty($('#task_table > tbody')))
then I want the following to happen:
- task-bar blinks with a message so it is visible
- if the window is focused it will display "Tickets in the queue!" alert right away
- if the window is not focused, it will wait for 10 seconds, if still not focused - display "Tickets in the queue!" alert and bring the window to front.
I've got the refresh and blinking part, but I cannot get the focus part to work... I've been looking around and I see that Firefox is having some "issues" with window.focus() and all the "bring to front", most of the code below is inspired by stuff I've found on this site.
Any input is appreciated! I am also opened to alternatives - in the end, what this needs to do is refresh, check the condition and notify if I am already looking at it or if it is not focused wait 10 seconds with a "soft notify" (blink) then bring it to the front if I don't notice it.
Regards,
Dan
{
newExcitingAlerts = (function () {
var oldTitle = document.title;
var msg = "***NEW***";
var timeoutId;
var blink = function() { document.title = document.title == msg ? 'Tickets in queue!' : msg; };
var clear = function() {
clearInterval(timeoutId);
document.title = oldTitle;
window.onmousemove = null;
timeoutId = null;
};
return function () {
if (!timeoutId) {
timeoutId = setInterval(blink, 1000);
window.onmousemove = clear;
}
};
}());
$(document).ready(function(){
function isEmpty( el ){
return !$.trim(el.html());
}
if (isEmpty($('#incident_table > tbody'))&isEmpty($('#task_table > tbody'))) {
}
else{
newExcitingAlerts();
}
setTimeout(function() {
location.reload();
}, 120000);
});
}
Here is the alternative I've used, works like a charm. Web API notifications.
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('Tickets in queue!', {
icon: 'http://siliconangle.com/files/2014/05/servicenow-icon.png',
body: "There are new tickets in queue, please acknowledge!",
});
notification.onclick = function () {
window.open("https://cchprod.service-now.com/task_list.do?sysparm_query=assignment_group%3D3139519437b7f1009654261953990e1f^ORassignment_group%3D31de85e337818a00ef8898a543990e99^ORassignment_group%3Da40029e937ec420065aa261953990eb5^ORassignment_group%3De903ad2d37ec420065aa261953990ecb^ORassignment_group%3Dd25fe5323779c24065aa261953990e54^ORassignment_group%3D508639363779c24065aa261953990e29^ORassignment_group%3D51fe5a37379e0a00ef8898a543990ea2^ORassignment_group%3D3d8171b23779c24065aa261953990e21^ORassignment_group%3Decfe5a37379e0a00ef8898a543990e6c^ORassignment_group%3D48c0b9723779c24065aa261953990e5d^ORassignment_group%3De5fde9fe3739c24065aa261953990e75^ORassignment_group%3D15fe5a37379e0a00ef8898a543990e99^ORassignment_group%3D15fe5a37379e0a00ef8898a543990ea7^ORassignment_group%3D1ed3f1f23779c24065aa261953990e47^active%3Dtrue^sys_class_name%3Dincident^ORsys_class_name%3Dsc_req_item^assigned_toISEMPTY&sysparm_first_row=1&sysparm_view=");
};
}
}
{
newExcitingAlerts = (function () {
var oldTitle = document.title;
var msg = "***NEW***";
var timeoutId;
var blink = function() {
document.title = document.title == msg ? 'Tickets in queue!' : msg;
};
var clear = function() {
clearInterval(timeoutId);
document.title = oldTitle;
window.onmousemove = null;
timeoutId = null;
};
return function () {
if (!timeoutId) {
timeoutId = setInterval(blink, 1000);
window.onmousemove = clear;
}
};
}
());
$(document).ready(function () {
function isEmpty(el) {
return !$.trim(el.html());
}
var x = document.getElementById("task_table").getAttribute("grand_total_rows");
if( x != "0" ) {
newExcitingAlerts();
notifyMe();
}
else
{
}
setTimeout(function() {
location.reload();
}
, 120000);
});
}
In Windows operating system you cannot focus the window while the window of another process is focused. You have to use js-ctypes to get around this.
On Mac OS X and Linux, I'm not sure if you can make your process steal focus from another with the normal functions. But if you can't you can for sure use js-ctypes to get the job done.
Here is how to do it in Windows - https://stackoverflow.com/a/32038880/1828637
It is harder on Windows then on OS X and Linux. I have focused windows on all systems using js-ctypes. So if you can't find out how to do with the functions available to you, let me know.

YouTube API - iframe onStateChange events

I'm using the iframe YouTube API and I want to track events, for example, sending data to google analytics, when user start and stop video.
<iframe src="https://www.youtube.com/embed/DjB1OvEYMhY"></iframe>
I looked https://developers.google.com/youtube/iframe_api_reference?csw=1 and did not find an example how to do that. The example creates iframe and defines onReady and onStateChange as well. How would I do same when I've only iframe on page?
This example listens to every play/pause action the user makes, using onPlayerStateChange with its different states, and prints (records) them.
However, you need to create your own record function to do whatever you want with this data.
You also need an ID on your iframe (#player in this case) and to add ?enablejsapi=1 at the end of its URL. And of course, make sure to include the Youtube iframe API.
Note
It's important to declare the API after your code, because it calls onYouTubeIframeAPIReady when it's ready.
<!DOCTYPE html>
<html>
<body>
<iframe id="player" src="https://www.youtube.com/embed/DjB1OvEYMhY?enablejsapi=1"></iframe>
<h5>Record of user actions:</h5>
<script>
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player( 'player', {
events: { 'onStateChange': onPlayerStateChange }
});
}
function onPlayerStateChange(event) {
switch(event.data) {
case 0:
record('video ended');
break;
case 1:
record('video playing from '+player.getCurrentTime());
break;
case 2:
record('video paused at '+player.getCurrentTime());
}
}
function record(str){
var p = document.createElement("p");
p.appendChild(document.createTextNode(str));
document.body.appendChild(p);
}
</script>
<script src="https://www.youtube.com/iframe_api"></script>
</body>
</html>
JS Fiddle Demo
Here is a version that doesn't use Youtubes iframe API script. The only drawback is that the iframe API might change.
<iframe id="player" src="https://www.youtube.com/embed/dQw4w9WgXcQ?enablejsapi=1"></iframe>
var addYoutubeEventListener = (function() {
var callbacks = [];
var iframeId = 0;
return function (iframe, callback) {
// init message listener that will receive messages from youtube iframes
if(iframeId === 0) {
window.addEventListener("message", function (e) {
if(e.origin !== "https://www.youtube.com" || e.data === undefined) return;
try {
var data = JSON.parse(e.data);
if(data.event !== 'onStateChange') return;
var callback = callbacks[data.id];
callback(data);
}
catch(e) {}
});
}
// store callback
iframeId++;
callbacks[iframeId] = callback;
var currentFrameId = iframeId;
// sendMessage to frame to start receiving messages
iframe.addEventListener("load", function () {
var message = JSON.stringify({
event: 'listening',
id: currentFrameId,
channel: 'widget'
});
iframe.contentWindow.postMessage(message, 'https://www.youtube.com');
message = JSON.stringify({
event: "command",
func: "addEventListener",
args: ["onStateChange"],
id: currentFrameId,
channel: "widget"
});
iframe.contentWindow.postMessage(message, 'https://www.youtube.com');
});
}
})();
addYoutubeEventListener(document.getElementById("player"), function(e) {
switch(e.info) {
case 1:
// playing
break;
case 0:
// ended
break;
}
});
Sometimes the event load is not enough to ensure that the document inside the iframe is ready. If the iframe is in a different domain it is not possible to subscribe to see when it is ready.
A possible workaround is to record when an event is received from the iframe, if after subscribing no event was received try again:
var addYoutubeEventListener = (function() {
var callbacks = [];
var iframeId = 0;
var subscribed = [];
return function (iframe, callback) {
// init message listener that will receive messages from youtube iframes
if(iframeId === 0) {
window.addEventListener("message", function (e) {
if(e.origin !== "https://www.youtube.com" || e.data === undefined) return;
try {
var data = JSON.parse(e.data);
subscribed[data.id] = true;
if(data.event !== 'onStateChange') return;
var callback = callbacks[data.id];
callback(data);
}
catch(e) {}
}, true);
}
// store callback
iframeId++;
callbacks[iframeId] = callback;
subscribed[iframeId] = false;
var currentFrameId = iframeId;
//console.log("adding event listener to iframe id " + iframeId);
// sendMessage to frame to start receiving messages
iframe.addEventListener("load", function () {
var tries = 0;
var checkSubscribed = function()
{
if (subscribed[currentFrameId]) {
//console.log("subscribed succesfully " + currentFrameId)
}
else
{
tries++;
//console.log("Try again " + currentFrameId + " (" + tries + ")");
if (tries < 100) {
doSubscribe();
}
else
{
console.log("Unable to subscribe" + currentFrameId );
}
}
}
var doSubscribe = function()
{
var message = JSON.stringify({
event: 'listening',
id: currentFrameId,
channel: 'widget'
});
iframe.contentWindow.postMessage(message, 'https://www.youtube.com');
message = JSON.stringify({
event: "command",
func: "addEventListener",
args: ["onStateChange"],
id: currentFrameId,
channel: "widget"
});
iframe.contentWindow.postMessage(message, 'https://www.youtube.com');
setTimeout(checkSubscribed, 100);
};
doSubscribe();
}, true);
}
})();

Categories