【问题标题】:How can I pass a variable from iframe to a parent window?如何将变量从 iframe 传递到父窗口?
【发布时间】:2014-10-30 16:02:58
【问题描述】:

我有一个颜色框父页面,其中包含一个带有不同 iFrame 的 TabContainer,用于第二个选项卡,其中对数据库进行了更改,需要更新父窗口的文本框。

【问题讨论】:

  • 请把图片换成你有的代码。

标签: javascript c# asp.net iframe colorbox


【解决方案1】:

很遗憾,您不能直接跨 iframe 的边界进行交互,因为这会带来安全风险。

一种解决方法是更改​​ iframe 中的 url 以包含 #anchor 值或 ?querystring,然后从父级读取 iframe 的 url。

【讨论】:

  • 您可以在 iframe 的 DOM 对象上使用 contentWindow.location.href。例如:var TheLocation = document.getElementById('myframe').contentWindow.location.href;
  • 您也可以从父级设置位置,因此这可以双向工作。
【解决方案2】:

希望你尝试过postMessage,这是一个javascript API,但是有浏览器限制。

页面可以这样发布消息。

var win = document.getElementById("iframe").contentWindow

win.postMessage(
  "value",
  "iframe-domain"
);

并且iframe页面可以收听这样的消息。

<script>
function listener(event){
  if ( event.origin !== "[parent-page-domain]" )
    return;

 // operate with event.data
}

if (window.addEventListener){
  addEventListener("message", listener, false)
} else {
  attachEvent("onmessage", listener)
}
</script>

来源 - http://javascript.info/tutorial/cross-window-messaging-with-postmessage

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-31
    • 2016-03-25
    • 2015-09-24
    相关资源
    最近更新 更多