I recently needed to use AMP for making a Website & came across a similar kind of scenario.
I solved it using amp-bind
.
Listing the details below. Hope this helps! :)
Scenario:
- Get the redirection URL from an API's response.
- Set the URL as the
href
of an anchor tag using AMP.setState()
& variable substitution.
- Use
layout="fixed-height"
& height="100vh"
attributes in <amp-script />
(Critical if you want variable substitution to work).
The code looks like this:
<!DOCTYPE html>
<html
⚡
...
>
<head>
<!-- Custom CSS -->
<style amp-custom>
/* Force overflow scrolling in fixed height AMP script container */
/* !important required to override AMP's default styling */
.script-container {
overflow: scroll !important;
}
/* ... */
</style>
<!-- AMP plug n play scripts -->
<script
async
custom-element="amp-script"
src="https://cdn.ampproject.org/v0/amp-script-0.1.js"
></script>
<script
async
custom-element="amp-bind"
src="https://cdn.ampproject.org/v0/amp-bind-0.1.js"
></script>
</head>
<body>
<!-- layout="fixed-height" & height="100vh" is required,
else AMP will only update url in it's state & not
bind it as the href for our CTA
-->
<amp-script
class="script-container"
layout="fixed-height"
height="100vh"
script="my-custom-js"
data-ampdevmode
>
<!-- ... -->
<!-- Below is my CTA (Call to Action) -->
<!-- The bracket's around href is amp-bind's variable substitution -->
<!-- "url" is the name of my AMP state variable -->
<a class="cta" [href]="url" />
</amp-script>
<!-- Custom JS that runs on the DOM in our amp-script tag -->
<script id="my-custom-js" type="text/plain" target="amp-script">
(async () => {
const response = await fetch('www.example.com/api');
AMP.setState({ url: response?.data?.url };
document.querySelector('.cta').addEventListener('click', event => {
console.log(event.target.getAttribute('href'));
});
})();
</script>
</body>
</html>