When navigating out of the page where the event listener is, I get the following error in the browser's console:
Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
at HTMLDocument.<anonymous> (about.astro:19:11)
at triggerEvent (router.js?v=eff4607c:17:41)
at onPageLoad (router.js?v=eff4607c:18:26)
at router.js?v=eff4607c:334:5
It seems that the script is added to every page so that it gets re-executed on every navigation, but if the event listener is attached to an element that exists on just one page the element won't be found on the next page and an error will be thrown.
The example shown in the docs is for a Nav component that's present on every page, but that's not always the case.
This error message can be avoided with optional chaining (document.querySelector('#some-button')?.addEventListener... etc) however, I think this is something you might want to warn about in the docs, or refactor router.js to address this issue.
Astro Info
If this issue only occurs in one browser, which browser is a problem?
No response
Describe the Bug
I'm using View Transitions, wrapping event listeners inside an 'astro:page-load' event for script re-execution like so:
When navigating out of the page where the event listener is, I get the following error in the browser's console:
It seems that the script is added to every page so that it gets re-executed on every navigation, but if the event listener is attached to an element that exists on just one page the element won't be found on the next page and an error will be thrown.
The example shown in the docs is for a Nav component that's present on every page, but that's not always the case.
This error message can be avoided with optional chaining (
document.querySelector('#some-button')?.addEventListener... etc
) however, I think this is something you might want to warn about in the docs, or refactorrouter.js
to address this issue.What's the expected result?
No error messages in the browser's console.
Link to Minimal Reproducible Example
https://stackblitz.com/edit/github-4hf8r3?file=src%2Fpages%2Fabout.astro
Participation