javascripthtmlgoogle-apps-scripturliframe

Get URL parameters of iframe host


Right now, I have code that gets the parameters of the current URL:

function doGet(e) {
  var page = e.parameter.page || 'Recruit_Create';
  var urlGSID = e.parameter.gsid || 'null';
  var urlSheet = e.parameter.sheet || 'null';
  var html = HtmlService.createTemplateFromFile(page);
  html.urlGSID = urlGSID;
  html.urlSheet = urlSheet;
  return html.evaluate().setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}

The problem is, my code is hosted on another site inside an iframe. This current code gets the GAS URL (script.google.com/...?page=...), not the URL of the site hosting the iframe (example.com/...?page=...). How can I instead get the URL parameters of the iframe host?


Solution

  • To talk to the parent page you need to use the PostMessage API.

    A GAS application is hosted two iframes deep, this make communication with the iframe a bit more tricky, as neither the host page or the GAS app have sight of the other.

    To overcome this you need to first add the following to the GAS app

    top.postMessage('gasFrame', '*')
    

    Then on your page you need to listen for that message and respond.

    window.addEventListener(
      "message",
      (event) => {
        if (event.data === "gasFrame") {
          event.source.postMessage(location.href, ‘*’)
        }
      },
      false
    )
    

    Finally your GAS app then needs to listen for this response.

    let e
    
    window.addEventListener(
      "message",
      (event) => {
        e = doGet(event)
      },
      false
    )