I am forced to put code in place where which when inserted, it applies to thousands of web pages.
I would like to only have a script work when a URL contains: "/pN2toKYZ/checkout" :
Here is what I am trying, i've also tried escaping bthe 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>
The version shown in your question has line breaks, which are not allowed in strings. You might have put them in for presentation here but make sure they are not in your actual code.
If you must use
document.writethere's no need to escape anything in your quotted string argument ofdocument.write(if it contained the same quote marks as you use to quote it, they would need to be escaped but tags etc. are fine).Although I can't see why the command specified in the 'created' script inside your your conditional cannot simply be placed directly in your conditional (without needing to write a new script to the page), if I had to add a script created by a script, I would create a new script element, add innerText to it specifying the required commands, and then append the the script element to the document.
If your added script needs to be placed at a specific part of the page (rather than appended as the last child of the body as in my example) you can learn more here: How to append a childnode to a specific position
The following example has a single script which creates a new script with a single command to change the page background color. CSS has been used to show the actual scripts in the rendered html (for presentation only, irrelevant to function). You will see that the created script is added to the page and executed.