After searching Google and Stack Overflow I decided to ask if this is even possible.
Currently I am loading an iFrame on my site. I wish to hide a certain element loaded in the iFrame.
<span id="blahblah">
function collapseAll(){
var body = document.getElementById('body');
var spans = body.getElementsByTagName("span");
var span;
for (i = 0; i < spans.length; i++){
span = spans[i];
if(span.class=='blahblah'){
span.style.visibility = "hidden";
}
}
}
However this did not work. Question number one is can this be done? If yes could you explain how?
Thank you kindly.
You'll have to put that script inside the contents of the iframe. You can't access the DOM of another frame, especially if it's from another domain.
Sorry, but you cannot access elements within an iframe from the outer window, due to security controls.
You would have to try this, but you might be able to create a function on the window object of the iframe and the call it from the outer window.
In the iframe:
<script type="text/javascript">
window.collapseAll = function() {
.....
}
</script>
In the outer window:
<script type="text/javascript">
function doCollapse() {
document.getElementById('my_iframe").window.collapseAll();
}
</script>
Again, that's untested but I'm pretty sure Facebook does something similar to that.
if the iframe is from the same domain as your javascript is from then this is doable.
using plain javascript you would write the following
`
function collapseAll(){
var body = document.getElementById('body');
var spans = body.getElementsByTagName("span");
var span;
for (i = 0; i < spans.length; i++){
span = spans[i];
if(span.class=='blahblah'){
**span.style.display = "none";**
}
}
}
this fixes the issue.
if the iframe is from a different site (domain) then things would get really difficult..
there are solutions like greasemonkey which can operate on pages from different domains.
you can try
document.frame.document.getElementsByTagName('span')
<script type="text/javascript">
function remove_elemment() {
var body = document.getElementById('body');
var divs = body.getElementsByTagName("div");
var div;
for (i = 0; i < divs.length; i++){
div = divs[i];
if(div.class=='buybox'){
**div.style.display = "none";**
}
}
};
function doRemove() {
document.frame.document.getElementById('my_iframe').remove_elemment();
}();
</script>
<div class="floating-widget">
<iframe id="my_iframe" src="http://www.nodebeginner.org/index-vi.html" frameborder="0" width="100%" height="500">
</iframe>
</div>
Related
i'm completely new to Javascript and I wanted to create an Greasemonkey Script that replaced "/text/othertext/" to "/text2/text3" on all the href elements of the document. That's what i came up with, and as expected, it doesn't work:
var links = document.getElementsByTagName('a');
for (i=0; i<links.length; i++)
{
var gethref = links[i].getAttribute('href');
gethref = gethref.replace(/text\/othertext/g,'text2\/text3');
links[i].setAttribute("href", gethref);
}
Thanks in advance!
Edit: ok, i know why my script is not working, but i don't know if it can be fixed, i'm trying to replace elements that load after the page is completely loaded (maybe with ajax?)
http://i.imgur.com/7n5V7Bi.png
This code works. Your code looks okay too. Perhaps you are loading the script before the document elements? Note how my elements are listed before my script:
link
link
<script>
var links = document.getElementsByTagName('a');
for(var i = 0; i < links.length; i++) {
var href = links[i].getAttribute('href');
href = href.replace('before', '#');
links[i].setAttribute('href', href);
}
</script>
Edit, based on your comments a dirty fix to cause delay in your app before running a script is to use the setTimeout function. To delay five seconds for example, you might use it like this:
link
link
<script>
setTimeout(function() {
var links = document.getElementsByTagName('a');
for(var i = 0; i < links.length; i++) {
var href = links[i].getAttribute('href');
href = href.replace('before', '#');
links[i].setAttribute('href', href);
}
}, 5000); // < --- note the time in ms here
</script>
Not too sure why your code wouldn't be working.
I've put together the following snippet which might help.
(function() {
var anchors = document.querySelectorAll('a');
for(var i = 0; i < anchors.length; i++) {
var newHref = anchors[i].getAttribute('href').replace(/text\/othertext/g,'text2\/text3');
anchors[i].setAttribute('href', newHref);
}
}());
a {
display: block;
}
<!DOCTYPE html>
<head></head>
<body>
Some link
Some other link
</body>
If you run this snippet you'll see only one anchor is updated correctly as intended.
Hope that helps you out!
The easiest solution would be to wrap your code in this:
window.onload = function(){
/* your code here */
};
This will ensure that your code (especially if you've placed your script in the of the document, won't load until the whole page is loaded (including text, images, etc).
window.onload = function() {
document.body.innerHTML = document.body.innerHTML
.replace('<a href="text/othertext/"', '<a href="text2/text3"');
};
<!DOCTYPE html>
<head></head>
<body>
Some link
Some other link
</body>
I would like to load a bunch of iframes at different times, not all at the same time but one after another like one at 300000ms, then 209000ms, then 257000ms, etc. They will all need to be loaded at different times after each other and I need to be able to change them later if needed. I would like it to be when I click a button not as an onload event. I have little experience in javascript.
Please no jQuery.
Thanks!
Edit: I want the iframes to load on top of one another, or replace one another, not load a bunch of them in a list. I will only be putting up around 5 iframes total. Sorry for not being specific enough. Something like this, except for the time working:
<a target='page' href='http://framedsite1'>#1 (visible for 300000ms)</a>
<a target='page' href='http://framedsite2'>#2 (visible for 209000ms)</a>
<a target='page' href='http://framedsite3'>#3 (visible for 257000ms)</a>
<iframe id='page' name='page' src=''></iframe>
Except for auto playing through them all, not as a bunch of links but by being clicked on and loaded into the iframe after a set amount of time after the previous frames time has gone by, kind of like a playlist. They will all need to be displayed for different amounts of time then load the next iframe, I am emphasizing that they all will be different amounts of time.
You can use setInterval() and loop through to set the source for each iframe:
var iframes = document.getElementsByTagName("iframe"); //retrieves a NodeList of iframes
var i = 0;
var interval = window.setInterval(function(){
if(i < iframes.length){
iframes[i].src = "//example.com"; //source of the iframes
i++;
}else{
window.clearInterval(interval);
}
}, 3000); //interval to load each iframe in milliseconds
Demo
If you want to trigger it with a button click, just wrap it in a function and attach an event listener:
document.getElementById("idOfButton").addEventListener("click", function(){
var iframes = document.getElementsByTagName("iframe"); //retrieves a NodeList of iframes
var i = 0;
var interval = window.setInterval(function(){
if(i < iframes.length){
iframes[i].src = "//example.com"; //source of the iframes
i++;
}else{
window.clearInterval(interval);
}, 3000); //interval to load each iframe in milliseconds
});
Demo
<html>
<head>
<script>
var iframes;
var loadIframes = function(){
iframes = document.getElementsByClassName('custom-iframe');
for(var i=0; i<iframes.length; i++){
var iframe = iframes[i],
seconds = iframe.getAttribute('data-seconds'),
src = iframe.getAttribute('data-src');
run(i, src, seconds);
}
}
var run = function(i, src, seconds){
setTimeout(function(){
iframes[i].src = src;
}, seconds);
}
</script>
</head>
<body>
<button onclick="loadIframes()">Load iframes</button>
<iframe class="custom-iframe" data-seconds="3000" data-src="http://example.com"></iframe>
<iframe class="custom-iframe" data-seconds="900" data-src="http://google.com"></iframe>
</body>
</html>
Just change "data-seconds" and "data-src" attributes in each iframe, and put "custom-frame" class in the iframe elements.
When you click the button, they will run based on the iframe custom configs.
<html>
<head>
<script>
var buttons = document.getElementsByClassName('iframe-button');
var iframe = document.getElementById('my-iframe');
for(var i=0; i < buttons.length; i++){
var button = buttons[i];
button.addEventListener("click", function(){
var src = button.getAttribute('data-src');
iframe.src = src;
});
}
</script>
</head>
<body>
Example.com
Google.com
<iframe id="my-iframe"></iframe>
</body>
Just need to repeat those <a> elements. Put "iframe-button" class on them, and "data-src" attribute if the URL value.
I Have a div something like this
<div id="tid">
<iframe>
<html>
<body>
<scripts></scripts>
<iframe>...
//more content
<ifram>
</body>
</html>
</iframe>
</div>
I want to get below using javascript.
<iframe>
<html>
<body>
<scripts></scripts>
<iframe>...
//more content and cannot guess how many iframes are there.
<ifram>
</body>
</html>
</iframe>
InnerHtml only return first iframe only. I tried with .contentDocument.getElementsByTagName('body')[0].innerHTML. but this only return first iframe. I want get all the content into string variable without using jquery.
Thanks
YOU NEED TO REPLACE < WITH < AND > WITH > TO PRINT HTML TAGS AS A PLAIN TEXT.
try this code,
var content = document.getElementById('tid').innerHTML;
content = content.replace(/</g,"<").replace(/>/g,">");
document.getElementById('content').innerHTML = content;
SEE THIS DEMO
if you want to reuse that div html, simply add that content to any other html element like below,
var content = document.getElementById('tid').innerHTML;
//the variable content contains the html inside "tid" div.
var iDiv = document.createElement('div');
iDiv.id = 'newDiv';
iDiv.innerHTML = content;
document.getElementsByTagName('body')[0].appendChild(iDiv);
SEE THIS DEMO
If you only want the body tags this should work.
var els = document.getElementsByTagName("body");
var allContent = "";
for (var i=0; i < els.length; i++) {
allContent += els[i].innerHTML;
}
Do this
var iframe = document.getElementById('iframeID');
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
now you can use iframeDocument to access content of iframe, jquery does the same
UPDATE
You can do something like this ..
var myDiv = document.getElementById("tid");
var iframes = myDiv.getElementsByTagName("iframe");
// now loop over the iframes
for(iframe in iframes){
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
var internalIframes = iframeDocument.getElementsByTagName("iframe");
if(internalIframes.length > 1){
// start the for in loop again
}
}
can not do this because of same origin policy
Because of the widget format I'm working with I have a page which has multiple iframes embedded within iframes. I won't paste the code as it's vast and unwieldy but it is essentially just this:
<html>
<head></head>
<body>
<iframe>
<html>
<head></head>
<body>
<iframe>
<html>
<head></head>
<body>
<iframe>
<html>
<head></head>
<body>
blah
</body>
</html>
</iframe>
</body>
</html>
</iframe>
</body>
</html>
</iframe>
</body>
</html>
However, there may be more - or less - iframes dependent upon the page and template I use.
I'm trying to therefore get the ID of all of the iframes in this page, from within the most-embedded iframe.
Is this possible with jQuery? I've tried a few snippets of code but had no luck:
$('iframe', window.parent.document).each(function() {
console.log($(this).attr("id"));
});
$('iframe', parent.document).each(function() {
console.log($(this).attr("id"));
});
$('iframe').each(function() {
console.log($(this).attr("id"));
});
The output of these is a single ID string - and unfortunately it's not the iframe I'm looking to control.
Thanks in advance,
EDITED
This returns an iframe element which has the wanted id, and null, if the wanted id is not found.
function searchIds(wantedId) {
var idArray = [], n,
search = function (iframes) {
var n;
for (n = 0; n < iframes.length; n++) {
if (iframes[n].frames.length > 0) {
search(iframes[n].frames);
}
idArray.push(iframes[n].frameElement.id);
idArray.push(iframes[n].frameElement);
}
};
search(window.top.frames);
for (n = 0; n < idArray.length; n += 2) {
if (idArray[n] === wantedId) {
return idArray[n + 1];
}
}
return null;
}
Notice, that searchIds() can't be run before onload of the main window has been fired.
I do not believe you can reference the iframe's children directly. You will need to recursively search each iframe using it's .contents() call.
As far as I know, this will only work as long as the same-origin policy is not violated (i.e. the iframes must point to the same domain).
From the most embedded iframe:
var ids = (function up( context, ids ){
ids = ids || [];
// proceed if we're not at the top window yet
if( context !== window.top){
// point context to parent window (or top if no parent).
context = context.parent || window.top;
// get the id of the first iframe in parent window;
// this will break if there are sibling iframes
ids.push(context.document.getElementsByTagName('iframe')[0].id);
// recursive call to traverse parents
return up(context, ids);
} else {
// otherwise return the list of ids
return ids;
}
}(this)); // 'this' is the initial context - current window
console.log( ids );
I forgot to include 'run multiple times in one page' on my last question located here: Create iframe with javascript appending to a div
I need to run the code on multiple div's within the same page. Right now the code below only runs once on the last div. For example if I have 3 div's, all 3 should have an iframe appended to it. Regular javascript. Trying not to use JQuery.
window.onload = function(){
var link = "http://www.somesite.com"
var iframe = document.createElement('iframe');
iframe.frameBorder=0;
iframe.width="300px";
iframe.height="250px";
iframe.id="randomid";
iframe.setAttribute("src", link);
document.getElementById("ad54").appendChild(iframe); //<--this id will be dynamically generated to match div's
}
<div class="ad" id="1"></div>
<div class="ad" id="2"></div>
<div class="ad" id="3"></div>
EDIT: Tested in IE9, Chrome, Safari, Firefox and opera. This code works. No JQuery or loops needed. This code will create the iframe wherever you use it.
var link = "http://www.somesite.com"
document.write(iframe);
var myIframe = parent.document.getElementById("randomid");
myIframe.height = 250;
myIframe.width = 300;
myIframe.src = link;
myIframe.style.border = "0px";
myIframe.style.padding = "0px";
window.onload = function() {
var elements = document.getElementsByTagName('div');
for (var i = 0; i < elements.length; i++) {
append_iframe( elements[i] );
}
}
function append_iframe( div ) {
var link = "http://www.somesite.com"
var iframe = document.createElement('iframe');
iframe.frameBorder=0;
iframe.width="300px";
iframe.height="250px";
iframe.id="randomid";
iframe.setAttribute("src", link);
div.appendChild(iframe);
}
Not a jQuery guy but I think this works
$("div").each(function(d) {
var link = "http://www.somesite.com"
var iframe = document.createElement('iframe');
iframe.frameBorder=0;
iframe.width="300px";
iframe.height="250px";
iframe.id="randomid";
iframe.setAttribute("src", link);
this.appendChild(iframe);
});