jQuery/JavaScript : iframe의 내용에 액세스합니다
-
21-08-2019 - |
문제
jQuery를 사용하여 iframe 내부의 HTML을 조작하고 싶습니다.
나는 jQuery 함수의 컨텍스트를 iframe의 문서로 설정하여 다음과 같은 것들을 만들 수 있다고 생각했습니다.
$(function(){ //document ready
$('some selector', frames['nameOfMyIframe'].document).doStuff()
});
그러나 이것은 작동하지 않는 것 같습니다. 약간의 검사는 변수가 frames['nameOfMyIframe']
~이다 undefined
Iframe이로드되기를 잠시 기다리지 않는 한. 그러나 Iframe이로드되면 변수에 액세스 할 수 없습니다 ( permission denied
-유형 오류).
누구든지 이것에 대한 근로를 아는 사람이 있습니까?
해결책
나는 당신이하는 일이 동일한 원산지 정책. 이것이 당신이 얻는 이유입니다 허가 거부 유형 오류.
다른 팁
만약 <iframe>
동일한 도메인에서 나오고 요소는 다음과 같이 쉽게 액세스 할 수 있습니다.
$("#iFrame").contents().find("#someDiv").removeClass("hidden");
$(document).ready(function(){
$('#frameID').load(function(){
$('#frameID').contents().find('body').html('Hey, i`ve changed content of <body>! Yay!!!');
});
});
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');
사용
iframe.contentWindow.document
대신에
iframe.contentDocument
이벤트를 iframe의 Onload 핸들러에 첨부하고 JS를 실행하여 Iframe이 액세스하기 전에로드를 완료했는지 확인해야합니다.
$().ready(function () {
$("#iframeID").ready(function () { //The function below executes once the iframe has finished loading
$('some selector', frames['nameOfMyIframe'].document).doStuff();
});
};
위의 내용은 '예정되지 않은'문제를 해결하지만 권한과 관련하여 다른 도메인에서 나온 iframe에 페이지를로드하는 경우 보안 제한으로 인해 해당에 액세스 할 수 없습니다.
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의 변수에 액세스 할 수 있습니다.$
변수이기도하며 정당한 전화에 액세스 할 수 있습니다.window.iframe_id.$
예를 들어, window.view.$('div').hide()
- ID 'View'와 함께 iframe에 모든 div를 숨기십시오.
그러나 FF에서는 작동하지 않습니다. 더 나은 호환성을 위해 사용해야합니다
$('#iframe_id')[0].contentWindow.$
JQuery의 내장 준비 기능을 사용하여 하중이 완료되기를 기다리는 클래식을 사용해 보셨습니까?
$(document).ready(function() {
$('some selector', frames['nameOfMyIframe'].document).doStuff()
} );
케이
샘플 코드를 만듭니다. 이제 다른 도메인에서 쉽게 이해할 수 있습니다. iframe의 컨텐츠에 액세스 할 수 없습니다 .. 동일한 도메인 우리는 iframe 컨텐츠에 액세스 할 수 있습니다.
내 코드를 공유합니다.이 코드를 실행하십시오. 콘솔 확인을 확인하십시오. 콘솔에서 이미지 SRC를 인쇄합니다. 4 개의 iframe, 동일한 도메인에서 나오는 2 개의 iframe 및 다른 도메인에서 2 개의 Iframe이 있습니다 (제 3 자). 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) Console에서 두 가지 권한 오류가 표시 될 수 있습니다 (2 오류 : 권한 부동산 '문서'액세스 거부
... irstchild)}, 내용 : 함수 (a) {return m.nodename (a, "iframe")? a.contentDocument ...
) 제 3 자 이브라마에서 온 것입니다.
<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>
나는 여기서 jQuery없이 iframe의 내용을 얻기를 찾고 있었기 때문에 다른 사람에게는 다음과 같습니다.
document.querySelector('iframe[name=iframename]').contentDocument
이 솔루션은 IFRame과 동일하게 작동합니다. 다른 웹 사이트에서 모든 내용을 얻을 수있는 PHP 스크립트를 만들었습니다. 가장 중요한 부분은 해당 외부 콘텐츠에 사용자 정의 jQuery를 쉽게 적용 할 수 있다는 것입니다. 다른 웹 사이트에서 모든 내용을 가져올 수있는 다음 스크립트를 참조하십시오. 그런 다음 Cusom jQuery/JS도 적용 할 수 있습니다. 이 콘텐츠는 요소 또는 페이지 내에서 어디서나 사용할 수 있습니다.
<div id='myframe'>
<?php
/*
Use below function to display final HTML inside this div
*/
//Display Frame
echo displayFrame();
?>
</div>
<?php
/*
Function to display frame from another domain
*/
function displayFrame()
{
$webUrl = 'http://[external-web-domain.com]/';
//Get HTML from the URL
$content = file_get_contents($webUrl);
//Add custom JS to returned HTML content
$customJS = "
<script>
/* Here I am writing a sample jQuery to hide the navigation menu
You can write your own jQuery for this content
*/
//Hide Navigation bar
jQuery(\".navbar.navbar-default\").hide();
</script>";
//Append Custom JS with HTML
$html = $content . $customJS;
//Return customized HTML
return $html;
}
더 많은 견고성을 위해 :
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();
...
}
...