想要獲取子窗口的變量,
必須滿足同源條件.
父級
test.html
<iframe src="son.html" width="" name="son" height=""></iframe>
<script type="text/javascript">
var ifr = document.getElementsByTagName("iframe")[0];
// 父級拿到子級的變量.
ifr.onload = function () {// 因為iframe 異步加載,所以要等到onload 才能獲取數(shù)據(jù).
console.log(window.frames["son"].a);
console.log(ifr.contentWindow.a);
}
</script>
子級
son.html
<body>
demo
<script type="text/javascript">
var a = 123;
// 子級拿到父級的變量
console.log(window.parent.ifr);
</script>
</body>
iframe 跨域
- src里添加哈希值
子級通過 location.hash 取值. 父傳子.
test.html
<body>
<iframe src="https:// 不同源/son.html" width="" name="son" height=""></iframe>
<script type="text/javascript">
var ifr = document.getElementsByTagName("iframe")[0];
var age = 50;
var oSrc = ifr.src;
document.onclick = function () {// 按需傳值.
age++;
ifr.src = oSrc + "#" + age;
}
</script>
</body>
son.html
<body>
demo
<script type="text/javascript">
var a = 123;
// 子級拿到父級的變量
// 必須進行監(jiān)聽
var lastHash = location.hash;
setInterval(function () {
if (lastHash != location.hash) {// 當(dāng)值不變時,
console.log(location.hash.slice(1));
lastHash = location.hash;
}
},50);
// 因為setInterval 要一直監(jiān)聽,太過耗費性能
// 所以這種跨域方式不怎么用了.
// 剛才發(fā)現(xiàn)有一個監(jiān)聽 哈希值的事件 // 用這個應(yīng)該也可以
document.body.onhashchange = function () {
console.log(location.hash);
}
</script>
</body>
2.window.name
完成 子傳父
window.name 是可以跨域的.
同一個窗口的不同源的網(wǎng)頁,都共享一個 window.name
都可以操作window.name
我們設(shè)置一個中間頁面, uncle
test 和 uncle 是 父子,且同源, 可以通過 contentWindow 完成子傳父
uncle 和 son 不是同源, 但同一個iframe 共享同一個 window.name
可以完成 互相之間的值傳遞.
所以test 就能通過 uncle 來獲取 son給他的數(shù)據(jù).
test.html
<body>
<iframe src="son.html" width="" name="son" height=""></iframe>
<script type="text/javascript">
var ifr = document.getElementsByTagName("iframe")[0];
var flag = true;// 這是為了只執(zhí)行一次.// 否則會無休止的刷新.因為 ifr.src 會一直觸發(fā) onload
ifr.onload = function () {
if (flag) {
flag = false;
ifr.src = "./uncle.html";
} else{
// 如果這里 flag = true 就變成了 類似 toggle 的功能.
console.log(ifr.contentWindow.name);
}
}
// 假設(shè)我們希望, 獲取完值后,頁面返回到 son
function cb (data) {
console.log(data);
}
function getName (ifr, callback) {
var src = ifr.src;
ifr.src = "./uncle.html";
var flag = true;
ifr.onload = function () {
if (flag) {
flag = false;
callback(ifr.contentWindow.name);
ifr.src = src;
}
}
}
getName(ifr, cb);
</script>
</body>
uncle.html
這個什么都可以沒有
son.html
<body>
demo
<script type="text/javascript">
window.name = "son is hansom";
</script>
</body>
這個過程完成了子傳父.
無論是 用哈希值方式, 還是 window.name 的方式
都必須有傳值的情況下,才能獲取值.
不能在沒傳的情況下獲取值.