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

如何将变量赋值给iframe的src属性,实现动态修改iframe链接

问题原因

  • HTML是静态标记语言,无法直接解析JavaScript变量,你直接在iframe标签的src属性中写receivedData时,浏览器会将其当作普通字符串处理,不会读取对应变量的实际值。
  • 你用let声明的receivedData是if代码块内的块级作用域变量,即使在JS代码中,块外也无法访问该变量。

修复方案

你只需要给iframe添加一个ID方便DOM选择,在收到postMessage数据后直接通过JS给iframe的src属性赋值即可,建议额外添加发送源校验避免安全风险,完整修改后的代码如下:

<!DOCTYPE HTML>
<html lang="en-US">
<head>
    <meta charset="UTF-8">
    <link rel="mask-icon" href="https://assets-cdn.github.com/pinned-octocat.svg" color="#000000">
    <link rel="icon" type="image/x-icon" href="https://assets-cdn.github.com/favicon.ico">
    <link rel="shortcut icon" type="image/x-icon" href="https://assets-cdn.github.com/favicon.ico">
      
    <style> 
        body { background: #232323; width: 95%; margin: 0 auto; }
        
        /* Responsive Container for iFrame */
        .embed-container { position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden; max-width: 100%; } 
        .embed-container iframe, .embed-container object, .embed-container embed { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }
    </style>
    
    <title>Tech Ops PH | your &lt; IT / design &lt; partner </title>
  
  <script type="text/javascript">
  window.onmessage = (event) => {
    // 可选:添加发送源校验,替换成你实际的消息发送方域名避免安全问题
    // if (event.origin !== 'https://你的可信域名.com') return
    if (event.data) {
       // 直接获取iframe元素赋值src
       const iframe = document.getElementById('reportIframe')
       iframe.src = event.data
    }
  };
  </script>
  
</head>

    <body>
        <div class='embed-container embed-responsive embed-responsive-4by3'>
                <!-- 移除原来的src属性,添加id方便JS定位 -->
                <iframe id="reportIframe" width="600" height="9000" frameborder="0" style="border:0" allowfullscreen></iframe>
        </div>
    </body>
    
    </html>

补充说明

  • 我们给iframe添加了id="reportIframe",方便JS快速选中该元素
  • 收到消息后不需要额外定义变量,直接将收到的event.data赋值给iframe的src属性即可生效
  • 注释中保留了可选的发送源校验规则,推荐生产环境启用避免恶意消息注入风险

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 03:18:04