1

I am trying to change the HREF of a link (<a href...) when the user clicks based on a web service response and then navigate to the new received URL.

The use case is that we need to check some of the existant links and modify some of them but we cannot change the (because of the CMS).

We tried using amp-script but we are not beeing able to stop (prevent default) the event, change the URL (this we can) and then relaunch the event. We couldn't find a way to redirect current URL within the context of a amp-script.

Any idea?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
user1399063
  • 151
  • 1
  • 1
  • 4

1 Answers1

0

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>