I currently have a working webpage that has a list of links that open in a targeted iFrame. I would like to add a subsequent iFrame target and be able to open supplementary pages in that iFrame as well as the original iFrame with the same link.
From my research, it seems this should be possible with some JS but I'm struggling to figure it out.
So basically, how could I click on "Lot 1" and open up a Youtube in the "gallery" iFrame and, say, www.example.com in the "info" iFrame simultaneously?
<iframe src="" name="gallery"</iframe>
<iframe src="" name="info"</iframe>
Lot 1
Lot 2
You can have an array/object storing the links, and then run an onclick event that will change the corresponding iframe sources to the values from said array (iframes have a src attribute which you can change through JS).
For example:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var frm = ['gallery', 'info'];
var hrf = ['http://example.com/', 'http://example.net/'];
function setSource() {
for(i=0, l=frm.length; i<l; i++) {
document.querySelector('iframe[name="'+frm[i]+'"]').src = hrf[i];
}
}
</script>
</head>
<body>
<iframe src="" name="gallery"></iframe>
<iframe src="" name="info"></iframe>
<span onclick="javascript: setSource();">Click me</span>
</body>
</html>
If you'd like to have multiple span elements, each changing the iframes' sources to a different set of links, you can always use a multidimensional array (an array of arrays) for src and add a parameter to the function:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var frm = ['gallery', 'info'];
var hrf = [['http://example0.com/', 'http://example0.net/'], ['http://example1.com/', 'http://example1.net/']];
function setSource(num) {
for(i=0, l=frm.length; i<l; i++) {
document.querySelector('iframe[name="'+frm[i]+'"]').src = hrf[num][i];
}
}
</script>
</head>
<body>
<iframe src="" name="gallery"></iframe>
<iframe src="" name="info"></iframe>
<span onclick="javascript: setSource(0);">Click me #0</span>
<span onclick="javascript: setSource(1);">Click me #1</span>
</body>
</html>
Here hrf is an array that contains another array (['http://example0.com/', 'http://example0.net/']) at index 0 and yet another one (['http://example1.com/', 'http://example1.net/']) - at index 1. By passing a parameter to setSource we can choose what subarray we want to pick to get the sources from.
Please don't forget to close your tags.
Using the a tag for your purpose is not a good idea, I recommend using a span. The a tag's purpose is to link the user to another document, not run javascript code (not using a also means you don't have to use preventDefault).
The javascript: prefix is used for the onclick attribute to provide backwards compatibility for some older mobile browsers.
This code works simply great :
<!DOCTYPE html>
<html>
<body>
<h1 style="display:flex;
justify-content:center;color:green;">
GeeksforGeeks
</h1>
<iframe src="about:blank" id="frame1"> </iframe>
<iframe src="about:blank" id="frame2"> </iframe>
<button id="update">Click me</button>
<script>
document.getElementById('update').addEventListener('click', function () {
// Change src attribute of iframes at a same time
document.getElementById('frame1').src ='https://www.google.com/search?q=java&igu=1';
document.getElementById('frame2').src ='https://www.google.com/search?q=farming&igu=1';
});
</script>
</body>
</html>
Related
I need to find a specific element, which is inside an iframe, from a parent component, the structure would be something like this: (Just an example)
Edit: See comments below concerning the nature of this example
<iframe id ='if1'>
<iframe id ='if2'>
<iframe id ='if3'>
<iframe id ='if4'>
<input type='hidden' id ='elementToBeFound'>
</iframe>
</iframe>
</iframe>
</iframe>
Now, how can i do this with javascript? (Can also be jquery or another helper)
I have a reference to the first iframe ('if1'), i wanted to search all child nodes until i found 'elementToBeFound'.
Is this possible?
Thanks in advance.
My question is different from the existing ones, because i want to access multiple iframes inside iframes, not only one level.
I belive that something like this should work:
const elem = document.getElementById('if1').contentDocument
.getElementById('if2').contentDocument
.getElementById('if3').contentDocument
.getElementById('if4').contentDocument
.getElementById('elementToBeFound')
But for sure all windows should be loaded to do that. In real workld it may be more complicated you will need to listen for load event for each iframe to be able to check what is inside.
You can use this function to query for any element on the page, regardless of if it is nested inside of an iframe:
function querySelectorAllInIframes(selector) {
let elements = [];
const recurse = (contentWindow = window) => {
const iframes = contentWindow.document.body.querySelectorAll('iframe');
iframes.forEach(iframe => recurse(iframe.contentWindow));
elements = elements.concat(contentWindow.document.body.querySelectorAll(selector));
}
recurse();
return elements;
};
querySelectorAllInIframes('#elementToBeFound');
Note: Keep in mind that each of the iframes on the page will need to be of the same-origin, or this function will throw an error.
You can get the div element by using iframe.contentWindow call.
Here is the example:
NOTE : You have to use "src" (external iframes) to make it work
<!DOCTYPE html>
<html>
<head>
<title>IF1</title>
</head>
<body>
<iframe id='if1' src="./iframe2.html">
<!-- <iframe id='if2'>
<iframe id='if3'>
<iframe id='if4'> -->
<!-- <div id='elementToFind'>Hello</div> -->
<!-- </iframe>
</iframe>
</iframe> -->
</iframe>
<script>
window.onload = function() {
let if1 = document.getElementById('if1').contentWindow;
let if2 = if1.document.getElementById('if2').contentWindow;
let div = if2.document.getElementById('elementToFind');
console.log(div)
}
</script>
</body>
</html>
I am using a hosted CMS that renders an iFrame within another iFrames. These iFrames are loaded from the same domain but since this is a hosted CMS I do not have access to these iFrames directly. Is it possible, using jQuery, to insert HTML content into the body tag of the iFrame with the id of re_contentIframe?
Here is how the code renders on my site:
<div class="editor">
<iframe id="editorf" frameborder="0" src="/ForumEditor.aspx?ForumID=2221&TopicID=-1&NoTemplate=False&Internal=False" style="display: inline;">
<html>
<head></head>
<body>
<!-- CODE -->
<iframe id="re_contentIframe" frameborder="0" src="javascript:'<html></html>';">
<html>
<head></head>
<body> <!-- THIS IS WHAT I WANT TO TARGET --> </body>
</html>
</iframe>
<!-- CODE -->
</body>
</html>
</iframe>
</div>
I tried using the following code but nothing happens with this code (including no errors):
$(function() {
$( "#test" ).click(function() {
$("#re_contentIframe").contents().find("body").html("<p>new HTML content goes here</p>");
});
});
The problem is that you are trying to access a nested frame.
The #re_contentIframe frame is nested within #editorf, which is subsequently nested within your document.
Try:
$('#re_contentIframe').contents().find('body').find('#editorf').contents()
Fiddle: http://jsfiddle.net/8VP4y/3/
haven't checked it ,might help :
var frameObject = document.getElementById('editorf');
var frameContent = frameObject.contentDocument ||
frameObject.contentWindow.document;
var insideIframe = frameContent.getElementById('re_contentIframe');
var insideIframeContent = insideIframeObject.contentDocument ||
insideIframeObject.contentWindow.document;
var $body = $('body',insideIframeContent);
$body.html('<div>contentupdated</div>');
<html>
<head>
<script language="javascript">
var var1 = "<html><body>Content1</body></html>"
var2 = "<html><body>Content2</body></html>"
function doublelink([arg]){
top.iframe2.location="javascript:parent.var1";
}
</script>
</head>
<body>
<a href="source1" target="iframe1" onClick="doublelink([arg1])";>Link 1</a><p>
<a href="source1" target="iframe1" onClick="doublelink([arg2])";>Link 2</a><p>
<iframe src="source" name="iframe1"></iframe>
<iframe src="source" name="iframe2"></iframe>
</body>
</html>
I was seeking for method to create links that update multiple frames at a time and found the code above. Without defining argument for the function "doublelink", clicking "Link 1" will put "source1" to "iframe1" and the html in "var1" to "iframe2", and clicking "Link 2" will lead to the same result. Now I want to add an argument, which is related to "javascript:parent.var1" somehow, so that clicking "Link 1" will get "iframe2" filled with "Content1" and clicking "Link2" will put "content2" to the same "iframe2".
There are two ways to get the same outcome:
Create another two html files instead of storing them in "var1" and "var2" and give argument relating to their names.
Create another "doublelink" function.
Method 2 is not optimal, since 100 functions are needed if there are 100 links. Method 1 is normal, but I'm just curious, is there a method to get it done the way I mentioned above? Thank you.
Try something like this:
<html>
<head>
<script>
var var1 = "<html><body>Content1</body></html>",
var2 = "<html><body>Content2</body></html>";
function doublelink(i) {
top.iframe2.location = "javascript:parent.var" + i;
}
</script>
</head>
<body>
Link 1<br>
Link 2<br>
<iframe src="" name="iframe1"></iframe>
<iframe src="" name="iframe2"></iframe>
</body>
</html>
Using jQuery I am trying to access div id="element".
<body>
<iframe id="uploads">
<iframe>
<div id="element">...</div>
</iframe>
</iframe>
</body>
All iframes are on the same domain with no www / non-www issues.
I have successfully selected elements within the first iframe but not the second nested iframe.
I have tried a few things, this is the most recent (and a pretty desperate attempt).
var iframe = jQuery('#upload').contents();
var iframeInner = jQuery(iframe).find('iframe').contents();
var iframeContent = jQuery(iframeInner).contents().find('#element');
// iframeContent is null
Edit:
To rule out a timing issue I used a click event and waited a while.
jQuery().click(function(){
var iframe = jQuery('#upload').contents().find('iframe');
console.log(iframe.find('#element')); // [] null
});
Any ideas?
Thanks.
Update:
I can select the second iframe like so...
var iframe = jQuery('#upload').contents().find('iframe');
The problem now seems to be that the src is empty as the iframe is generated with javascript.
So the iframe is selected but the content length is 0.
Thing is, the code you provided won't work because the <iframe> element has to have a "src" property, like:
<iframe id="uploads" src="http://domain/page.html"></iframe>
It's ok to use .contents() to get the content:
$('#uploads).contents() will give you access to the second iframe, but if that iframe is "INSIDE" the http://domain/page.html document the #uploads iframe loaded.
To test I'm right about this, I created 3 html files named main.html, iframe.html and noframe.html and then selected the div#element just fine with:
$('#uploads').contents().find('iframe').contents().find('#element');
There WILL be a delay in which the element will not be available since you need to wait for the iframe to load the resource. Also, all iframes have to be on the same domain.
Hope this helps ...
Here goes the html for the 3 files I used (replace the "src" attributes with your domain and url):
main.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>main.html example</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(function () {
console.log( $('#uploads').contents().find('iframe').contents().find('#element') ); // nothing at first
setTimeout( function () {
console.log( $('#uploads').contents().find('iframe').contents().find('#element') ); // wait and you'll have it
}, 2000 );
});
</script>
</head>
<body>
<iframe id="uploads" src="http://192.168.1.70/test/iframe.html"></iframe>
</body>
iframe.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>iframe.html example</title>
</head>
<body>
<iframe src="http://192.168.1.70/test/noframe.html"></iframe>
</body>
noframe.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>noframe.html example</title>
</head>
<body>
<div id="element">some content</div>
</body>
var iframeInner = jQuery(iframe).find('iframe').contents();
var iframeContent = jQuery(iframeInner).contents().find('#element');
iframeInner contains elements from
<div id="element">other markup goes here</div>
and iframeContent will find for elements which are inside of
<div id="element">other markup goes here</div>
(find doesn't search on current element) that's why it is returning null.
Hey I got something that seems to be doing what you want a do. It involves some dirty copying but works. You can find the working code here
So here is the main html file :
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
Iframe = $('#frame1');
Iframe.on('load', function(){
IframeInner = Iframe.contents().find('iframe');
IframeInnerClone = IframeInner.clone();
IframeInnerClone.insertAfter($('#insertIframeAfter')).css({display:'none'});
IframeInnerClone.on('load', function(){
IframeContents = IframeInner.contents();
YourNestedEl = IframeContents.find('div');
$('<div>Yeepi! I can even insert stuff!</div>').insertAfter(YourNestedEl)
});
});
});
</script>
</head>
<body>
<div id="insertIframeAfter">Hello!!!!</div>
<iframe id="frame1" src="Test_Iframe.html">
</iframe>
</body>
</html>
As you can see, once the first Iframe is loaded, I get the second one and clone it. I then reinsert it in the dom, so I can get access to the onload event. Once this one is loaded, I retrieve the content from non-cloned one (must have loaded as well, since they use the same src). You can then do wathever you want with the content.
Here is the Test_Iframe.html file :
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div>Test_Iframe</div>
<iframe src="Test_Iframe2.html">
</iframe>
</body>
</html>
and the Test_Iframe2.html file :
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div>I am the second nested iframe</div>
</body>
</html>
You probably have a timing issue. Your document.ready commend is probably firing before the the second iFrame is loaded. You dont have enough info to help much further- but let us know if that seems like the possible issue.
You should use live method for elements which are rendered later, like colorbox, hidden fields or iframe
$(".inverter-value").live("change",function() {
elem = this
$.ajax({
url: '/main/invertor_attribute/',
type: 'POST',
aysnc: false,
data: {id: $(this).val() },
success: function(data){
// code
},
dataType: 'html'
});
});
I think the best way to reach your div:
var your_element=$('iframe#uploads').children('iframe').children('div#element');
It should work well.
If browser supports iframe, then DOM inside iframe come from src attribute of respective tag. Contents that are inside iframe tag are used as a fall back mechanism where browser does not supports iframe tag.
Ref: http://www.w3schools.com/tags/tag_iframe.asp
I guess your problem is that jQuery is not loaded in your iframes.
The safest approach is to rely on pure DOM-based methods to parse your content.
Or else, start with jQuery, and then once inside your iframes, test once if typeof window.jQuery == 'undefined', if it's true, jQuery is not enabled inside it and fallback on DOM-based method.
Let's imagine that I have something like this:
<html>
...
<div>
<iframe src="test.html" hash="r4d5f7"></iframe>
<iframe src="test.html" hash="8f7x97"></iframe>
<iframe src="test.html" hash="gg4v5e"></iframe>
<iframe src="test.html" hash="e54f87"></iframe>
</div>
...
</html>
test.html is empty page, custom hash attribute always has a different value, both pages are on the same domain for security reasons, number and order of iframe elements is random.
My question is: Is there a way to get from inner page (test.html) using Javascript to its proper iframe element? Let's say, I'm in the third iframe's page and I need to get to its iframe element and alert() hash value (in this case "gg4v5e").
To be more specific. If you are familiar with Firefox's Firebug, it visualizes this situation like this:
<html>
...
<div>
<iframe src="test.html" hash="r4d5f7">
<html>
...
</html>
</iframe>
<iframe src="test.html" hash="8f7x97">
<html>
...
</html>
</iframe>
<iframe src="test.html" hash="gg4v5e">
<html>
...
</html>
</iframe>
<iframe src="test.html" hash="e54f87">
<html>
...
</html>
</iframe>
</div>
...
</html>
Is it possible to call "something" in order to get parent element (<iframe>) when I'm with my Javascript at <html> element in inner page?
Sure there is.
This code works in FF and IE6, Opera, Chrome (requires a web server and both files coming from same domain protocol and port)
function getHash() {
var ifs = window.top.document.getElementsByTagName("iframe");
for(var i = 0, len = ifs.length; i < len; i++) {
var f = ifs[i];
var fDoc = f.contentDocument || f.contentWindow.document;
if(fDoc === document) {
alert(f.getAttribute("hash"));
}
}
}