How to use document and window element in astro JS?

Viewed 938

I want to use window or document to return path of the current page default Astro.site.pathname isn't working right or proper documentation isn't available.

My question is how to use document or window properly in Astro JS?

Thanks in advance!

3 Answers

You need to write the script inside <script is:inline></script> if you want to use things like window or document. This way Astro won't touch your JS and include it directly on the HTML. The JS positioned on the top of the page between --- --- will be executed at build time.

By default, Astro will process, optimize, and bundle any and tags that it sees on the page. You can opt-out of this behavior with the is:inline directive.

– Docs

You can use the is:inline directive like so in your .astro components:

---
// static build only
---

<script is:inline>
    console.log(document, window)
</script>

You can also access the current path name from an Astro component using const { pathname } = Astro.url.

Related