How to exclude script on certain routes in Nuxt?

Viewed 226

I have a nuxt2-webapp with a lot of routes and for all routes except 2, I need a script to be injected. Is there a way to disable the injecting?

Nuxt config:

meta: [
  script: [
    {
      id: 'Cookiebot',
      src: 'https://consent.cookiebot.com/uc.js',
      'data-cbid': 'xxxxx',
      type: 'text/javascript',
      async: true,
    },
  ],
]
2 Answers

No, there is no way to do so.
If you inject a script, it will be on the window object. Hence available everywhere in your DOM.

What's the issue with that? You could hide your thing with some CSS if it's annoying visually.

The best way to achieve this behaviour is via a plugin:

export default (context: Context) => {
  if (!context.route.name?.includes('embed')) {
    const scriptTag = document.createElement('script');
    scriptTag.id = 'Cookiebot';
    scriptTag.src = 'https://consent.cookiebot.com/uc.js';
    scriptTag.setAttribute('data-cbid', 'xxxx');
    scriptTag.type = 'text/javascript';
    scriptTag.async = true;
    document.head.appendChild(scriptTag);
  }
};
Related