#how to run script on every page

6 messages · Page 1 of 1 (latest)

muted pier
#

if I go from / to /something how to run a script on each page

#

I have added the script to the layout.astro

#

but it work well when not using <ViewTransitions />

grave quail
#

Hi Rohan! To run a script on multiple pages, you can create the script in a separate file, then import it into the Component Scripts of those pages.

---
import { myScript } from "./scripts";
const data = myScript();
---

If the script needs to run on every page, you can use Astro's Middleware API.

Create middleware.ts that exports a function onRequest:

import { myScript } from "./scripts";

export function onRequest (context, next) {
  const data = myScript();

  // Use context.locals to make the data available on every page
  context.locals.data = data;

  // return a Response, or the result of calling `next()`
  return next();
};

Then access the data in any page.

---
const { data } = Astro.locals;
---
trim tangle
#

If you're using ViewTransitions you can just add two lines to run the script on every page:
Add this to your layout and it will run everytime the pahe changes:

<script>
  document.addEventListener('astro:page-load', () => {
    console.log('layout script')
  })
</script>