AMP 会在点击时更改链接网址



当用户根据 Web 服务响应单击然后导航到新收到的 URL 时,我正在尝试更改链接的 HREF(

用例是我们需要检查一些现有的链接并修改其中一些,但我们无法更改(因为 CMS)。

我们尝试使用 amp-script,但我们无法停止(阻止默认)事件、更改 URL(我们可以这样做),然后重新启动事件。我们找不到在 amp 脚本上下文中重定向当前网址的方法。

知道吗?

我最近需要使用AMP来制作网站,并遇到了类似的情况。 我用amp-bind解决了它。 下面列出详细信息。希望这有帮助!:)

场景:

  • 从 API 的响应中获取重定向 URL。
  • 将URL设置为使用AMP.setState()和变量替换的锚标记的href
  • <amp-script />中使用layout="fixed-height"height="100vh"属性(如果您希望变量替换起作用,则为"关键")。

代码如下所示:

<!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>

最新更新