How to Include Javascript inside document.write properly or is there a workaround?

31 Views Asked by At

I am forced to put code in a place where- when inserted, it applies to thousands of web pages at the same time.

I would like to only have a script work when a URL contains: "/pN2toKYZ/checkout" :

So i used window.location.href.indexOf and that seems to work well, but im having trouble after that.

Here is what I am trying, I have also tried escaping the starting'<' but it did not work:

<script>
if (window.location.href.indexOf('/pN2toKYZ/checkout') != -1) {
   document.write("<script>
  gtag('event', 'conversion', {'send_to': 'AW-834461893/ixLXCK-Wm6kDEMXB840D'});
 </script>
")
}
</script>

Note: the script i'm trying to place is a Google Adwords conversion tag. Google Adwords general script is rightfully in place before this code.

1

There are 1 best solutions below

0
Sly_cardinal On

You're already running inside a script element - instead of trying to write a new script to the page, put the code you want to run directly:

<script>
if (window.location.href.indexOf('/pN2toKYZ/checkout') != -1) {
  gtag('event', 'conversion', {'send_to': 'AW-834461893/ixLXCK-Wm6kDEMXB840D'});
}
</script>