2017-06-19 31 views
0

之間的事件我試圖修改一些我有限訪問的網站上的CSS。我被允許在服務器上創建一個頁面,但不能修改網站上的其他PHP生成的頁面。IFRAMES:contentWindow.beforeunload()&onload()

我在探索將CSS注入iframe。我首先隱藏iframe,然後在做出更改後將其顯示出來。

不幸的是,我知道我唯一一次訪問iframe.contentWindow.document的事件發生在iframe.onload()事件發生之後。大部分頁面都是異步加載的,因此在屏幕上觀看內容需要等待3秒鐘,等待所有外部內容加載(包括社交媒體內容)時,等待7-10秒。

onload()之前是否有任何事件發生,我知道我有權訪問新文檔?我只想注入一個stylesheet,我不在乎90%的DOM是否「準備就緒」。

+0

真的,beforeunload是無關緊要因爲這是沒有什麼用的「當前頁」 –

+0

做不知道是否有可能上添加一個'MutationObserver' '如果rame.contentDocument'但這可能是一些可以幫助(等待'head'被添加到DOM,然後做你的事情) –

+0

我知道我剛剛嘗試了每個Iframe相關的事件,我可以找到和onbeforeload,並onload是我見過的工作中唯一的兩個。我懷疑它不可能,但是在我放棄努力之前想確定它。 – Cggart

回答

0

不知道這是否是你後之類的事情 - 但它可以幫助

注:我不一般都喜歡這種類型的代碼,我本來以爲我會用MutationObserver - 但是,我發現我必須做類似上面的事情,等待iframe的contentDocument,以表明內容已經開始加載,然後我可以附加突變觀察者 - 然後我會錯過head元素被一半的時間附加!

火狐對iFrame的mozbrowserloadstart事件 - 不過這只是Firefox的,所以不是所有有用的其他

function limitedRetryWithDelay(count, delay, tester, cb) { 
    var res = tester(); 
    if(res) { 
     cb(res); 
    } else { 
     if (count > 0) { 
      setTimeout(function() { 
       limitedRetryWithDelay(count - 1, delay, tester, cb); 
      }, delay); 
     } 
    } 

} 
// next 3 lines is just how I tested it - you'll need a reference to the iframe node instead for "tgt" 
var tgt = document.createElement('iframe'); 
document.body.appendChild(tgt); 
tgt.src = '/index.html?_=' + Math.random() + '_' + Math.random(); 
// end testing code 

// try every 10ms for 5 seconds because (500 * 10 = 5000ms) 
limitedRetryWithDelay(500, 10, function (e) { 
    return tgt.contentDocument && tgt.contentDocument.location != 'about:blank' && tgt.contentDocument.head; 
}, function(head) { 
    console.log('head is', head); 
}); 

隨時隨地順便說一句,你可能不需要等待head做一些與之前存在文檔,您可能能夠只是等待contentDocument

limitedRetryWithDelay(500, 10, function (e) { 
    return tgt.contentDocument && tgt.contentDocument.location != 'about:blank' && tgt.contentDocument; 
}, function(doc) { 
    console.log('document is', doc); 
}); 
+0

謝謝,我正在測試這個。我也不喜歡超時代碼。你有沒有在生產中看到這種類型的解決方案?我是否擔心在某些情況下部署這個可能會破壞的機會? – Cggart

+0

我不得不在Chrome的生產環境中這樣做 - 因爲由於某種原因,Chrome中的iframe onload事件與Firefox中的行爲不同 - 即在某些情況下它永遠不會觸發 - 不知道現在是否仍然如此,但我不再參與特定的代碼,所以我不在乎:p –