要实现AMP和amp-iframe之间的通信,可以通过以下步骤进行操作:
// 发送消息给父AMP页面
window.parent.postMessage('Hello from amp-iframe!', '*');
// 监听来自父AMP页面的消息
window.addEventListener('message', function(event) {
if (event.origin === 'https://your-amp-page.com') {
// 处理来自父AMP页面的消息
console.log('Received message from parent AMP page:', event.data);
}
});
// 获取amp-iframe元素
const iframe = document.querySelector('amp-iframe');
// 发送消息给amp-iframe
iframe.contentWindow.postMessage('Hello from parent AMP page!', 'https://your-iframe-url.com');
// 监听来自amp-iframe的消息
window.addEventListener('message', function(event) {
if (event.origin === 'https://your-iframe-url.com') {
// 处理来自amp-iframe的消息
console.log('Received message from amp-iframe:', event.data);
}
});
通过上述代码,你可以在AMP页面和amp-iframe之间实现双向通信。在amp-iframe中,使用postMessage方法向父AMP页面发送消息,并通过监听message事件接收来自父AMP页面的消息。在父AMP页面中,使用postMessage方法向amp-iframe发送消息,并通过监听message事件接收来自amp-iframe的消息。