简体   繁体   English

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

[英]How to pass value from parent to its iframe using javascript

Hi i want to pass the value by calling the parent link page value to its iframe link page sample code is嗨,我想通过将父链接页面值调用到其 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

<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>

when i call sendvalue function then the value should pass to iframe link page in form for input field.当我调用 sendvalue 函数时,该值应该以输入字段的形式传递给 iframe 链接页面。 how this can be achieved.这是如何实现的。

You can use postMessage in order to communicate between 2 iframe.您可以使用postMessage在 2 个 iframe 之间进行通信。

On the parent frame you need to grab the iframe's window with iframeEl.contentWindow.postMessage(value as a string, can be json.stringified value)在父框架上,您需要使用iframeEl.contentWindow.postMessage(value as a string, can be json.stringified value)抓取 iframe 的窗口

On the child frame you need to add event of type message , something like that:在子框架上,您需要添加message类型的事件,如下所示:

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

For more info read that有关更多信息, 请阅读

<html>
<head>
<title>
</title>
<script>
function sendvalue(v){
document.getElementById('va').value = v;
window.frames['framename'].document.getElementById("a").value = v


}
</script>
</head>
<body>
<form id="f">
 <input type="button" value="123" onclick="sendvalue(this.value)">
 <input type="text" name="va" id="va">
</form>
<iframe  name="framename" src="a.html" width="500px;"></iframe>
</body>
</html>

a.html一个.html

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

The Best way it to add to you Iframe将它添加到您的 Iframe 的最佳方式

<iframe id="frame1" src="a.html?data=SomeData" width="500px;"></iframe>

and inside the iframe you can get the information by making varible在 iframe 中,您可以通过设置变量来获取信息

var MYDATA = location.href.split('=')[1].split('&');

(you will see that MYDATA=SomeData ) (你会看到MYDATA=SomeData

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM