接着昨天的工作 如何根據iframe內嵌頁面調整iframe高寬 來說,按照文章中說的第二種方法實現代碼如下:
實現
A.com/detail/view 頁面的iframe代碼如下:
<iframe id="thirdiframe" src="http://B.com/location/testiframe" width="100%" scrolling="no" frameborder="0" height="900"></iframe>
B.com是第三方的域名,所以要求在B.com/location/testiframe的頁面增加下面的html
<iframe id="aiframe" src="#" style="display:none"></iframe> <script type="text/javascript">this.document.getElementById("aiframe").src="http://A.com/detail/iframe?height=" + window.innerHeight;</script> A.com/deatil/iframe是A提供的動態接口,返回的數據是一段js:
<script type="text/javascript">parent.parent.document.getElementById("thirdiframe").style.height="20px";</script>
這段中的20px是根據參數來生成的
基本這樣就可以了。但是在同事的提醒下,考慮到后面幾個問題:
1 動態接口的安全問題
A.com/detail/iframe?height=20
會返回一段js,而這里返回的js是帶傳入參數的。所以這里很有可能會出現反射型XSS。
所以在安全性上要注意一下,需要對height參數進行驗證,比如使用php的intval這個函數來一勞永逸。
2 讓B這個第三方嵌入一套html代碼好嗎?
這里不討論B是否允許嵌入的商務問題。即使B允許嵌入了,但是以后萬一想修改這個代碼,還需要去讓B來修改。
實際上讓B嵌入一個A域名的js
<script type="text/javascript" src="http://A.com/detail/iframejs"></script>
這個js:http://A.com/detail/iframejs 是A提供的一個js,它受A(我方)控制,所以,這個邏輯就可以由A方進行控制了
這個js返回的內容如下:
function initA() { var iframeA = document.createElement('iframe'); iframeA.src='http://A.com/detail/iframe?height=' + window.innerHeight; iframeA.style.display='none'; iframeA.id='iframeA'; document.body.appendChild(iframeA); } function updateAHeight(height) { if (document.getElementById('iframeA') == null) { init360(); } var iframeA = document.getElementById('iframeA'); iframeA.src='http://A.com/detail/iframe?height=' + height; } if (window.addEventListener) { window.addEventListener('load', initA, false); } else { window.attachEvent('onload', initA); }
對上面的一段代碼,注意幾點:
a 當頁面加載完成之后再執行initA事件,需要使用addEventListener和attachEvent函數,不應該直接把document.onload來執行,因為B的頁面本身可能會有綁定其他事件。
b addEventListener是firefox,chrome等使用的事件加綁定的函數,而attachEvent是IE使用的事件加綁定事件,所以需要分開來做。
c 這里為什么提供一個updateAHeight函數呢?因為有可能B的頁面高度會進行變化,那么當B的頁面高度變化的時候有沒辦法改變A的iframe的高度呢?
有兩種方法:
c.1 B在改變頁面高度的事件上調用一個函數,來修改B頁面的iframe的src,其中,這里的updateAHeight就是這個用處的
c.2 做循環,循環體內就是將當前頁面的高度設置值,傳遞給iframe,這個循環當然可以給http://A.com/detail/iframejs 這個js來做的。
總結
原本以為很簡單的一個事情,整一整還可以整出這么多名堂,話說也好久沒寫js了。。。代碼啥的,都是技術熟練活啊。。。