使用iframe如何通过url传参把数据从一个页面传到另一个页面(contentWindow)

时间:2021-11-16 02:43:41

最近做的项目使用Iframe,使用起来感觉挺方便的。但是唯一感觉不开森的就是使用Iframe后,页面的地址栏的是不改变的哦,那么我们如何通过url将数据从一个页面传到另一个页面?

<div style="background-color: transparent;height: 580px;width: 1050px">
<iframe name="studyFrame" allowtransparency="true" src="" width="100%" height="100%"
id="studyManageIframe" style="border: none;">

</iframe>
</div>

记住我的iframe的id值哦——studyManageIframe
下面这段代码是获取iframe 中嵌套的页面的url参数的。

function GetIframeQueryString(name) {
var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
/*var iframeSrc=window.parent.document.getElementById("studyManageIframe").contentWindow.location.href ;*/
var r =window.parent.document.getElementById("studyManageIframe").contentWindow.location.search.substr(1).match(reg);
if (r != null) {
return decodeURI(r[2]);
}
return null;
}

分解来说就是,

var iframeSrc=window.parent.document.getElementById("studyManageIframe").contentWindow.location.href ;`

可以把这个console一下,会发现这就是我们嵌套的在iframe中的那个页面的src哦,当然我们的参数也会一起出现的。
使用iframe如何通过url传参把数据从一个页面传到另一个页面(contentWindow)
然后用上正则,哈哈,参数的值就得到了啊!
通过contentWindow 这里,返回的是iframe的window对象。