如果你想動態創建一個iframe


如果你想動態的在頁面創建一個iframe,並且取得iframe的document,和 window.

並且在iframe中插入一個script標簽。

//我嘗試了各種創建方法,比較難搞定的是 ie8 和 window,IOS 下firefox標簽不太一樣。

//一個兼容的辦法大約是這樣。

var iframe = document.createElement('iframe');
var iframedocument;
var iframeWindow;
document.body.appendChild(iframe);


if(iframe.document){ //ie 8 chrome opera Safari (windows)

    iframedocument = iframe.document;//contentWindow.document;
    iframeWindow = iframe.contentWindow;
    var script = iframedocument.createElement('script');
    script.src = "/common_info/js/mx.im.inPoll.js";
    iframedocument.getElementsByTagName('head')[0].appendChild(script);

}else{
    // chrome opera Safari firefox (windows and os)
    iframedocument =  iframe.contentDocument;//contentWindow.document;
    iframeWindow = iframe.contentWindow;
    iframedocument.open();
    iframedocument.write('<html><head><title>im in_poll</title><script type="text/javascript" src="common_info/js/mx.im.inPoll.js"></script></head><body></body></html>');
    iframedocument.close();
}

記錄下,代碼並沒有做整理。

你可能遇到的錯誤:

IE8 在獲取 iframe.contextDocument的時候報錯“沒有訪問權限”(尼瑪,實在不知道是怎么回事,在本機用IP測試OK,可能跟 iframe.readyState 有關系,嘗試setInterval 獲取依然失敗)。

你可能嘗試使用iframe.onload 中執行一些代碼,但是IE8宣告不會觸發這個事件。不知是不是沒有設置 src的問題。(我的實例中不需要src,故沒有設置)

firefox 在 windows 和 IOS中的表現不太一樣。 實際是 else 中的代碼 幾乎可以平穩運行90%瀏覽器,if塊中針對下IE。

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM