same-origin-policy 크롬 contentwindow - jQuery / JavaScript : iframe의 내용에 접근하기
<iframe>
이 같은 도메인에서 온 경우 요소는 다음과 같이 쉽게 액세스 할 수 있습니다.
$("#iFrame").contents().find("#someDiv").removeClass("hidden");
jQuery를 사용하여 iframe 내부의 HTML을 조작하고 싶습니다.
jQuery 함수의 컨텍스트를 iframe의 문서로 설정하여이 작업을 수행 할 수있을 것이라고 생각했습니다.
$(function(){ //document ready
$('some selector', frames['nameOfMyIframe'].document).doStuff()
});
그러나 이것은 작동하지 않는 것 같습니다. iframe을로드하는 동안 잠시 기다리지 않으면 frames['nameOfMyIframe']
의 변수가 undefined
않은 것으로 나타납니다. 그러나 iframe이로드 될 때 변수에 액세스 할 수 없습니다 ( permission denied
형식 오류가 발생합니다).
누구든지 이것에 대한 해결 방법을 알고 있습니까?
iframe src가 다른 도메인의 것이라면 여전히 할 수 있습니다. 외부 페이지를 PHP로 읽고 도메인에서 에코해야합니다. 이렇게 :
iframe_page.php
<?php
$URL = "http://external.com"
$domain = file_get_contents($URL)
echo $domain
?>
다음과 같은 뭔가 :
display_page.html
<html>
<head>
<title>Test</title>
</head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
cleanit = setInterval ( "cleaning()", 500 );
});
function cleaning(){
if($('#frametest').contents().find('.selector').html() == "somthing"){
clearInterval(cleanit);
$('#selector').contents().find('.Link').html('ideate tech');
}
}
</script>
<body>
<iframe name="frametest" id="frametest" src="http://yourdomain.com/iframe_page.php" ></iframe>
</body>
</html>
위의 예는 액세스가 거부 된 등 iframe을 통해 외부 페이지를 편집하는 방법입니다.
나는이 방법을 깨끗하게 찾는다.
var $iframe = $("#iframeID").contents();
$iframe.find('selector');
window.postMessage를 사용하여 페이지와 iframe 사이의 함수를 호출 할 수 있습니다 (교차 도메인인지 여부).
page.html
<!DOCTYPE html>
<html>
<head>
<title>Page with an iframe</title>
<meta charset="UTF-8" />
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
var Page = {
id:'page',
variable:'This is the page.'
};
$(window).on('message', function(e) {
var event = e.originalEvent;
if(window.console) {
console.log(event);
}
alert(event.origin + '\n' + event.data);
});
function iframeReady(iframe) {
if(iframe.contentWindow.postMessage) {
iframe.contentWindow.postMessage('Hello ' + Page.id, '*');
}
}
</script>
</head>
<body>
<h1>Page with an iframe</h1>
<iframe src="iframe.html" onload="iframeReady(this);"></iframe>
</body>
</html>
iframe.html
<!DOCTYPE html>
<html>
<head>
<title>iframe</title>
<meta charset="UTF-8" />
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
var Page = {
id:'iframe',
variable:'The iframe.'
};
$(window).on('message', function(e) {
var event = e.originalEvent;
if(window.console) {
console.log(event);
}
alert(event.origin + '\n' + event.data);
});
$(window).on('load', function() {
if(window.parent.postMessage) {
window.parent.postMessage('Hello ' + Page.id, '*');
}
});
</script>
</head>
<body>
<h1>iframe</h1>
<p>It's the iframe.</p>
</body>
</html>
나는 샘플 코드를 만든다. 이제 iframe의 콘텐츠에 액세스 할 수없는 다른 도메인에서 쉽게 이해할 수 있습니다. iframe 콘텐츠에 액세스 할 수있는 동일한 도메인
내 코드를 공유합니다.이 코드를 실행하여 콘솔을 확인하십시오. 콘솔에서 이미지 src를 출력합니다. 4 개의 iframe, 2 개의 iframe이 동일한 도메인에서 나오고 다른 2 개의 iframe이 다른 도메인 (제 3 자)에서 있습니다 .2 개의 이미지 src ( https://www.google.com/logos/doodles/2015/googles-new-logo-5078286822539264.3-hp2x.gif )를 볼 수 있습니다. https://www.google.com/logos/doodles/2015/googles-new-logo-5078286822539264.3-hp2x.gif
과
https://www.google.com/logos/doodles/2015/arbor-day-2015-brazil-5154560611975168-hp2x.gif ) 콘솔에서 볼 수 있으며 두 개의 권한 오류가 표시 될 수 있습니다 (2 오류 : 권한이 속성의 문서에 액세스하는 것을 거부했습니다.) '
... irstChild)}, 내용 : 함수 (a) {반환 m.nodeName (a, "iframe")? a.contentDocument ...
)를 제공합니다.
<body id="page-top" data-spy="scroll" data-target=".navbar-fixed-top">
<p>iframe from same domain</p>
<iframe frameborder="0" scrolling="no" width="500" height="500"
src="iframe.html" name="imgbox" class="iView">
</iframe>
<p>iframe from same domain</p>
<iframe frameborder="0" scrolling="no" width="500" height="500"
src="iframe2.html" name="imgbox" class="iView1">
</iframe>
<p>iframe from different domain</p>
<iframe frameborder="0" scrolling="no" width="500" height="500"
src="https://www.google.com/logos/doodles/2015/googles-new-logo-5078286822539264.3-hp2x.gif" name="imgbox" class="iView2">
</iframe>
<p>iframe from different domain</p>
<iframe frameborder="0" scrolling="no" width="500" height="500"
src="http://d1rmo5dfr7fx8e.cloudfront.net/" name="imgbox" class="iView3">
</iframe>
<script type='text/javascript'>
$(document).ready(function(){
setTimeout(function(){
var src = $('.iView').contents().find(".shrinkToFit").attr('src');
console.log(src);
}, 2000);
setTimeout(function(){
var src = $('.iView1').contents().find(".shrinkToFit").attr('src');
console.log(src);
}, 3000);
setTimeout(function(){
var src = $('.iView2').contents().find(".shrinkToFit").attr('src');
console.log(src);
}, 3000);
setTimeout(function(){
var src = $('.iView3').contents().find("img").attr('src');
console.log(src);
}, 3000);
})
</script>
</body>
더욱 견고하게하기 위해서 :
function getIframeWindow(iframe_object) {
var doc;
if (iframe_object.contentWindow) {
return iframe_object.contentWindow;
}
if (iframe_object.window) {
return iframe_object.window;
}
if (!doc && iframe_object.contentDocument) {
doc = iframe_object.contentDocument;
}
if (!doc && iframe_object.document) {
doc = iframe_object.document;
}
if (doc && doc.defaultView) {
return doc.defaultView;
}
if (doc && doc.parentWindow) {
return doc.parentWindow;
}
return undefined;
}
과
...
var frame_win = getIframeWindow( frames['nameOfMyIframe'] );
if (frame_win) {
$(frame_win.contentDocument || frame_win.document).find('some selector').doStuff();
...
}
...