javascript - 如何使用 javascript 将值从父级传递到其 iframe

标签 javascript iframe

嗨,我想通过调用父链接页面值到其 iframe 链接页面来传递该值 示例代码为

<html>
    <head>
        <title>
        </title>
        <script>
            function sendvalue(v){
                alert(v);
            }
        </script>
    </head>
    <body>
        <form id="f">
            <input type="button" value="123" onclick="sendvalue(this.value)">
        </form>
        <iframe id="frame1" src="a.html" width="500px;"></iframe>
    </body>
</html>

a.html

<html>
    <head>
        <title>
        </title>
        <script>

        </script>
    </head>
    <body>
        <h3> Frame</h3>
        <form id="myform">
            Req value <input type="text" name="a" id="a">
        </form>
    </body>
</html>

当我调用 sendvalue 函数时,该值应该以输入字段的形式传递到 iframe 链接页面。 如何实现这一目标。

最佳答案

您可以使用 postMessage 在 2 个 iframe 之间进行通信。

在父框架上,您需要使用 iframeEl.contentWindow.postMessage(value as a string, can be json.stringified value) 抓取 iframe 的窗口

在子框架上,您需要添加 message 类型的事件,如下所示:

window.addEventListener('message', function(dataPassed) {
   //Your logic here.
})

了解更多信息read that

关于javascript - 如何使用 javascript 将值从父级传递到其 iframe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43344102/

相关文章:

javascript - 如何在不知道id的情况下从内页获取父iframe元素?

javascript - 在 iFrame 中暂停 YouTube 视频

javascript - 为什么这个 Javascript 代码只返回最后一个数字?

javascript - 用于创建带有象限的散点图的库

javascript - 模拟拖放文件事件

JavaScript 类型错误 "is not a constructor"

java - 为什么我在访问字符串时得到 "error : expected ;"?

javascript动态创建iframe,但是如何附加属性呢?

javascript - 如何使 iframe 中的所有链接在新选项卡中打开

javascript - 将数据属性值插入 Iframe src