Peter Hauer
Peter Hauer

Reputation: 90

How to exclude script on certain routes in Nuxt?

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,
    },
  ],
]

Upvotes: 1

Views: 1183

Answers (2)

Peter Hauer
Peter Hauer

Reputation: 90

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);
  }
};

Upvotes: 0

kissu
kissu

Reputation: 46604

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.

Upvotes: 1

Related Questions