From 10dd683b3248f3bbb2257de73254b66dd6491e76 Mon Sep 17 00:00:00 2001 From: Nik K <4200435+Dorson@users.noreply.github.com> Date: Wed, 22 Apr 2020 08:16:59 +0200 Subject: [PATCH] harden memory recall logic to be fail-safe Hardened the CSS class memory recall function against critical inpupt errors in exceptional cases. One could never know if this code will run in the apps or hardware for critical life support. Or maybe inside of machines that need to work 100% all the time to support safety of humans. Now the functon exits the loop, if any errors of the input variables are found. Limits possible attack vectors, where safety is an issue. If you want to test the function for critical errors or with false data input, use those console log variables for testing. Fake the input data and see what happens in the console logs. console.log( "load state was: " + document.readyState ) ; console.log( "Tag : " + Tag ) ; console.log( "TagNotAlive : " + TagNotAlive ) ; console.log( "MemoryName : " + MemoryName ) ; console.log( "MemoryValue : " + MemoryValue ) ; --- index.html | 32 ++++++++++++++++++++++++-------- 1 file changed, 24 insertions(+), 8 deletions(-) diff --git a/index.html b/index.html index 6305dda..ea17674 100644 --- a/index.html +++ b/index.html @@ -257,26 +257,42 @@ window.onerror = null ; -/* During load time, we remember the saved CSS classes from local memory */ +/* + During load time, we remember the saved CSS classes from localStorage + Only works with HTML Tags that are already loaded before the script run ! + Optimally the HTML tag. Works for the first Tag of it's type only ! +*/ + +document.addEventListener( 'DOMContentLoaded' , function() { + + RememberClasses() ; +}); -document.addEventListener("DOMContentLoaded", RememberClasses() , true ) ; function RememberClasses() { - var ClassMemory = [ + const ClassMemory = [ ["html" , "ColorMode"] , ["html" , "TextSize"] ] ; - for ( let [ Tag, MemoryName ] of ClassMemory ) { - /* On Errors we skip one loop. */ - if (!localStorage.getItem( MemoryName ) || !document.querySelector( Tag ) ) { + + for ( let [ Tag , MemoryName ] of ClassMemory ) { + + let TagNotAlive = !(document.querySelector( Tag )) ; + + let MemoryValue = window.localStorage.getItem( MemoryName ) ; + + /* On logic Errors we skip one loop. */ + + if ( !MemoryValue || TagNotAlive ) { continue ; } - else { + /* Else we remember and set CSS classes. */ - var MemoryValue = localStorage.getItem( MemoryName ); + else { + document.querySelector( Tag ).classList.add( MemoryValue ); } }