Rafael
Rafael

Reputation: 53

Dynamic src in AMP iframe

I'm working in an application that is embed in other websites and some of them use AMP. I'm currently using amp-iframe and I need the website url that the iframe is currently embed in for my app to work properly. I'm trying to pass it through params to use it in my application.

What I've been trying to do is getting the location.href (or location.origin + location.pathname) with amp-script and setting an AMP State to dynamically change the Iframe src. Currently not working.

HTML:

<amp-script layout="container" src="https://cdn.website.com/script.js">
       <amp-iframe height="150" resizable sandbox="allow-scripts allow-same-origin allow-popups allow-forms" frameborder="0" src="https://website.com/dev/html" [src]="dynamicUrl">
          <div overflow tabindex="0"></div>
      </amp-iframe>
</amp-script>

JS:

function checkForAmp(method) {
  if (window.AMP && typeof window.AMP.setState === "function") {
    method();
  } else {
    setTimeout(function () {
      checkForAmp(method);
    }, 50);
  }
}

function getUrlAndUpdateWidget() {
  const url = `https://website.com/dev/html?dynamic-url=${
    window.AMP.win.location.origin + window.AMP.win.location.pathname
  }`;
  window.AMP.setState({ dynamicUrl: url });
}

checkForAmp(getUrlAndUpdateWidget);

Any ideas how to work around it?

Thanks!

Upvotes: 0

Views: 871

Answers (1)

Ben Morss
Ben Morss

Reputation: 126

Unfortunately, the AMP object to which you have access in amp-script is not the same thing as the AMP object outside the worker.

AMP.win is undefined. I don't even think window.AMP.setState === "function" will work.

See here for a sample showing how to use AMP.setState in amp-script!

We do need someone to introduce support for the location object. Commenting on the github issue, as you did, helps. What we really need is someone who has time to contribute the code 😎

Upvotes: 1

Related Questions