目录
前言
iframe在web前端开发中很常见,iframe嵌入的页面与当前页面是在同一个域名下,是不存在跨域。但是在主域相同,子域不同的情况下,就会存在跨域,可以使用document.domain去解决。如下:iframe的跨域处理(document.domain)
iframe一般需要主动设置高度才会完全显示嵌入页面的内容,而内容可能会在迭代的时候变化,所以如果iframe的高度写死,那么就显得这个iframe不够智能。可以通过js去计算内容的高度,然后给iframe进行设置动态高度。如下:iframe计算高度
iframe的跨域处理(document.domain)
a.xxx.com域名下的a.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript">
document.domain='xxx.com'
</script>
</head>
<body>
<iframe src="https://b.xxx.com/b.html" id="open_api_iframe" scrolling="no" frameborder="no" border="0" width="100%"></iframe>
</body>
</html>
b.xxx.com域名下的b.html
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript">
document.domain='xxx.com'
</script>
</head>
注意:
- 该解决方案的前提是主域名相同,子域名不同。主域名是:
xxx.com
。 - 如果两个页面都在同一域名之下,就不需要设置document.domain。
iframe计算高度
a.xxx.com域名下的a.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript">
document.domain='xxx.com'
</script>
</head>
<body>
<iframe src="https://b.xxx.com/b.html" id="open_api_iframe" scrolling="no" frameborder="no" border="0" width="100%"></iframe>
<script type="text/javascript">
function setIframeHeight(iframe) {
if (iframe) {
var iframeWin = iframe.contentWindow || iframe.contentDocument.parentWindow;
if (iframeWin.document.body) {
iframe.height = iframeWin.document.documentElement.scrollHeight || iframeWin.document.body.scrollHeight;
}
}
};
window.onload = function() {
setIframeHeight(document.getElementById('open_api_iframe'));
};
</script>
</body>
</html>
b.xxx.com域名下的b.html
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript">
document.domain='xxx.com'
</script>
</head>
注意:
- 实现思路:获取iframe嵌套的内容高度=>然后将此高度赋值给iframe。
- 如果两个页面都在同一域名之下,就不需要设置document.domain。
iframe.contentWindow
兼容IE低版本(IE7),iframe.contentDocument.parentWindow
标准浏览器使用。
关注更多知识,不迷路
小伙伴,用你可爱的小手,点个赞,关注我了解更多知识!!!
如果任何疑问的可以在评论区留言或者私聊。
可以加QQ群交流:568984539,加群备注‘地区-名字-技术类型’。
更多前端、uniapp、nodejs等相关知识可关注我个人博客:https://blog.youkuaiyun.com/qq_42961150?spm=1011.2124.3001.5343