I recently saw a youtube tutorial on how to create desktop notifications and I thought it would be a good idea to have it serve as a reminder. For eg, say I want a specific reminder to appear(as a desktop notification) every 30 mins. This reminder should only be triggered when the trigger button is clicked. The issue is, with the code I have below, the setinterval method only seems to execute once. It seems to work fine if I don't include the click event, but as soon as I add the click event, it fails to repeat. Any suggestions?
Here's a snippet of what I have:
Trigger
<script type="text/javascript">
var myVar;
function showalert(){
var notify;
notify = new Notification('Reminder!',{
body:'How are you?'
});
window.location = '?message=' + this.tag;
}
function notifyme() {
myVar = setInterval(showalert, 5000);
}
It only works once because you redirect the browser with the line window.location = '?message=' + this.tag;, and when the page reloads, you have to click the anchor to start the interval again
Trigger
<script type="text/javascript">
var myVar;
function showalert() {
var notify;
notify = new Notification('Reminder!', {
body: 'How are you?'
});
}
function notifyme() {
myVar = setInterval(showalert, 5000);
}
Note that you generally have to ask for permission to show notifications
function showalert() {
var notify;
notify = new Notification('Reminder!', {
body: 'How are you?'
});
}
function notifyme() {
if (Notification.permission === "granted") {
var myVar = setInterval(showalert, 1000);
} else {
Notification.requestPermission(function(permission) {
if (permission === "granted") {
var myVar = setInterval(showalert, 1000);
}
});
}
}
Trigger
Related
Problem: I have a asp.net button and on click of that I am displaying another window using window.open() at the client side using <script></script>
"I actually, need a popup (alert message) to be displayed on my parent page where my button is located once the user closes the child window."
Couple of things I tried are as follows:
I tried using setTimeOut() to have a time out for some milliseconds. This does not work as the control is not waiting until the time out is complete. It just proceeds to execute next set of code.
I tried using setInterval() but for some reason it is not working for me. Below is the code snippet of that:
$(document).ready(function () {
$('#<%=btnClick.ClientID%>').bind('click', function () {
var newWindow = window.open("http://www.google.com/", "google", 'resizable=1,width=900,height=800,scrollbars=1', '_blank');
newWindow.moveTo(0, 0);
var test = setInterval(function (e) {
if (newWindow.closed) {
alert("HEYY");
clearInterval(test);
__doPostBack("<%= btnClick.UniqueID %>", "");
}
else {
e.preventDefault();
}
}, 5000);
});
});
.
I also tried making an ajax call to open the new window and make it async : false, it again did not help me.
Bring your window and timer variable out of scope of the event handler. You need to do a polling i.e. periodically keep on checking if the windows has been closed. Using setInterval to do a polling will do the job.
var newWin, pollTimer;
$('#btnId').bind('click', function () {
newWin = window.open("...", "...", "");
pollTimer = window.setInterval(function() {
if (newWin.closed) {
window.clearInterval(pollTimer);
callCodeWhenPopupCloses();
}
}, 5000);
});
function callCodeWhenPopupCloses() {
alert("Popup closed.");
...
}
I'm wanting a button that when clicked will refresh the current page after a specified amount of time.
I currently have:
<script type="text/javascript">
setTimeout(function reload(){
location = ''
},1000)
</script>
<button onclick="reload()">Reload</button>
However, that JUST reloads the page without even having to click the button. I'm wanting the button to execute the script, and also a button to STOP the page reload.
This should be really simple but I can't figure it out :(
******EDIT**********
I'd also like the script to run on an infinite loop after the button is clicked.
Your setTimeout is called on page load. You need to put it inside the reload() function:
function reload() {
setTimeout(function() {
window.location.reload();
}, 1000);
}
To make the timer run every x seconds and reload only a part of the page you would need to use setInterval and an AJAX request, something like this:
var timer;
function reload() {
timer = setInterval(function() {
$.post('foo.html', function(data) {
$('#bar').html(data);
});
}, 1000);
}
function clear() {
clearInterval(timer);
}
This should do the trick
<script type="text/javascript">
function reload(){
setTimeout(function(){location.reload()}, 3000);
}
</script>
<button onclick="reload()">Reload</button>
What you wrote is
window.setTimeout("location = ''"; ,1000);
You were saying execute this function after 1 second. You need to define the setTimeout inside the function. Also there is a built in method to reload the page. Call that instead of setting the location to a blank string.
function reload() {
setTimeout( function() {
window.location.reload(true);
},1000);
}
Now to cancel the timeout, you need to use clearTimeout(timeoutId); You get the timeoutId from the integer that the setTimeout returns when you call it.
var timer = null;
function reload() {
timer = window.setTimeout( function() {
window.location.reload(true);
},1000);
}
function cancelReload() {
if (timer) {
window.clearTimeout(timer);
}
timer = null;
}
AND you said you want it to keep running. That will require cookies or localstorage.
var timer = null;
function reload() {
localStorage.reload = true; //set localstorage so we know to fire it off again
timer = window.setTimeout( function() {
window.location.reload(true);
},1000);
}
function cancelReload() {
if (timer) {
window.clearTimeout(timer);
}
timer = null;
localStorage.removeItem("reload"); //remove the key in localstorage
}
if (localstorage.reload) { //check localstorage to see if key is set
reload();
}
You need to wrap the whole thing in another function and call that from the button click
<script>
var openDialog = function(uri, name, options, closeCallback) {
var win = window.open(uri, name, options);
var interval = window.setInterval(function() {
try {
if (win == null || win.closed) {
window.clearInterval(interval);
closeCallback(win);
}
}
catch (e) {
}
}, 1000);
return win;
};
var test = function() {
alert(bye);
};
openDialog("//google.com", "popup", "scrollbars=no", test);
</script>
This is code to show an alert after closing popup. It works fine in Chrome and Firefox, but has a problem in IE. In IE, the popup opens, and before closing it, the alert comes up. How can I fix it? I want to show the alert after closing the popup. Thank you.
You shouldn't probe objects to see if they exist every x seconds. Attach events with a callback function, then you only fire an event once, when you actually need to and not a million times before.
Try:
var openDialog = function(uri, name, options, closeCallback) {
var win = window.open(uri, name, options);
win.addEventListener("onunload", test);
};
var test = function() {
alert(bye);
};
this should fire your alert when the window closes, enjoy
The following piece of code autosaves a page but it also times it out by loging out and taking the user to a time out page. How can i chnage it so that it only does the auto save part but not the time out?
<script language='javascript'>
function Save() {
var hdnSessionTimeOut = document.getElementById('fast22_MainCtn_fast44');
hdnSessionTimeOut.value = 'SessionTimeOut';
__doPostBack('Fast22$MainCtn$btnSave', '');
}
function Redirect() {
window.location = "SessionTimeout.aspx"
}
window.onload = function () {
if ('True' == 'True') setTimeout(Save, 30000);
else setTimeout(Redirect, 30000);
}
</script>
I tried reducing it to the following but and I think it worked but it changed the doc to view mode instead of edit mode. and you have to click edit again. Also when it in edit mode, the counter still works and it gives and error. Is there a way to have it auto save and then go back again to edit mode?
<script language='javascript'>
function Save() {
__doPostBack('ctl00$MainContentPlaceHolder$btnSave', '');
}
window.onload = function () {
if ('True' == 'True') setTimeout(Save, 10000);
else setTimeout(Save, 25000);
}
</script>
Just because you don't see use for a feature doesn't mean it isn't useful.
The Stack Exchange network, GMail, Grooveshark, Yahoo! Mail, and Hotmail use the onbeforeunload prompt to prevent/warn users that they are leaving a page after they have begun editing something. Oh yah, nearly every single desktop program that accepts saveable user-input data utilizes this prompt-user-before-leaving UX pattern.
I have a function which behaves similarly to this one:
window.onbeforeunload = function(){
// only prompt if the flag has been set...
if(promptBeforeLeaving === true){
return "Are you sure you want to leave this page?";
}
}
When a user attempts navigates away from the page the browser presents them with the option to leave or stay on the page. If the user selects the "Leave this page option" and then they quickly click on a link again before the page unloads completely the dialog fires again.
Are there any foolproof solutions to this problem?
Note: The following NOT the solution:
var alreadyPrompted = false;
window.onbeforeunload = function(){
// only prompt if the flag has been set...
if(promptBeforeLeaving === true && alreadyPrompted === false){
alreadyPrompted = true;
return "Are you sure you want to leave this page?";
}
}
because the user might select the "Stay on the page" option which would cause future onbeforeunloads to stop working.
I think you could accomplish this with a timer (setInterval) that starts in the onbeforeunload callback. Javascript execution will be paused while the confirm dialog is up, then if the user cancels out the timed function could reset the alreadyPrompted variable back to false, and clear the interval.
Just an idea.
Ok I did a quick test based on your comment.
<span id="counter">0</span>
window.onbeforeunload = function () {
setInterval(function () { $('#counter').html(++counter); }, 1);
return "are you sure?";
}
window.onunload = function () { alert($('#counter').html()) };
In between the two callbacks #counter never got higher than 2 (ms). It seems like using these two callbacks in conjunction gives you what you need.
EDIT - answer to comment:
Close. This is what i was thinking
var promptBeforeLeaving = true,
alreadPrompted = false,
timeoutID = 0,
reset = function () {
alreadPrompted = false;
timeoutID = 0;
};
window.onbeforeunload = function () {
if (promptBeforeLeaving && !alreadPrompted) {
alreadPrompted = true;
timeoutID = setTimeout(reset, 100);
return "Changes have been made to this page.";
}
};
window.onunload = function () {
clearTimeout(timeoutID);
};
I have encapsulated the answers from above in an easy to use function:
function registerUnload(msg, onunloadFunc) {
var alreadPrompted = false,
timeoutID = 0,
reset = function() {
alreadPrompted = false;
timeoutID = 0;
};
if (msg || onunloadFunc) { // register
window.onbeforeunload = function() {
if (msg && !alreadPrompted) {
alreadPrompted = true;
timeoutID = setTimeout(reset, 100);
return msg;
}
};
window.onunload = function() {
clearTimeout(timeoutID);
if (onunloadFunc) onunloadFunc();
};
} else { // unregister
window.onbeforeunload = null;
window.onunload = null;
}
}
To register use:
registerUnload("Leaving page", function() { /* unload work */ });
To unregister use:
registerUnload();
Hope this helps ..