今天android加載html的時候遇到沒法滾動顯示完整內容的問題,確認沒有disable scroll方法,經查證是屬於iframe設置高度形成的,加載外部html的時候,由於安全策略沒法訪問到iframe的contentDocument,形成高度不正確。報錯:Uncaught SecurityError: Failed to read the 'contentDocument' property from 'HTMLIFrameElement': Blocked a frame with originnull from accessing a frame with origi nulljavascript
chrome 會限制protocol,cross domain等等,我遇到的就是local html file 的路徑問題,雖然是同一個文件夾裏的內容。html
解決方法就是postmessage,利用event來通訊傳遞自身的高度過去。java
這裏通配了domain,注意安全性的話,須要post domain and check it at message handler.android
parent :chrome
<script type="text/javascript"> // browser compatibility: get method for event // addEventListener(FF, Webkit, Opera, IE9+) and attachEvent(IE5-8) var myEventMethod = window.addEventListener ? "addEventListener" : "attachEvent"; // create event listener var myEventListener = window[myEventMethod]; // browser compatibility: attach event uses onmessage var myEventMessage = myEventMethod == "attachEvent" ? "onmessage" : "message"; // register callback function on incoming message myEventListener(myEventMessage, function (e) { // we will get a string (better browser support) and validate // if it is an int - set the height of the iframe #my-iframe-id if (e.data === parseInt(e.data)) document.getElementById('my-iframe-id').height = e.data + "px"; }, false); </script>
child安全
<script type="text/javascript"> // all content including images has been loaded window.onload = function() { // post our message to the parent window.parent.postMessage( // get height of the content document.body.scrollHeight // set target domain ,"*" ) }; </script>