開始接觸前端的時候,搜索iframe出來的是iframe耗能,不安全等,以致於並無去正式瞭解,想來也確實是太不夠嚴謹。如今在業務中有須要用到iframe來實現一些特定的需求,因此以爲頗有必要去了解一下,查了一些資料進行整理。javascript
<!--這個是最一般的使用,還能夠設置不少的屬性值的-->
<iframe src="http://m.haimati.cn"></iframe>
複製代碼
經常使用屬性,會在下文中作一些介紹css
那什麼是同域/ 什麼是跨域呢?html
就是判斷你的url首部是否同樣,例如:前端
A:<iframe id="mainIframe" name="mainIframe" src="/main.html" frameborder="0" scrolling="auto" ></iframe>
B:<iframe id="mainIframe" name="mainIframe" src="http://www.baidu.com" frameborder="0" scrolling="auto" ></iframe>
複製代碼
使用A時,由於同域,父頁面能夠對子頁面進行改寫,反之亦然。 使用B時,不一樣域,父頁面沒有權限改動子頁面,但能夠實現頁面的跳轉 這裏,咱們先從簡單的開始,當主頁面和iframe同域時,咱們能夠作些什麼。java
var iframe = document.getElementById("iframe1");
var iwindow = iframe.contentWindow;
var idoc = iwindow.document;
console.log("window",iwindow);//獲取iframe的window對象
console.log("document",idoc); //獲取iframe的document
console.log("html",idoc.documentElement);//獲取iframe的html
console.log("head",idoc.head); //獲取head
console.log("body",idoc.body); //獲取body
複製代碼
另一種簡單的方法是根據name來獲取web
<iframe src ="/index.html" id="ifr1" name="ifr1" scrolling="yes">
<p>Your browser does not support iframes.</p>
</iframe>
<script type="text/javascript">
console.log(window.frames['ifr1'].window);
console.dir(document.getElementById("ifr1").contentWindow);
</script>
複製代碼
同理,在同域下,父頁面能夠獲取子iframe的內容,那麼子iframe一樣也能操做父頁面內容。在iframe中,能夠經過在window上掛載的幾個API進行獲取. 獲取了以後,咱們就能夠進行相關操做了。ajax
話說在好久好久之前,咱們實現異步發送請求是使用iframe實現的~! 那時候爲了避免跳轉頁面,提交表單時是使用iframe提交的。如今,前端發展很快,websocket,SSE,ajax等的出現,顛覆了iframe, 如今基本上只能活在IE8,9的瀏覽器內了。跨域
若是寫過ajax的童鞋,應該知道,長輪詢就是在ajax的readyState = 4的時,再次執行原函數便可。 這裏使用iframe也是同樣,異步建立iframe,而後reload, 和後臺協商好, 看後臺哥哥們將返回的信息放在,而後獲取裏面信息便可. 這裏是直接放在body裏.瀏覽器
var iframeCon = docuemnt.querySelector('#container'),
text; //傳遞的信息
var iframe = document.createElement('iframe'),
iframe.id = "frame",
iframe.style = "display:none;",
iframe.name="polling",
iframe.src="target.html";
iframeCon.appendChild(iframe);
iframe.onload= function(){
var iloc = iframe.contentWindow.location,
idoc = iframe.contentDocument;
setTimeout(function(){
text = idoc.getElementsByTagName('body')[0].textContent;
console.log(text);
iloc.reload(); //刷新頁面,再次獲取信息,而且會觸發onload函數
},2000);
}
複製代碼
還有一些應用還有待去結合業務場景敲實例,未完待續···安全