Reload Page on Focus - javascript

I have a Progressive Web App that I need to refresh every time the user opens it.
To achieve this I have tried:
1) First Option
window.onblur = function() {
window.onfocus= function () {
window.location = self.location;
}
};
2) Second Option
var blurred = false;
window.onblur = function() {
blurred = true;
};
window.onfocus = function() {
blurred && (window.location = self.location);
};
Credit of Option 1: https://stackoverflow.com/a/16406350/11843328
Credit of Option 2: https://stackoverflow.com/a/11313719/11843328
This work well but the problem is that sometimes whenever you click something, it reloads again. It basically reloads like 4 times in a row with some action. Other times it works as expected, just reloading once, but most of the times is like 4 or 5 times in a row.
I need it to reload just once when opened (on focus). Is there any alternatives I could try or any advice would be appreciated!

Make sure you're using window focus event. As others have pointed out, there is no need to use the blur event, as focus will only fire if the window focus was blurred.
You can use the window.location.reload method to reload the window as well.
window.addEventListener("focus", e => window.location.reload());
<p>Look for a flicker</p>

You don't need the onblur event. Using just the onfocus event will do the work.

Related

How can I check if app is being minimized from minimize icon or by clicking taskbar app icon?

I have added functionality where the app hides in the background on window.minimize. But I want to hide it only when the minimize button is clicked and minimize when clicked from the taskbar.
win.on("minimize", function(event, args) {
event.preventDefault();
win.hide();
console.log("hide min");
win.resizable = true;
win.resizable = false;
});
minimize seems to fire in both cases, and there doesn't appear to be a standard way of catching one, but not the other.
However, when you click on the taskbar icon, the blur event fires slightly before the minimize event, but if you click on the minimize button, the minimize event fires first.
This isn't the most robust solution, because of the timeout guess I had to make, but it seems to work fine:
mainWindow.on("minimize", () => {
console.log(`minimized via ${blur ? "taskbar" : "titlebar"}`);
});
let blur = false;
mainWindow.on("blur", () => {
blur = true;
setTimeout(() => {
blur = false;
}, 100);
})
However, what behavior do you want went hitting the hotkey Windows+DownArrow? Currently, it will count that as the titlebar case and will hide the window.
If you care about that case, you might have to hook into before-input-event and detect those key presses.
There's potentially another solution to hook into Windows messages, but that's uglier and only works on Windows.

Page is not jumping if window.onhashchange is used

I am using hashchange event to ask a confirmation dialog box saying that the data in the current page will be lost, if moved.
I've implemented like this:
window.onhashchange = function() {
if(window.confirm("Do you really want to close?")){
}
};
This event is triggered correctly. But the page is not changing if the user clicks yes. What do I need in the {...}?
Please try
window.onhashchange = function() {
if (window.confirm("Do you really want to navigate?")) {
location.hash = location.hash; // or set the hash elsewhere and change here
}
};

Set variable on back button click

I have a function I dont want to run if the broswer back button was clicked. I am attempting to use something like the below:
var backButtonClicked = false;
window.onpopstate = function() {
alert("Back clicked");
backButtonClicked = true;
};
then later I am trying to use the variable like:
if(!backButtonClicked) {
//run function if not back button clicked
}
However with the code above the alert is not getting fired when I hit the back button.
window.onpopstate = function() {
alert("back clicked");
backButtonClicked = true;
};
history.pushState({}, '');
With the code above the alert gets fired when I click the back button, however the browser doesnt navigate back to the previous page unless I click the back button for the second time. Is there something I am doing incorrect here or is there a better approach to achieve what I am trying to do?
My coding skills are not very good when I have very little time to type. But maybe an eventlistener would be another approach to the problem you can maybe consider?
For examples and reference from an excellent source:
http://www.w3schools.com/js/js_htmldom_eventlistener.asp
Hope this helps, and good luck!

Exit confirmation in Javascript with Telerik controls

