Search code examples
javascriptgoogle-apps-scriptweb-applicationsbrowser-history

Handling History Changes In Google Apps Script Web App


I'm building a web app using Google Apps Script, looking to replicate a multi-page site, and struggling to get the history changes to do what I want.

I have links set up with event listeners that use google.script.history.push() like this:

document.getElementById('navPage1').addEventListener('click', function() {
  google.script.history.push({timestamp:new Date().getTime(),page:'page1'}, {page:'page1'})
});

When I click on this link, I see the URL update accordingly with the parameters (i.e. to https://script.google.com/a/XXX/macros/s/XXX/dev?page=page1).

In my HTML file I then want to use google.script.history.setChangeHistory() to detect these changes and load content accordingly. However, the event doesn't seem to be triggering at all. I currently have it set up just to log on history change, and I'm not seeing anything at all:

google.script.history.setChangeHandler(function(e) {
  console.log('History Change Triggered');
});

Have I misunderstood how these should be used?


Solution

  • As written in the documentation,

    Calling history.pushState() or history.replaceState() won't trigger a popstate event. The popstate event is only triggered by performing a browser action, such as clicking on the back button (or calling history.back() in JavaScript), when navigating between two history entries for the same document.

    Related Answer:

    Sample web app