동적 인 iframe이있는 페이지가 있습니다. iframe이로드 될 때 window.print()가 호출되어야합니다 (예 : src가 있음).페이지의 모든 iframe에 src가 있는지 검색합니다.
어떻게 페타 틱하지 않고도 순수한 JavaScript에서 우아하게 처리 할 수 있습니까?
동적 인 iframe이있는 페이지가 있습니다. iframe이로드 될 때 window.print()가 호출되어야합니다 (예 : src가 있음).페이지의 모든 iframe에 src가 있는지 검색합니다.
어떻게 페타 틱하지 않고도 순수한 JavaScript에서 우아하게 처리 할 수 있습니까?
function getLoadedFrames() {
var frames = document.getElementsByTagName('iframe'), // Get all iframes
loadedFrames = [], i;
for (i = 0; i < frames.length; i++) {
/*
If iframe has a src attribute, that attribute has a value AND
that value is not equal to the current window location (leaving src
blank seems to return the current location instead of empty string)
then add the frame to the loadedFrames array.
*/
if (frames[ i ].src && frames[ i ].src.length > 0 && frames[ i ].src !== window.location.href) {
loadedFrames.push(frames[ i ]);
}
}
return loadedFrames; // An array of your 'loaded' frames
}
당신은 이상의 모든 iframe을 반복하고 그들 모두가 정의 src
이 있는지 여부에 true 또는 false를 반환합니다
function areAllIframesLoaded() {
var frames = document.getElementsByTagName('iframe')
return Array.prototype.slice.call(frames).reduce(function(p, c) {
return p && c.src && c.src.length > 0 && c.src !== window.location.href
}, true);
}
이 작업을 수행 할 수 있습니다. 만약 당신이 원하는, 그러나 아마 도움이된다면
frames.reduce returns Fx 15의 오류? "오류 : TypeError : frames.reduce가 함수가 아닙니다." –
분명히 아니지만 Firefox 15.0.1입니다. –
Durr, 먼저 Array.prototype.slice를 사용해야했습니다. 업데이트 된 솔루션 – saml
아주 확실하지 않음 :이 src
속성을 확인하지 않고 작동
window.addEventListener("DOMContentLoaded", function(){
// Get all iframes as soon as DOM has loaded
var iframes = document.getElementsByTagName("iframe");
for (var i = 0, l = iframes.length; i < l; ++i) {
// Add event handler to every iframe
iframes[i].onload = function(){
// Execute window.print() when iframe has loaded
window.print();
};
}
});
하는 iframe
가 src
이없는 경우 때문에 onload
이벤트가 없을 것 해고 됐어.
IE에서는 작동하지 않습니다. this answer을 (를) 다음과 같이하면 jQuery의 $(document).ready
과 같습니다.
iframe을 모두 제어 할 수 있습니까? 아니면 그들 중 일부는 당신이 통제하지 않는 다른 도메인입니까? – jfriend00
그것은 외부로부터 왔으며 제 통제하에 있지 않습니다. – PHearst