iframe 跨域
本地建立两个域 www.site1.com 和 www.site2.com
一、同域交互
site1/iframe/index.html 和 site1/iframe/index2.html
index.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>site1-index</title> <script> function fMain(){ console.log('from site-index'); } function exec_iframe(){ window.myframe.fIframe(); } </script> </head> <body> <p>site1-index</p> <input type="button" value="调用site1-index2" onclick="exec_iframe()"> <br /><br /> <iframe src="http://www.site2.com/iframe/index2.html" name="myframe" width="500" height="100" frameborder="1"></iframe> </body> </html>
index2.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>site1-index2</title> <script type="text/javascript"> function fIframe(){ console.log('from site1-index2'); } function exec_main(){ parent.fMain(); } </script> </head> <body> <p>site1-index2</p> <input type="button" value="调用site1-index" onclick="exec_main()"> </body> </html>
访问 http://www.site1.com/iframe/index.html
二、跨域交互
如果按照同域交互的方法把 iframe 的 src 改为 http://www.site2.com/iframe/index.html,则会报错:
具体实现:
site1/iframe/index3.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>site1-index3</title> <script> function fMain(){ console.log('from site1-index3'); } function exec_iframe(){ if(typeof(exec_obj)=='undefined'){ exec_obj = document.createElement('iframe'); exec_obj.name = 'tmp_frame'; exec_obj.src = 'http://www.site2.com/iframe/execB.html'; exec_obj.style.display = 'none'; document.body.appendChild(exec_obj); }else{ exec_obj.src = 'http://www.site2.com/iframe/execB.html?' + Math.random(); } } </script> </head> <body> <p>site1-index3</p> <input type="button" value="调用site2-index2" onclick="exec_iframe()"> <br /><br /> <iframe src="http://www.site2.com/iframe/index2.html" name="myframe" width="500" height="100" frameborder="1"></iframe> </body> </html>
site1/iframe/execA.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<script type="text/javascript">
parent.parent.fMain();
</script>
<body>
</body>
</html>
site2/iframe/index2.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>site2-index2</title> <script> function fIframe(){ console.log('from site2-index2'); } function exec_main(){ if(typeof(exec_obj)=='undefined'){ exec_obj = document.createElement('iframe'); exec_obj.name = 'tmp_frame'; exec_obj.src = 'http://www.site1.com/iframe/execA.html'; exec_obj.style.display = 'none'; document.body.appendChild(exec_obj); }else{ exec_obj.src = 'http://www.site1.com/iframe/execA.html?' + Math.random(); } } </script> </head> <body> <p><input type="button" value="调用site1-index3" onclick="exec_main()"></p> </body> </html>
site2/iframe/execB.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<script type="text/javascript">
parent.window.myframe.fIframe();
</script>
<body>
</body>
</html>
访问 http://www.site2.com/iframe/index3.html
参考: