js iframe跨域訪問(同主域/非同主域)分別深入介紹

來源:互聯網
上載者:User

js跨域是個討論很多的話題。iframe跨域訪問也被研究的很透了。
一般分兩種情況
一、 是同主域下面,不同子域之間的跨域
  同主域,不同子域跨域,設定相同的document.domian就可以解決;
父頁訪問子頁,可以document.getElementById("myframe").contentWindow.document來訪問iframe頁面的內容;如果支援contentDocument也可以直接document.getElementById("myframe").contentDocument訪問子頁面內容;
  子頁訪問父頁,可以parent.js全域屬性
二、 是不同主域跨域
  前提,www.a.com下a.html,a.html內iframe調用了www.b.com下的b.html,b.html下iframe調用了www.a.com下的c.html
  b.html是不無法直接存取a.html的對象,因為涉及到跨域,但可以訪問parent,同樣c.html的parent可以訪問b.html。c.html和a.html同域,是可以訪問a下的對象的。parent.parent.js對象!
  看下面執行個體:
  a.html
複製代碼 代碼如下:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>無標題文檔</title>
</head>
<body>
<iframe src="http://www.b.com/b.html" ></iframe>
<ul id="getText"></ul>
<script>
function dosome(text){
document.getElementById("getText").innerHTML= decodeURI(text);
}
</script>
</body>
</html>

b.html
複製代碼 代碼如下:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>無標題文檔</title>
</head>
<body>
<iframe id="myfarme" src="###"></iframe>
<ul id="ct">
<li>這裡是內容1</li>
<li>這裡是內容2</li>
<li>這裡是內容3</li>
<li>這裡是內容4</li>
<li>這裡是內容5</li>
<li>這裡是內容6</li>
</ul>
<script>
window.onload = function(){
var text = document.getElementById('ct').innerHTML;
document.getElementById('myfarme').src="http://www.a.com/c.html?content="+encodeURI(text);
}
</script>
</body>
</html>

c.html
複製代碼 代碼如下:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>無標題文檔</title>
<script>
window.onload = function(){
var text = window.location.href.split('=')[1]
console.log(parent.parent)
parent.parent.dosome(text);
}
</script>
</head>
<body>
ddddddddddd
</body>
</html>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.