AMP页面报错求助:iframe标签违规及自定义JS禁用问题(Next.js)
Next.js AMP页面iframe报错解决方案
报错分析
- 标签
iframe只能作为noscript后代出现,需替换为AMP官方组件amp-iframe - AMP禁止自定义JavaScript,所有DOM处理必须在服务端完成(如
getStaticProps/getServerSideProps中执行)
代码修改方案
完善现有getAmpSocial函数,将匹配到的WordPress自定义iframe替换为符合AMP规范的amp-iframe,同时移除违规iframe:
export const getAmpSocial = (body, router, liveBlogCheck) => { if (!body) return body; // 移除带allow-scripts的违规iframe(AMP不允许iframe启用脚本) body = body.replace(/<iframe[^>]*sandbox="allow-scripts" ?[^>]*>.*?<\/iframe>/gi, ''); // 匹配wpcom保护iframe并替换为amp-iframe const wpcomIframeRegex = /<iframe\s+id="wpcom-iframe-[a-f0-9]+-[0-9]+-[0-9]+"\s+width="[^"]+"\s+height="[^"]+"\s+src="https:\/\/embeds\.indianexpress\.com\/protected-iframe\/[a-f0-9]+-[0-9]+-[0-9]+"\s+scrolling\s+frameborder="0"\s+class="wpcom-protected-iframe">\s+<\/iframe>/g; body = body.replace(wpcomIframeRegex, (match) => { // 提取原iframe的核心属性 const widthMatch = match.match(/width="([^"]+)"/); const heightMatch = match.match(/height="([^"]+)"/); const srcMatch = match.match(/src="([^"]+)"/); const idMatch = match.match(/id="([^"]+)"/); if (!widthMatch || !heightMatch || !srcMatch) return ''; // 构造符合AMP规范的amp-iframe标签 return ` <amp-iframe id="${idMatch[1]}" width="${widthMatch[1]}" height="${heightMatch[1]}" layout="responsive" sandbox="allow-same-origin allow-popups" frameborder="0" src="${srcMatch[1]}" class="wpcom-protected-iframe" > <!-- 添加占位符满足AMP对amp-iframe的位置规则 --> <div placeholder></div> </amp-iframe> `.trim(); }); return body; };
关键注意事项
amp-iframe必须设置layout属性(推荐responsive适配移动端)- sandbox属性仅允许AMP许可的取值,禁止添加
allow-scripts - 需确保
amp-iframe的src为HTTPS协议(你的目标链接已符合) - 在Next.js AMP页面中,Next.js会自动处理AMP组件依赖;若手动处理HTML,需在head添加组件脚本:
<script async custom-element="amp-iframe" src="https://cdn.ampproject.org/v0/amp-iframe-0.1.js"></script> - 所有HTML替换逻辑必须在服务端执行,避免客户端运行自定义JS触发AMP报错
内容的提问来源于stack exchange,提问作者Umesh Singh
相关产品推荐
相关产品推荐

