0

I have a for loop that is iterating through some data. Every 10th iteration I need to display an ad from Google Adsense.

However, when I insert the Adsense code the rest of my code breaks -- I get an "Unexpected EOF."

Here is what I have, based off of this example from Google:

for (var i = 0; i < json.length; i++) {

     if ((i % 10) == 0)$("#contentRow").append(`

      <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js">
      </script>
        <ins class="adsbygoogle" style="display:block"
        data-ad-format="fluid"
        data-ad-client="ca-pub-1234567891234567"
        data-ad-slot="1234567890"></ins>
      <script>
        (adsbygoogle = window.adsbygoogle || []).push({});
      </script>

 `);

 $("#contentRow").append(`-- iterating my data here... --`)

This all works fine until I add the Adsense code. Replacing the Adsense code with hello world, for example, works just fine. But once the Adsense code is included everything breaks, think because of the script tags. Any help?

SAA
  • 37
  • 1
  • 7
  • Do you need to inject the script and global vars? Seems like you could have those on the page already and just append the ins tag+contents. Also, it's typically good practice to use strict equals `===` and using brackets for `if` blocks. – Christopher Marshall Aug 28 '19 at 16:56
  • Yes, I have to include the scripts, AFAIK, because 1) you're not allowed to change the code at all due to TOS, and 2) the ad is inserted directly after the script, so it has to be placed wherever the ad is supposed to appear. Thanks for the tip re: brackets and ===. – SAA Aug 28 '19 at 17:10

1 Answers1

0

Per https://stackoverflow.com/a/22090482/697079 you need to escape your script tag(s).

<\/script>

I'm receiving 404's assuming because of the account settings. https://jsfiddle.net/zem4xqsw/

Christopher Marshall
  • 10,678
  • 10
  • 55
  • 94
  • 1
    Perfect -- this fixed my problem! I wonder why that isn't included in the Google example linked in my question? (And yes -- the account numbers in the post are dummy numbers provided by Google; not real account settings). Tried to upvote but not enough reputation. Thanks again! – SAA Aug 28 '19 at 17:38