IFRAME로드가 완료되면 Javascript 콜백?
IFRAME로드가 완료되면 콜백을 실행해야합니다. IFRAME의 내용을 제어 할 수 없으므로 콜백을 실행할 수 없습니다.
이 IFRAME은 프로그래밍 방식으로 만들어지며 iframe을 파괴 할뿐만 아니라 콜백에서 변수로 데이터를 전달해야합니다.
어떤 아이디어?
편집하다:
여기 내가 지금 가진 것입니다 :
function xssRequest(url, callback)
{
var iFrameObj = document.createElement('IFRAME');
iFrameObj.src = url;
document.body.appendChild(iFrameObj);
$(iFrameObj).load(function()
{
document.body.removeChild(iFrameObj);
callback(iFrameObj.innerHTML);
});
}
iFrame이로드되기 전에 콜백되므로 콜백에 데이터가 반환되지 않습니다.
먼저 xssRequest 함수 이름으로 크로스 사이트 요청을 시도하는 것처럼 들립니다. 맞으면 iframe의 내용을 읽을 수 없습니다.
반면에 iframe의 URL이 도메인에 있으면 본문에 액세스 할 수 있지만 시간 초과를 사용하여 iframe을 제거하면 콜백이 정상적으로 작동한다는 것을 알았습니다.
// possibly excessive use of jQuery - but I've got a live working example in production
$('#myUniqueID').load(function () {
if (typeof callback == 'function') {
callback($('body', this.contentWindow.document).html());
}
setTimeout(function () {$('#frameId').remove();}, 50);
});
jQuery를 사용하고 있으며 방금 테스트하고 무거운 페이지를로드 할 때 놀랍게도로드되는 것처럼 보이고 iframe로드를 볼 때까지 몇 초 동안 경고가 표시되지 않았습니다.
$('#the_iframe').load(function(){
alert('loaded!');
});
따라서 jQuery를 사용하지 않으려면 소스 코드를 살펴 보고이 함수가 iframe DOM 요소와 다르게 작동하는지 확인하십시오. 나중에 관심을 가지고 여기에 게시 할 때 직접 살펴 보겠습니다. 또한 최신 크롬에서만 테스트했습니다.
iframe 태그가 상위 문서의 내용을 둘러싸 지 않기 때문에 iframe의 innerHTML이 비어 있습니다. iframe의 src 속성이 참조하는 페이지에서 컨텐츠를 가져 오려면 iframe의 contentDocument 속성에 액세스해야합니다. src가 다른 도메인에서 온 경우 예외가 발생합니다. 이는 다른 사람의 페이지에서 임의의 JavaScript를 실행하지 못하게하는 사이트 간 스크립팅 취약점을 발생시키는 보안 기능입니다. 다음은 내가 말하는 것을 보여주는 예제 코드입니다.
<script src="http://prototypejs.org/assets/2009/8/31/prototype.js" type="text/javascript"></script>
<h1>Parent</h1>
<script type="text/javascript">
function on_load(iframe) {
try {
// Displays the first 50 chars in the innerHTML of the
// body of the page that the iframe is showing.
// EDIT 2012-04-17: for wider support, fallback to contentWindow.document
var doc = iframe.contentDocument || iframe.contentWindow.document;
alert(doc.body.innerHTML.substring(0, 50));
} catch (e) {
// This can happen if the src of the iframe is
// on another domain
alert('exception: ' + e);
}
}
</script>
<iframe id="child" src="iframe_content.html" onload="on_load(this)"></iframe>
추가 예제를 보려면 이것을 iframe의 내용으로 사용하십시오.
<h1>Child</h1>
<a href="http://www.google.com/">Google</a>
<p>Use the preceeding link to change the src of the iframe
to see what happens when the src domain is different from
that of the parent page</p>
I have had to do this in cases where documents such as word docs and pdfs were being streamed to the iframe and found a solution that works pretty well. The key is handling the onreadystatechanged
event on the iframe.
Lets say the name of your frame is "myIframe". First somewhere in your code startup (I do it inline any where after the iframe) add something like this to register the event handler:
document.getElementById('myIframe').onreadystatechange = MyIframeReadyStateChanged;
I was not able to use an onreadystatechage attribute on the iframe, I can't remember why, but the app had to work in IE 7 and Safari 3, so that may of been a factor.
Here is an example of a how to get the complete state:
function MyIframeReadyStateChanged()
{
if(document.getElementById('myIframe').readyState == 'complete')
{
// Do your complete stuff here.
}
}
I wanted to hide the waiting spinner div when the i frame content is fully loaded on IE, i tried literally every solution mentioned in Stackoverflow.Com, but with nothing worked as i wanted.
Then i had an idea, that when the i frame content is fully loaded, the $(Window ) load event might be fired. And that exactly what happened. So, i wrote this small script, and worked like magic:
$(window).load(function () {
//alert("Done window ready ");
var lblWait = document.getElementById("lblWait");
if (lblWait != null ) {
lblWait.style.visibility = "false";
document.getElementById("divWait").style.display = "none";
}
});
Hope this helps.
I have a similar code in my projects that works fine. Adapting my code to your function, a solution could be the following:
function xssRequest(url, callback)
{
var iFrameObj = document.createElement('IFRAME');
iFrameObj.id = 'myUniqueID';
document.body.appendChild(iFrameObj);
iFrameObj.src = url;
$(iFrameObj).load(function()
{
callback(window['myUniqueID'].document.body.innerHTML);
document.body.removeChild(iFrameObj);
});
}
Maybe you have an empty innerHTML because (one or both causes): 1. you should use it against the body element 2. you have removed the iframe from the your page DOM
I had a similar problem as you. What I did is that I use something called jQuery. What you then do in the javascript code is this:
$(function(){ //this is regular jQuery code. It waits for the dom to load fully the first time you open the page.
$("#myIframeId").load(function(){
callback($("#myIframeId").html());
$("#myIframeId").remove();
});
});
It seems as you delete you iFrame before you grab the html from it. Now, I do see a problem with that :p
Hope this helps :).
I think the load event is right. What is not right is the way you use to retreive the content from iframe content dom.
What you need is the html of the page loaded in the iframe not the html of the iframe object.
What you have to do is to access the content document with iFrameObj.contentDocument
. This returns the dom of the page loaded inside the iframe, if it is on the same domain of the current page.
I would retreive the content before removing the iframe.
I've tested in firefox and opera.
Then i think you can retreive your data with $(childDom).html()
or $(childDom).find('some selector') ...
I've had exactly the same problem in the past and the only way I found to fix it was to add the callback into the iframe page. Of course that only works when you have control over the iframe content.
Using onload
attrbute will solve your problem.
Here is an example.
function a() {
alert("Your iframe has been loaded");
}
<iframe src="https://stackoverflow.com" onload="a()"></iframe>
Is this what you want?
Click here for more information.
참고URL : https://stackoverflow.com/questions/164085/javascript-callback-when-iframe-is-finished-loading
'IT' 카테고리의 다른 글
Java 웹 애플리케이션에 사용하는 아키텍처를 설명 하시겠습니까? (0) | 2020.06.18 |
---|---|
UIWebView에 표시되는 HTML 페이지의 제목을 얻는 방법? (0) | 2020.06.18 |
Chrome에서 개발자 모드 확장 프로그램 팝업 사용 중지 (0) | 2020.06.18 |
스택 샘플링을 넘어서 : C ++ 프로파일 러 (0) | 2020.06.18 |
Android Studio 및 gradle을 사용하여 Android 라이브러리를 작성하는 방법은 무엇입니까? (0) | 2020.06.18 |