如何将变量赋值给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 < IT / design < 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
相关产品推荐
相关产品推荐

