You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

@iframe-resizer/react实现报错:JSON解析异常求助

解决@iframe-resizer/react触发的JSON解析错误

问题分析

你遇到的Uncaught SyntaxError: Unexpected token 's', "scroll-to-top" is not valid JSON错误,是因为iframe-resizer库默认会尝试解析所有来自iframe的消息为JSON格式,但收到了纯字符串"scroll-to-top",导致解析失败。这个消息大概率来自iframe内部的脚本(可能是自定义逻辑或第三方库)直接发送的非JSON格式消息。

解决方案

1. 过滤非JSON消息

通过messageFilter配置项,让库忽略不符合JSON格式的消息,避免解析报错。修改你的组件代码:

<IFrameResizer
  src={iframeSrc}
  license="GPLv3"
  className="iframe-dialog"
  title="Iframe Dialog"
  onLoad={onLoad}
  scrolling={false}
  forwardRef={iframeRef}
  style={{
    width: "100%",
    border: "none",
    opacity: "100",
    height: "100vh",
  }}
  messageFilter={(message) => {
    // 直接过滤掉"scroll-to-top"字符串
    if (typeof message === 'string' && message === 'scroll-to-top') {
      return false;
    }
    // 仅保留可解析为JSON的消息
    try {
      JSON.parse(message);
      return true;
    } catch (e) {
      return false;
    }
  }}
/>

2. 修正iframe内部的消息格式(若你控制iframe内容)

如果iframe是你开发的,把发送的"scroll-to-top"改成JSON格式,既避免报错,还能在父组件中处理该消息:

iframe内的代码修改:

// 替换原有的postMessage调用
window.parent.postMessage(JSON.stringify({ type: "scroll-to-top" }), "*");

父组件中添加消息处理:

const handleMessage = (msg) => {
  if (msg.data.type === "scroll-to-top") {
    // 执行滚动到顶部的逻辑
    window.scrollTo({ top: 0, behavior: "smooth" });
  }
};

<IFrameResizer
  // 其他属性...
  onMessage={handleMessage}
/>

3. 定位消息来源

如果不确定是谁发送的"scroll-to-top",可以在iframe内部添加监听,打印所有发送的消息:

window.addEventListener('message', (event) => {
  console.log('发送的消息内容:', event.data);
  console.log('消息来源脚本:', event.source);
});

运行后查看控制台,就能找到发送该消息的代码位置,针对性处理。

内容的提问来源于stack exchange,提问作者Soham Dey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 12:12:14