Messaging between an AMP Doc and a Viewer
npm install @ampproject/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.
Install via:
``sh`
npm i @ampproject/viewer-messaging
Assuming you have an AMP document hosted on https://example.com/amp-document:
`js
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:
`html``