javascripthtmlrandomgoogle-web-designer

Starting from random pages in Google Web Designer


I've been using Google Web Designer for a few months and I have a question. I don't know if it's possible to do in GWD:

I want the index.html file to load a different random page, choosing between 3 pages. When you hit reload, it should load another random page, and so on. The pages don't need to appear in order. I'm trying to find out how this can be done but I had no success so far.


Solution

  • This can be accomplished with a custom JavaScript event handler.

    The <gwd-doubleclick> element fires an adinitialized event before any content is displayed, which we can use to make sure our changes are applied before the user sees the first page. It also provides a .goToPage(n) method which we can use to switch pages. (goToPage has additional arguments that can be used to control animation between pages, but we can ignore those because we want the default behaviour of instantly jumping.)

    Start by adding a new event handler.

    1. target: document.body
    2. event: Google Ad: Ad Initialized
    3. action: Custom: Add Custom Action
    4. configuration: a name of your choice (such as gwd.goToRandomPage), for the following code:

      var pages = 3; // adjust as appropriate
      var targetPage = Math.floor(Math.random() * pages);
      event.target.goToPage(targetPage);
      

    In code view you can see that this produces something like the following:

     // This script block is auto-generated. Please do not edit!
    gwd.actions.events.registerEventHandlers = function(event) {
      gwd.actions.events.addHandler('document.body', 'adinitialized', gwd.goToRandomPage, false);
    };
    gwd.actions.events.deregisterEventHandlers = function(event) {
      gwd.actions.events.removeHandler('document.body', 'adinitialized', gwd.goToRandomPage, false);
    };
    

    You could choose to skip the GWD UI and use the standard JavaScript event handling APIs to accomplish the same thing, with something along the lines of:

    document.body.addEventListener('adinitialized', function() {
      var pages = 3; // adjust as appropriate
      var targetPage = Math.floor(Math.random() * pages);
      event.target.goToPage(targetPage);
    });
    

    However, you probably want to avoid this in general, because it will prevent GWD from handling things like element renaming automatically.

    If you'd like to jump to one of a specific set of pages, instead of selecting from all pages, you could use an array of page IDs instead.

    var pageIds = ['page1_1', 'page1_2'];
    var targetPage = pageIds[Math.floor(Math.random() * pageIds.length)];
    event.target.goToPage(targetPage);
    

    For future reference, you can find most of the component APIs described in the documentation. Questions about GWD that do not involve code or are otherwise unsuitable for Stack Overflow should be asked on the GWD support forum instead.