Appendix JS_N_A6
Summary
Requirement: Changes of context are only initiated by user request or with user control.
Details: Do not automatically refresh the page without user confirmation or control.
Examples
Correct code
Refer to the JS_N_A6 live demo for a working example.
<form id="demo" action="#"> <fieldset> <legend><strong>Refresh the page ...</strong></legend> <p> <input id="refresh0" name="refresh" value="0" type="radio" checked="checked" /> <label for="refresh0">Never</label> </p> <p> <input id="refresh30" name="refresh" value="30" type="radio" /> <label for="refresh30">Every 30 seconds</label> </p> <p> <input id="refresh60" name="refresh" value="60" type="radio" /> <label for="refresh60">Every minute</label> </p> <p> <input id="refresh300" name="refresh" value="300" type="radio" /> <label for="refresh300">Every 5 minutes</label> </p> <p> <input id="refresh900" name="refresh" value="900" type="radio" /> <label for="refresh900">Every 15 minutes</label> </p> </fieldset> <fieldset> <button type="submit">Save and Refresh</button> </fieldset> </form>
var form = document.getElementById('demo'); var radios = form.refresh; var cookiename = 'page_refresh_time'; if(document.cookie.indexOf(cookiename) != -1) { var refreshtime = document.cookie .split(cookiename + '=')[1] .split(';')[0] .split('=')[0]; for(var i = 0; i < radios.length; i ++) { if(radios[i].value == refreshtime) { radios[i].checked = true; break; } } var milliseconds = parseInt(refreshtime, 10) * 1000; if(milliseconds > 0) { window.setTimeout(function() { document.location.reload(); }, milliseconds); } } form.addEventListener('submit', function(e) { for(var i = 0; i < radios.length; i ++) { if(radios[i].checked) { var now = new Date(); now.setTime( now.getTime() + (365 * 24 * 60 * 60 * 1000)); document.cookie = cookiename + '=' + radios[i].value + '; expires=' + now.toGMTString() + '; path=/'; document.location.reload(); } } e.preventDefault(); }, false);