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
- 类型错误)。
有谁知道解决这个问题的方法吗?
解决方案
我觉得你在做什么是受同源策略。这应该是为什么你所得到的原因的许可被拒绝类型的错误。
其他提示
$(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()
- 隐藏所有div在ID为 '视图' 的iframe
但是,它并不在FF工作。为了更好的兼容性,应使用
$('#iframe_id')[0].contentWindow.$
您是否尝试过的经典,等待加载使用jQuery的内置功能齐全,完成?
$(document).ready(function() {
$('some selector', frames['nameOfMyIframe'].document).doStuff()
} );
ķ
我创建了一个示例代码。现在,您可以轻松地从不同的域中理解您无法访问iframe的内容。我们可以访问 iframe 内容的同一域
我分享您的代码,请运行此代码检查控制台。我在控制台打印图像 src。有四个 iframe ,两个 iframe 来自同一域,另外两个来自其他域(第三方)。您可以看到两个图像 src( 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)},contents:function(a){return m.nodeName(a,"iframe")?a.contentDocument...
) 来自第三方 iframe。
<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>
我在这里结束了找得到的iframe不jQuery的内容,所以对任何人寻找的是,它仅仅是这样的:
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();
...
}
...