【JavaScript】frame跨域访问元素

什么是跨frame访问元素呢?好比main.html中有以下代码:html

<frameset cols="50%,*">
  <frame src="frame1.html">
  <frame src="frame2.html">
</frameset>

若是想在frame2.html的页面操做frame1.html中的元素,那么经过以下的js代码就能够完成:web

parent.frames[0].document

其中parent表示访问main.html的文档。frames[0]表示访问main.html中的第一个frame对象,也就是frame1.html页面。也能够经过name来指定访问特定的页面,例如:chrome

<frameset cols="50%,*">
  <frame name="myframe1" src="frame1.html">
  <frame name="myframe2" src="frame2.html">
</frameset>

frame2.html中的访问代码就能够改成:跨域

parent.frames["myframe1"].document

 

到这里咱们知道了frame之间如何访问元素,笔者这里只是列举了一种方法,有兴趣的读者能够自行googling。那么什么是跨域访问元素呢?浏览器

若咱们把上面main.html中的一个frame指向其它的域名地址(好比:www.google.com),那么咱们还能正常在myframe2中操做myframe1中的元素吗?安全

<frameset cols="50%,*">
  <frame name="myframe1" src="www.google.com">
  <frame name="myframe2" src="frame2.html">
</frameset>

答案是不行!在myframe2中操做myframe1中的元素,会获得以下的错误信息:frame Blocked a frame with origin "null" from accessing a cross-origin frame.google

浏览器是禁止这种行为的。那么有没有什么方法能够实现这种操做呢?spa

答案是有的,解决方法有多种,笔者稍后会把连接粘贴在后面。这里笔者说一下,笔者可行方法(就是禁用浏览器的安全域检查):code

笔者的Chrome是75.0.3770.142,环境是win7。htm

而后使用以下的命令启动chrome浏览器:

chrome.exe --disable-site-isolation-trials --disable-web-security --user-data-dir="your dir"

 

读者能够翻阅下面的连接,查看更详细的说明

1.Disable same origin policy in Chrome

2.blocked a frame of origin “null” from accessing a cross-origin frame - chrome

相关文章
相关标签/搜索