#Persisting dispatchEvent() logic across the entire astro app

8 messages · Page 1 of 1 (latest)

brisk swift
#

Hello, I'm trying to put together a site without any JS frameworks outside Astro and I'm trying to propagate a new event on the window object for other frontend scripts to listen to when localStorage gets updated. The code is pretty simple:

const nativeSetItem = localStorage.setItem;

localStorage.setItem = function(key, value) {
  const event = new Event('localStorageUpdated');
        event.key = key; 
        event.value = value; 
  
  window.dispatchEvent(event);
  nativeSetItem.apply(this, arguments);
};

I tried to add this inside a <script is:inline /> block, but I believe it is still only appended to the bottom of the rendered HTML. Is it then correct to assume that the bundled scripts are being run beforehand and therefore do not have access to this custom event I'm trying to propagate? Are there any alternative strategies for achieving this outside of ultimately having to encapsulate everything inside 1 astro component/using a UI framework?

Thanks in advance!

iron topaz
brisk swift
#

I see, thanks for that clarification. Unfortunately, the problem still persists where in another .astro file in this project where I have a frontend script tag, the above logic that I would expect to work still doesn't. The callback below never gets triggered inside any logic block outside that script:

addEventListener('localStorageUpdated', e => {
// do stuff
});
iron topaz
#

I see, can you make a reproduction of the issue?

#

My guess is that the setItem function is somehow never run

brisk swift
iron topaz
#

Went through your reproduction, I found that it's because the script in layout is called because the script in card
Which means that the event is fired before the event listener is attached.