AMP
  • websites

Copy Button

Introduction

This is a sample showing how to add a "copy" button to your page, allowing the user to copy some fixed item per-page. This uses an amp-iframe, running custom JS, that loads in the background while a placeholder button remains visible.

Setup

We use amp-iframe to load a copy button, replacing a placeholder button.

<script async custom-element="amp-iframe" src="https://cdn.ampproject.org/v0/amp-iframe-0.1.js"></script>

How a "Copy" button works

By including amp-iframe with custom JS (this is in /static/samples/files/copier.html), we can perform any operation from vanilla JS, including copy.

The iframe is allowed to load anywhere on your AMP as it has a placeholder, and in our case, this placeholder has exactly the same presentation as the final display so it's not obvious when it is "swapped out". Users who hover over the button before it loads will see a "disabled" indicator.

We pass the data to be copied via the hash. The copier "helper" page can always serve the same HTML and can be cached in its own right.

<amp-iframe sandbox="allow-scripts" width="64" height="42" frameborder="0" src="/static/samples/files/copier.html#This text was copied from amp.dev!">
  <button class="copy-button" placeholder disabled>Copy</button>
</amp-iframe>

Dynamically change the value to copy

We can use amp-bind to update the value being passed to the copier iframe. Whenever the value is changed (via input-debounced), we update the hash param on the iframe so the copier can copy the new value.

First we define an input field which updates an amp-state variable called textToCopy.

Copy the contents of the input
<span>
  <input type="text" value="Hello World" on="input-debounced: AMP.setState({ textToCopy: event.value })">
  <div>Copy the contents of the input</div>
</span>

Then we bind the iframe's src attribute to the value of the textToCopy amp-state variable.

<amp-iframe sandbox="allow-scripts" width="64" height="42" frameborder="0" src="/static/samples/files/copier.html#Hello World" [src]="'/static/samples/files/copier.html#' + textToCopy">
  <button class="copy-button" placeholder disabled>Copy</button>
</amp-iframe>
هل تحتاج إلى مزيد من التوضيح؟

إذا لم تكن الإيضاحات الموجودة في هذه الصفحة تُجيب على جميع أسئلتك، فلا تتردد في التواصل مع مستخدمي AMP الآخرين لمناقشة حالة الاستخدام المحددة لديك بالضبط.

الذهاب إلى Stack Overflow
هل هي ميزة غير موضحة؟

يشجع مشروع AMP مشاركتك ومساهمتك بشدة! ونأمل أن تكون مشاركًا دائمًا في مجتمعنا مفتوح المصدر، ولكننا نشجع أيضًا المساهمات التي تحدث لمرة واحدة في الأمور التي تتحمس لها.

تعديل العينة على GitHub