I have a script that shows 10 most clicked keywords, their average CPC and conversions. While previewing the script it works fine. But when I send it to my email, only last row of the 10 rows shows. What is wrong here?

function main() {   var keywords = AdsApp.keywords()       .orderBy("Clicks DESC")   //  .orderBy("Impressions DESC")       .forDateRange("THIS_MONTH")       .withLimit(10)       .get(); Logger.log("10 most clicked keywords");   while (keywords.hasNext()) {     var keyword = keywords.next();     content = keyword.getText() + " | Clicks: " + keyword.getStatsFor("THIS_MONTH").getClicks() + " | CPC: " + keyword.getStatsFor("THIS_MONTH").getAverageCpc().toFixed(2) +      " | Conversions: " + keyword.getStatsFor("THIS_MONTH").getConversions();   }    MailApp.sendEmail({             to: 'myemail@myemail.com',             subject: "10 most clicked keywords",             htmlBody: content });      }

Tag:google-ads-api, javascript, google-ads-script, google-apps-script, scripting

6 comments.

  1. medic_dev

    Looks to me like you're over-writing the content variable with every while loop. I think you need to declare content outside the while loop and then add it to your content = string e.g.

    var content = ""; while (keywords.hasNext()) { var keyword = keywords.next(); content = content + keyword.getText() + " | Clicks: " + keyword.getStatsFor("THIS_MONTH").getClicks() + " | CPC: " + keyword.getStatsFor("THIS_MONTH").getAverageCpc().toFixed(2) + " | Conversions: " + keyword.getStatsFor("THIS_MONTH").getConversions(); }

    I suspect you'll probably want to add a new line character + "\n" at the end of the concatenations as well.

    1. Tane

      Hey, this almost worked! But for some reason it shows 9 results, leaving the most clicked keyword out, do you have any idea why?

    2. Tane

      So basically the 1st result seems to be overwritten by the others, for some reason.

    3. medic_dev

      Hmm.. not sure. Suppose we should make sure the first term is actually processed by the while loop (although it appears identical to the script in the guide). Have you added Logger.log(keyword); on the line after var keyword... to make sure it's definitely processing the first keyword?

    4. medic_dev

      While you're at it, add Logger.log(content); to the line after content too so we can double check if it's actually getting written to the content string at all.

    5. Tane

      Now it works, thank you so much for helping me out!

Add a new comment.