AMP Viewer Messaging
The AMP Viewer Messaging library allows an AMP Viewer to establish a communication channel with an AMP document.
See Connecting AMP Viewers with AMP pages for more information.
Installation
Install via:
npm i @ampproject/viewer-messaging
Usage
Assuming you have an AMP document hosted on https://example.com/amp-document
:
import {Messaging} from '@ampproject/viewer-messaging';
const iframe = document.createElement('iframe');
iframe.setAttribute(
'src',
`https://example.com/amp-document#origin=${window.location.origin}`
);
document.body.appendChild(iframe);
const messaging = await Messaging.waitForHandshakeFromDocument(
/* source window */ window,
/* target window */ iframe.contentWindow,
/* target origin */ 'https://example.com'
);
messaging.setDefaultHandler((name, data, rsvp) => {
console.log(`Received message: ${name}`);
});
// use messaging.sendRequest(...) to make requests to the AMP document
Note: The AMP document needs to include the amp-viewer-integration
script:
<script async src="https://cdn.ampproject.org/v0/amp-viewer-integration-0.1.js"></script>