javascripteventslocal-storageweb-storage

How to store/stash JavaScript event and reuse it later?


From https://developers.google.com/web/fundamentals/app-install-banners/#trigger-m68

let deferredPrompt;

window.addEventListener('beforeinstallprompt', (e) => {
  e.preventDefault();
  // Stash the event so it can be triggered later.
  deferredPrompt = e;
});

This code is fine, but I want to trigger the stashed event later, in a different place. To perform that, I need to store an event not just in a variable, but somewhere else.

The question: how can an event be stored with its methods?

I tried Local Storage with serialization/deserialization of an object:

> localStorage.setItem('stashed-event', JSON.stringify(e))
>
> JSON.parse(localStorage.getItem('stashed-event'))

But this approach doesn't work as expected, because it's storing only key-values and losing all event methods.


Solution

  • After reading your question a few times, and the answers another few,

    The question: how can any javascript Object be stored with its methods?

    The answer: there is no how.

    However,

    Josh properly explained you can extract and store all the serializable properties, say data, from your event.

    I will just add you can create an event with somehow that same data later anywhere, this new event will have all the methods any Event has, but by now probably none of use.

    Obviously, even serialized in your data, properties like timeStamp, isTrusted, etc... will be overriden at creating the new event.

    What you just miss / need is an EventTarget, the value of the event.target property, the reference which is lost forever when document.body unloads forever, or when serializing the event Object.

    But if it is still alive, or if you know what event.target should be, like a DOM Element or any Object you can reference, from wherever you recreate the event (where?), just dispatch your event to that object, if it listens to that event.type, your brand new event should be at least heard.

    Simple example from MDN EventTarget, or see EventTarget.dispatchEvent

    As a comment over the extensive answer by cegfault: eval, and text source code... could be <script> text source code </script>... should your script produces a (String) script. If not you ´d probably better go further backwards to where did your script creates the unserializable things that appear in your event, and think about recreating those things, not the event.