-1

I would like to add a js script with an @click on a button.

I already tried to do it with InnerHTML and a Node but that's not working.

Do someone have any idea on how to do it ?

Here is my not working code :

addGtmScript: function(company){
            gtmScript = document.innerHTML += `
            <script>
            window.dataLayer = window.dataLayer || [];
                window.dataLayer.push({
                    'event': 'register-form-ok',
                    'company': ${ company },
                });
                </script>`
                document.querySelector('body').innerHTML += gtmScript
        },
Antoine Kurka
  • 322
  • 3
  • 9
  • 1
    Does this answer your question? [How to add external JS scripts to VueJS Components?](https://stackoverflow.com/questions/45047126/how-to-add-external-js-scripts-to-vuejs-components) – Bruno Francisco Aug 09 '21 at 14:50
  • No i'm not trying to add an external script. I have my own script – Antoine Kurka Aug 09 '21 at 14:50
  • 1
    It will be easier for someone with the relevant knowledge to answer your question if you share code examples of what you tried and why they aren't working. – futur Aug 09 '21 at 14:50
  • 1
    "No i'm not trying to add an external script. I have my own script ". Why a simple `import MyScript from 'path/to/script'` wont work? – Bruno Francisco Aug 09 '21 at 14:51
  • Why not use [Vue2 Google Tag Manager](https://www.npmjs.com/package/@gtm-support/vue2-gtm) package? It will do exactly what you are trying to achieve – Bruno Francisco Aug 09 '21 at 14:54
  • Because that's not the only task I want to execute with a script. GTM is one among so many others – Antoine Kurka Aug 09 '21 at 14:58

1 Answers1

1

Try this:

addGtmScript: function(company){
  var head = document.querySelector("head");
  var script = document.createElement("script");

  var gtmScript = `window.dataLayer = window.dataLayer || [];
            window.dataLayer.push({
                'event': 'register-form-ok',
                'company': ${ company },
            });`;

  var text = document.createTextNode(gtmScript);

  script.appendChild(text);

  head.appendChild(script);
        },

This should add the script to the <head> tag

Zaeem Khaliq
  • 296
  • 5
  • 14