I'm using Telerik controls for my project. On my page, there are some links to another page, several radtextboxes and a radbutton (it causes a postback). When the textbox values are changed, the button becomes enabled. Then, in my window.onbeforeunload, I check if the button is enabled or disabled. If it is enabled, then the confirm dialog appears. The code looks like this :
window.onbeforeunload = function (evt) {
var ClientGeneral_btnSave = $find('<%=btnSave.ClientID %>');
if (ClientGeneral_btnSave.get_enabled() == true) {
var message = 'You will lose unsaved data?';
if (typeof evt == 'undefined') {
evt = window.event;
}
if (evt) {
evt.returnValue = message;
}
return message;
}
This code works well. When I close the tab, the confirm dialog appears. When I click on the links, it does. But, when I click on the btnSave itself, the dialog appears too, which is unsual. I want the btnSave NOT to cause onbeforeunload event
Please tell me how to do this.
Thank you in advance
It will fire onbeforeunload this if the btnSave posts back which it looks as if it is. Therefore you have a couple of choices
Prevent the btnSave from posting back if you don't need it to. Easiest way to do it is put this attribute in the asp:Button markup
OnClientClick="return false"
Wire up a javaScript/jQuery method to disable the onbeforeunload event. I did this before by stashing an value in a hidden field and using this to signal that the onbeforeunload event should fire.
for instance
$('#<%= btnSave.ClientID %>').bind('click', function(e){
$('#myHiddenFieldId').val('1');
});
and change your on beforeunload handler to check that the hidden field is not equal to 1 (make 0 the default i.e.
window.onbeforeunload = function (evt) {
if( $('#myHiddenFieldId').val() != '1')
{
//your logic here
}
}
You could probably do something better by unbinding the onbeforeunload handler in the btnSave click event using JQuery rather than using a hidden field to override.
Option 2 can get fiddly though - so best of luck

window.beforeunload called twice in Firefox - how to get around this?

I'm creating a popup window that has a beforeunload handler installed. When the "Close" file menu item is used to close the popup, the beforeunload handler is called twice, resulting in two "Are you sure you want to close this window?" messages appearing.
This is a bug with Firefox, and I've reported it here, but I still would like a way to prevent this from happening. Can you think of a sane way of detecting double beforeunload to prevent the double message problem? The problem is that Firefox doesn't tell me which button in the dialog the user elected to click - OK or cancel.
<script type="text/javascript">
var onBeforeUnloadFired = false;
window.onbeforeunload = function ()
{
if (!onBeforeUnloadFired) {
onBeforeUnloadFired = true;
event.returnValue = "You have attempted to leave this page. If you have made any changes to the fields without clicking the Save button, your changes will be lost. Are you sure you want to exit this page?";
}
window.setTimeout("ResetOnBeforeUnloadFired()", 10);
}
function ResetOnBeforeUnloadFired() {
onBeforeUnloadFired = false;
}
</script>
Set a variable in the handler to prevent the dialog coming up the second time. Use setTimeout to reset it afterwards.
This is definitely a FF bug. I've reported it at https://bugzilla.mozilla.org/show_bug.cgi?id=531199
The best solution I've found is to use a flag global variable that is reset after so many milliseconds, say 500 (this ensures that the function can be called again, but not immediately after its appearance).
See last code in:
http://social.msdn.microsoft.com/Forums/en/sharepointinfopath/thread/13000cd8-5c50-4260-a0d2-bc404764966d
I've found this problem in Chrome 21, Firefox 14, IE 7-9, Safari 5 (on PC).
The following works on all of these browsers. If one removes the window.onbeforeunload function during the event this will prevent the second call. The trick is to reset the window.onbeforeunload function if the user decides to stay on the page.
var window_on_before_unload = function(e) {
var msg;
// Do here what you ever you need to do
msg = "Message for user";
// Prevent next "window.onbeforeunload" from re-running this code.
// Ensure that if the user decides to stay on the page that
// this code is run the next time the user tries to leave the page.
window.onbeforeunload = set_on_before_unload;
// Prepare message for user
if (msg) {
if (/irefox\/([4-9]|1\d+)/.test(navigator.userAgent))
alert(msg
+ '\n\nThe next dialog will allow you to stay here or continue\nSee Firefox bug #588292');
(e = e || window.event).returnValue = msg;
return msg;
}
};
// Set window.onbeforeunload to the above handler.
// #uses window_on_before_unload
// #param {Event} e
var set_on_before_unload = function(e) {
// Initialize the handler for window.onbeforeunload.
window.onbeforeunload = window_on_before_unload;
}
// Initialize the handler for window.onbeforeunload.
set_on_before_unload();
Create a global variable that is set to true inside the handler. Only show the alert/popup when this variable is false.
I use the following snippet to track the exitcount
When the page loads the following variable exitCount is initialized
if (typeof(MTG) == 'undefined') MTG = {};
MTG.exitCount=0;
and in the Window unload event
$(window).bind("beforeunload", function(){
if (MTG.exitCount<=0)
{
//do your thing, save etc
}
MTG.exitCount++;
});
I've found that instead of doing your own call to confirm(), just do even.preventDefault(); within the beforeunload event. Firefox throws up its own confirm dialog.
I'm not sure if this is the correct/standard thing to do, but that's how they're doing it.
I have a document opening another popup window with window.open. In the original window I have registered (with jquery) a listener for "unload" event like this:
var popup_window = window.open(...)
$(popup_window).on('unload', function(event) ...
I have came across this page because the event was effectively triggering twice. What I have found is that it is not a bug, it triggers twice because it fires once for "about:blank" page being replaced by your page and another for your page being unloaded.
All I have to do is to filter the event that I am interested in by querying the original event:
function (event) {
var original_url = e.originalEvent.originalTarget.URL;
if (original_url != 'about:blank')
{
... do cool things ...
}
}
I don't know if this applies to the original question, because it is a special case of a window opening another, but I hope it helps.

Categories