iframe获取父页面URL

不跨域情况:

1
2
3
4
5
6
7
const getParentUrlInIfram = () => {
if(window.parent !== window.self) { //判断是否存在iframe
window.top.location.href = '/' // 只有一层iframe时有效
// 或
window.parent.location.href = '/'
}
}

跨域情况,无解。只能间接的修改子页面URL模拟修改父页面URL

1
2
3
4
5
6
7
const getParentUrlInIfram = () => {
if(window.parent !== window.self) { //判断是否存在iframe
window.top.location.href = '//localhost:8080/' // 只有一层iframe时有效
// 或
window.parent.location.href = '//localhost:8080/'
}
}

另外,跨域时可获取父页面URL

1
2
3
4
5
const getParentUrlInIfram = () => {
if(window.parent !== window.self) { //判断是否存在iframe
return document.referrer
}
}