Firefox is firing onchange events in my webapp after tab restore.
When reloading the same URL in Firefox there is no problem, no onchange events get fired on page load, all changed values since last visit are displayed correctly.
But when reopening the same page with the same URL, after closing Firefox and reopening the page with "restored tabs" (from the Firefox option "show my windows and tabs from last time") then it is firing onchange events for all values that have been changed since last visit.
Actual workflow ot reproduce the problem:
- My update events are in background (JavaScript/AJAX) and are fired with onchange events;
- Firefox setting "show my windows and tabs from last time" enabled;
- Change some values in my page (select fields);
- Close Firefox;
- Open the same URL on another browser or computer, and change some values;
- Reopen Firefox, select the tab with the page on it, it reloads and fires onchange events again for all changed values since last visit.
Tried to reproduce this behaviour with completely different pages (not created by me and using other script libraries and stuff) and the result is the same, it is always firing the onchange events.
Chrome is not doing this with the "restore tabs" option.
Why is it firing onchange events? How can I prevent it?
A few suggestions on how to deal with this depending on the wanted result. Note that this is tested on my machine, behaviors may vary. They way it seems to work is that Firefox tries to restore data that was entered by user. So it modifies the page, triggering the
change
event
. This event is slighlty different than the one triggered by the user. It is aUIEvent
while the user triggered one is a straightEvent
. And this Event iscancelable
and triggered before thewindow load
event. So this gives a couple of ways to deal with this. I'll take a select element for example.If you want the select to keep value entered before window closing, but not trigger the onchange event, you can set the onchange call on the
window.onload
. Like this:Since the setting of the
select
occurs beforeonload
, this specific change won't trigger youronchange
function.Other way would be to target behaviors you don't to trigger by putting a condition validating if the element is cancelable or not. If it's
cancelable
, it means it's called from a restore session and won't trigger what's inside. Like this:Other way, to clear out all data would be to set a
document.onchange
event and reload the page if the event iscancelable
. Like this:Of course you need to make sure you don't have any other cancelable change event called in your page.
EDIT:
To clarify order of events fired, see this jsfiddle, not in iframes, iframes seems to behave differently, so if you have iframes, it may be a bit more complicated. But without iframe, you'll see how the different events are triggered depending on your interactions:
http://fiddle.jshell.net/nozp9uhk/6/show/