iframe 이로 드 또는 콘텐츠가 있는지 확인하는 방법은 무엇입니까?
id = "myIframe"인 iframe이 여기에 콘텐츠를로드하는 코드가 있습니다.
$('#myIframe').attr("src", "my_url");
문제는 많은 로딩에 너무 오래 걸리고 매우 빨리 빨리 빨리 것입니다. 그래서 "setTimeout"함수를 사용합니다.
setTimeout(function(){
if (//something shows iframe is loaded or has content)
{
//my code
}
else
{
$('#myIframe').attr("src",""); //stop loading content
}
},5000);
내가 알고 싶은 것이 iFrame이 있는지 또는 콘텐츠가 있는지 확인하는 방법입니다. 사용 iframe.contents().find()
이 작동하지 않습니다. 사용할 수 없습니다 iframe.load(function(){})
.
이 시도.
<script>
function checkIframeLoaded() {
// Get a handle to the iframe element
var iframe = document.getElementById('i_frame');
var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
// Check if loading is complete
if ( iframeDoc.readyState == 'complete' ) {
//iframe.contentWindow.alert("Hello");
iframe.contentWindow.onload = function(){
alert("I am loaded");
};
// The loading is complete, call the function we want executed once the iframe is loaded
afterLoading();
return;
}
// If we are here, it is not loaded. Set things up so we check the status again in 100 milliseconds
window.setTimeout(checkIframeLoaded, 100);
}
function afterLoading(){
alert("I am here");
}
</script>
<body onload="checkIframeLoaded();">
친절하게 사용 :
$('#myIframe').on('load', function(){
//your code (will be called once iframe is done loading)
});
표준이 변경됨에 따라 내 대답을 업데이트했습니다.
가장 쉬운 옵션 :
<script type="text/javascript">
function frameload(){
alert("iframe loaded")
}
</script>
<iframe onload="frameload()" src=...>
나는 동일한 문제가 있지만 추가하여 교차 도메인 정책에 관계없이 iframe이로드되었는지 확인해야합니다. 웹 페이지에 특정 부분을 삽입하고 상위 페이지의 일부 콘텐츠를 iframe에 표시하는 크롬 확장 프로그램을 개발하고 있습니다. 나는 다음 접근 방식을 시도합니다. 나를 위해 완벽하게 작동했습니다.
추신 : 제 경우에는 iframe의 콘텐츠를 제어 할 수 없습니다. (Iframe은 내 서버에서 호스팅됩니다.)
첫째 : 속성이
있는 iframe을 다음과data-
같이 만듭니다 (이 부분은 내 경우 삽입 된 펼쳐져 있음).
<iframe id="myiframe" src="http://anyurl.com" data-isloaded="0"></iframe>
이제 iframe 코드에서 다음을 사용합니다.
var sourceURL = document.referrer;
window.parent.postMessage('1',sourceURL);
이제 내 경우에 따라 삽입 된 전개로 돌아갑니다.
setTimeout(function(){
var myIframe = document.getElementById('myiframe');
var isLoaded = myIframe.prop('data-isloaded');
if(isLoaded != '1')
{
console.log('iframe failed to load');
} else {
console.log('iframe loaded');
}
},3000);
과,
window.addEventListener("message", receiveMessage, false);
function receiveMessage(event)
{
if(event.origin !== 'https://someWebsite.com') //check origin of message for security reasons
{
console.log('URL issues');
return;
}
else {
var myMsg = event.data;
if(myMsg == '1'){
//8-12-18 changed from 'data-isload' to 'data-isloaded
$("#myiframe").prop('data-isloaded', '1');
}
}
}
질문에 대답하지 않을 수도 있습니다.
로드되었는지 여부를 감지 할 수 있는지 확실하지 않지만로드가 완료되면 이벤트를 실행할 수 있습니다.
$(function(){
$('#myIframe').ready(function(){
//your code (will be called once iframe is done loading)
});
});
편집 : Jesse Hallett이 지적했듯이 iframe
이미로드 된 경우에도로드 되면 항상 실행됩니다 . 따라서 기본적으로 iframe
가 이미로드 된 경우 콜백이 즉시 실행됩니다.
iframe의 load
이벤트를 사용하여 iframe이로드 될 때 응답 할 수 있습니다 .
document.querySelector('iframe').onload = function(){
console.log('iframe loaded');
};
이것은 올바른 콘텐츠가로드되었는지 여부를 알려주지 않습니다.이를 확인하려면 contentDocument
.
document.querySelector('iframe').onload = function(){
var iframeBody = this.contentDocument.body;
console.log('iframe loaded, body is: ', body);
};
contentDocument
iframe이src
코드가 실행중인 도메인과 다른 도메인을 가리키는 경우 확인이 작동하지 않습니다 .
제 경우에는 교차 출처 프레임이었고 가끔로드되지 않았습니다. 나를 위해 일한 해결책은 다음과 같습니다. 성공적으로로드되면이 코드를 시도하면 :
var iframe = document.getElementsByTagName('iframe')[0];
console.log(iframe.contentDocument);
contentDocument
교차 출처 오류 에 액세스 하고 던지는 것을 허용하지 않지만 프레임이 성공적으로로드되지 않으면 객체 contentDocument
를 반환 #document
합니다.
iFrame이로드 될 때 처음에는 #document가 포함되므로로드 상태를 확인하는 것이 가장 효과적 일 수 있습니다.
if ($('iframe').contents().find('body').children().length > 0) {
// is loaded
} else {
// is not loaded
}
iframe을 조작 할 준비가 된시기를 알아야하는 경우 간격을 사용하십시오. 이 경우 I "핑 (ping)"내용 모든 250 MS와이 있다면 어떤 대상은 iframe 내부의 내용은 "핑 (ping)"을 중단하고 뭔가를이.
var checkIframeLoadedInterval = setInterval( checkIframeLoaded, 250 );
function checkIframeLoaded() {
var iframe_content = $('iframe').contents();
if (iframe_content.length > 0) {
clearInterval(checkIframeLoadedInterval);
//Apply styles to the button
setTimeout(function () {
//Do something inside the iframe
iframe_content.find("body .whatever").css("background-color", "red");
}, 100); //100 ms of grace time
}
}
정말 좋은 방법은 jQuery AJAX를 사용하는 것입니다. 상위 프레임은 다음과 같습니다.
<iframe src="iframe_load.php" style="width: 100%; height: 100%;"></iframe>
iframe_load.php 파일은 AJAX GET에서 대상 URL을로드하려고 시도하는 jQuery 라이브러리와 JavaScript를로드합니다.
var the_url_to_load = "http://www.your-website.com" ;
$.ajax({
type: "GET",
url: the_url_to_load,
data: "",
success: function(data){
// if can load inside iframe, load the URL
location.href = the_url_to_load ;
},
statusCode: {
500: function() {
alert( 'site has errors' ) ;
}
},
error:function (xhr, ajaxOptions, thrownError){
// if x-frame-options, site is down or web server is down
alert( 'URL did not load due to x-frame-options' ) ;
} });
중요 대상에는 "Access-Control-Allow-Origin"헤더가 있어야합니다. PHP의 예 :
HEADER( "Access-Control-Allow-Origin: *" ) ;
참고 URL : https://stackoverflow.com/questions/9249680/how-to-check-if-iframe-is-loaded-or-it-has-a-content
'ProgramingTip' 카테고리의 다른 글
AsyncTask는 활동이 파괴 된 경우에도 중지되지 않습니다. (0) | 2020.11.07 |
---|---|
두 날짜의 차이 (초) (0) | 2020.11.07 |
AngularJS 컨트롤러에 변수 전달, 모범 사례? (0) | 2020.11.07 |
navigateUpFromSameTask ()를 사용하여 활동에서 복귀 (0) | 2020.11.07 |
테이블 열 크기 조정 (0) | 2020.11.07 |