我想使用 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");
更多关于 jQuery
.contents()
方法 和 “如何在 jQuery 中访问 iframe”
我认为你正在做的是受同源政策。这应该是您收到 permission denied type 错误的原因。
.contents()
jQuery 的方法。
如果 iframe 与主页位于同一域中,
方法也可用于获取 iframe 的内容文档。.contents()
$(document).ready(function(){
$('#frameID').load(function(){
$('#frameID').contents().find('body').html('Hey, i`ve changed content of <body>! Yay!!!');
});
});
如果 iframe src 来自另一个域,您仍然可以这样做。您需要将外部页面读入 PHP 并从您的域中回显它。像这样:
<?php
$URL = "http://external.com";
$domain = file_get_contents($URL);
echo $domain;
?>
然后是这样的:
<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 编辑外部页面而不会拒绝访问等的示例...
使用
iframe.contentWindow.document
代替
iframe.contentDocument
我觉得这样更干净:
var $iframe = $("#iframeID").contents();
$iframe.find('selector');
你需要给iframe的onload handler附加一个事件,并在其中执行js,这样你才能确保iframe在访问它之前已经完成加载。
$().ready(function () {
$("#iframeID").ready(function () { //The function below executes once the iframe has finished loading
$('some selector', frames['nameOfMyIframe'].document).doStuff();
});
};
上面会解决'not-yet-loaded'的问题,但是关于权限,如果你在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 中的变量。
$
也是一个变量,您可以访问它的 just 调用
window.iframe_id.$
例如,
window.view.$('div').hide()
- 在 iframe 中隐藏所有 id 为 'view' 的 div
但是,它在 FF 中不起作用。为了更好的兼容性,你应该使用
$('#iframe_id')[0].contentWindow.$
你试过经典的,使用jQuery内置的ready函数等待加载完成吗?
$(document).ready(function() {
$('some selector', frames['nameOfMyIframe'].document).doStuff()
} );
K
我创建了一个示例代码。现在您可以轻松了解您无法访问的不同域 iframe 的内容 .. 我们可以访问 iframe 内容的同一域
我把我的代码分享给你,请运行这段代码 检查控制台。我在控制台打印图像 src。有四个 iframe,两个 iframe 来自同一域,另外两个来自其他域(第三方)。您可以看到两个图像 src(https://www.google.com/logos/doodles/2015/googles-new-徽标-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").contents().find("#someDiv").removeClass("hidden");
这是让它工作的可靠方法:
$(document).ready(function(){
setTimeout(
function () {
$("#iFrame").contents().find("#someDiv").removeClass("hidden");
},
300
);
});
这样脚本将在 300 毫秒后运行,因此它将有足够的时间加载
iFrame
然后代码将开始运行。有时 iFrame
不会加载并且脚本会尝试在它之前执行。 300ms
可以根据您的需要调整为任何其他内容。
为了更加坚固:
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();
...
}
...
我最终在这里寻找不使用 jquery 的 iframe 的内容,所以对于其他寻找它的人来说,就是这样:
document.querySelector('iframe[name=iframename]').contentDocument
此解决方案与 iFrame 的工作原理相同。我已经创建了一个可以从其他网站获取所有内容的 PHP 脚本,最重要的部分是您可以轻松地将自定义 jQuery 应用于该外部内容。请参考以下脚本,可以从其他网站获取所有内容,然后您也可以应用您的自定义 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;
}