How to alter current url in AMP HTML?

Viewed 1161

In my website, filtering of products is done server side by alterining the URLS, ie. by adding ?q=alpha+beta+gama at the end of the URL if the category is to be filtered for products containing tags alpha, beta & gama

I want to remove "beta" from the url should someone press a button.

Seems easy in non-amp pages by using javascript, but I cant find a way to do it in amp.

Is there a script that can fiind current url and remove some keywords from them based?

I am planning to achieve this with a form. The form will have multiple inputs. On pressing submit button, the input fields in the form will be grabbed and appending to current url. Situation 1:

The current url is website.com/?view=amp
Desirable url is website.com/?view=amp&q=alpha+beta+gama

Situation 2

Current url is website.com/?view=amp&q=alpha+beta+gama+delta
Second desirable URL is website.com/?view=amp&q=alpha+gama
2 Answers

We can't read current url and manipulate it in AMP.

What is solution to create dynamic url (or links) in AMP?

We should have a state strategy to create dynamic url in AMP. We should render default state in server side and create dynamic url when states change. for example:

Default states (rendered in server side):

<amp-state id="filters">
  <script type="application/json">
    {
      "alpha": "",
      "beta": "",
      "gama": ""
    }
  </script>
</amp-state>

Dynamic url base on states:

<a href="website.com/?view=amp" data-amp-bind-href="'website.com/?view=amp&q=' + filters.alpha + (filters.beta ? '+' + filters.beta : '') + (filters.gama ? '+' + filters.gama : '')">dynamic link</a>

As per your use-case, you can simply use amp-bind to keep updating the URL in case user adds/changes default input value.

e.g.

<label>Username
    <input name="username" on="change:AMP.setState({name: event.value})"/>
</label>
<a href="example.com/default-url" [href]="'example.com/default-url?name=' + name">Submit</a>

So, you need to provide a default URL as href value by default and [href] will update the default URL when any change on the input box is made (amp-bind works only when elements having AMP actions are triggered, remove). You can read more about the actions(i.e. any change) for making URL change here.

Related