Google AMP html - insert amp-iframe without src at

2019-06-01 20:12发布

问题:

I'm trying to run a script inside an AMP page.

There is no page I need to load within the src attribute; my script should inject an <iframe> with the correct src (it is unknown at first load, only received in response to a request made by my script).

Is this possible in AMP?

Disclaimer: I'm open to different approaches to accomplish the same result - injecting an <iframe> with an src attribute within an AMP page.

Thank you

回答1:

The AMP page cannot contain any javascript in the first place, so this won't work: https://www.ampproject.org/docs/reference/spec.html#html-tags



回答2:

The only way to achieve your goal is to:

  1. create an iframe with a src attribute pointing to an HTML page you control
  2. in that page load the Javascript that does the work. You can see a similar approach in this example: https://ampbyexample.com/advanced/how_to_create_interactive_amp_pages/


回答3:

As stated by @ade you can pull this off. Think about it like this.....

You'll have an HTTPS resource that you can hit that will return the blank iframe along with all of the JS code you need to populate the iframe. So basically an entirely functioning page that will be returned to the AMP-IFRAME.

Calling this from the src attribute of an AMP-IFRAME tag will then pull in your page that includes a blank iframe and all of the scripting needed to populate it or manipulate it. So all of your custom code is happening within the AMP-IFRAME tag but all of it's resources live within the embedded iframe tag that the AMP-IFRAME tag pulls in and renders.

We have a custom video player that works very similar to what you are talking about. I created a template that can be hit via HTTPS that returns a page that iframes our video as well as includes all the scripts to play it and manipulate it. It's all contained in a nice neat little package and the only thing required to use the AMP-IFRAME is the script that extends it. Check out all the AMP-FRAME documentation here.

Hope this helps.