How to execute JS code only ones?

I have a JS snippet with the code on the page, and I want this code to run only ones (only when the user opens this page for the first time). What is the best way to implement it in Mendix? I could create a variable in the code and add a condition to run this code only if the variable is true and then set it to false, but the varible will be reset when the page will be reloaded.
2 answers

One way to handle this, is storing and checking a variable in localstorage like shown below. Note however that this solution is browser specific. Thus opening another browser will rerun your script.

if (!localStorage.getItem('runonlyonce')) {
   // Do something
   localStorage.setItem('runonlyonce', "visited");   

If the user has an account, then you can use a persistent entity with a boolean attribute. Upon visiting the page you can load the entity in a dataview and read the boolean value from the context object in a JS snippet.


Even without an account you could create a Non-persistable entity, connect it to the Session-entity and use that to store a variable. That way, you can use it for every first time it's showed within that session.

If you want to make sure it's triggered only once regardless of sessions, use a variable in the account-object or an associated persistable object. as mentioned by Nils.