原理
- 每个窗口都有自己独立的 window.name
- 当修改一个窗口的src属性的时候,不会影响这个窗口的 window.name 属性
- window.name可以存储不超过2M的数据,传递的数据都会变成string类型
例
准备
- a.html,在localhost:3000上
- b.html,在localhost:3000上
- c.html,在localhost:4000上
a 和 b 是同源的,c 是独立的
a 先引用c,c把值放到window.name中,然后把a引用的地址改到b
代码
- a.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>a.html</title> </head> <body> <iframe id="iframe" src="http://localhost:4000/c.html" frameborder="0" "load()"></iframe> <script type="text/javascript"> let first = true;//第一次加载 function load(){ if(first){ let iframe = document.querySelector("#iframe"); iframe.src = 'http://localhost:3000/b.html'; first = false; }else{ console.log(iframe.contentWindow.name);//yuhua } } </script> </body> </html>
- b.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> </body> </html>
- c.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> c页面 <script type="text/javascript"> window.name = 'yuhua'; </script> </body> </html>