JavaScript code in iframe doesn't work - javascript

I have an iframe which is created after loading page. (main DOM)
var object_preview = $('#preview');
var iframe = $('<iframe id="preview_frame">'),
iframe_body,
iframe_head;
object_preview.html(iframe);
setTimeout(function() {
var doc = iframe[0].contentWindow.document;
iframe_body = $('body', doc);
iframe_head = $('head', doc);
}, 1);
When you click on a button, in the iframe head inserted JS-code (jQuery), which must be executed within the iframe DOM.
$('#run').click(function() {
iframe_body.append('<script type="text/javascript">\
$(document).ready(function() {\
$(".test").click(function() { alert(true); });\
});\
</script>');
});
Now it doesn't work. How to implement it?
Element with class .test is within iframe DOM.
HTML structure:
Thanks in advance.

Related

Check if all/multiple iframes are loaded

I am currently trying to run a function when all iframes on the page are loaded. I am using jQuery, but it only works when there is one iframe on the page. Once I start having mutiple iframes my functionality stops working. Here is the code im working with:
$('iframe.preview-iframe').on( 'load', function() {
$('iframe.preview-iframe').contents().find('section[rowposition] a').each(function(){
// Append a span tag with the href of the according content a tag
$(this).append('<span style="position:absolute;left:0;color:red;background:yellow;">' + $(this).attr('href') + '</span>');
});
});
Do I need to write a loop that looks over how many iframes I have and then only run the script once the last iframe is loaded or is there some other way to do it?=
You can do something like the following:
Get all the iframes elements in a variable
Loop through each of the iframes and if all of them are loaded, execute your required code.
$(window).on('load', function() {
var iframes = $('iframe');
var loaded = 0;
iframes.each(function() {
$(this).on('load', function() {
loaded++;
if (loaded == iframes.length) {
// run your code here
$('iframe').each(function() {
$(this).contents().find('section[rowposition] a').each(function() {
// Append a span tag with the href of the according content a tag
$(this).append('<span style="position:absolute;left:0;color:red;background:yellow;">' + $(this).attr('href') + '</span>');
});
});
}
});
});
});

Javascript - run function in iFrame after parent window has loaded

Is there a way to know if parent window has loaded from within iframe?
I want to run a function which is in iFrame but I need to run it after all the parent windows are loaded and the event listener will be inside the iframe.
I tried the following but it runs before parent windows are loaded.
window.addEventListener('load', function () {
alert("It's loaded!")
});
One way would be to add the iframe dynamically:
parent:
window.addEventListener('load', function () {
var iframe = document.createElement('iframe');
iframe.src = "https://www.example.com";
document.body.appendChild(iframe);
});
iframe:
window.addEventListener('load', function () {
alert('hello world!');
//doSomethingUseful();
}
This way, you could be certain that they will load in a specific order. However, as they'd be loading in series, the increase in total page load time could become noticeable.
Alternatively, you could use this approach. This one may not work as is, if one page happens to finish loading before the other. If you do opt for this approach, it may be necessary to communicate in both directions so that the first page to load finds out when the second page has loaded. That may look like this:
parent:
newEvent();
window.document.addEventListener('myCustomEventI', newEvent, false);
function newEvent() {
var data = { loaded: true }
var event = new CustomEvent('myCustomEventP', { detail: data })
window.parent.document.dispatchEvent(event);
}
iframe:
newEvent();
window.document.addEventListener('myCustomEventP', handleEvent, false);
function newEvent() {
var data = { loaded: true }
var event = new CustomEvent('myCustomEventI', { detail: data })
window.parent.document.dispatchEvent(event);
}
function handleEvent(e) {
alert('both loaded!');
//doSomethingUseful();
}

Detect when the iframe inside another iframe is loaded from third(parent) iframe

Brainf... with iframes.
So, current page structure:
page -> main_iframe -> iframe1 -> iframe2
The scripts are executed in "main_iframe".
This "main_iframe" has "iframe1" and "iframe1" has "iframe2" inside:
I want to change width=100% of iframe2 which is inside iframe1, which is inside main_iframe
SO i am executing following js at "main_iframe" and it works:
document.querySelector('#iframe1').onload = function() {
setTimeout(function(){
document.querySelector('#iframe1').contentDocument.querySelectorAll("iframe")[0].style.width = '100%';
}, 3000);
}
But how to remove timeout timer so it will render as soon as iframe2 has loaded?
I've tried following:
document.querySelector('#iframe1').onload = function() {
document.querySelector('#iframe1').contentDocument.querySelectorAll("iframe")[0].onload = function () {
document.querySelector('#iframe1').contentDocument.querySelectorAll("iframe")[0].style.width = '100%';
}
};
But without luck, nothing is happening after onload fires.
You can reference the outer iframe with this inside the load event handler, which makes it a bit tidier. This should do what you need...
document.querySelector("#iframe1").addEventListener("load", function() {
this.contentDocument.querySelector("iframe").style.width = "100%";
});

Dynamically Adding HTML into an iFrame - Javascript

I'm attempting to dynamically create an iFrame and add HTML into it from the current document. The iFrame gets created successfully, but when the function gets to the point where it needs to add the HTML in, it doesn't do it.
Here's my code:
function createiFrame(min, max, key) {
console.log("Max-Width", max);
//CREATING A CLASS FOR THE IFRAME
var iframeClass = key + "-" + max;
//var path = window.location.pathname;
//var page = path.split("/").pop();
//ADDING AN IFRAME INTO THE DOCUMENT AND ADDING ON THE CLASS
$(document).ready(function() {
$('<iframe>', {
width: max
}).addClass(iframeClass).prependTo('body');
});
var requiredHTML = document.getElementById('container').innerHTML;
console.log("RequiredHTML", requiredHTML);
//ADDING THE COLLECTED HTML INTO THE IFRAME -- THIS IS WHERE
//IT STOPS WORKING
$('.' + iframeClass).ready(function() {
console.log("iFrame ready");
$('.' + iframeClass).contents().find('body').html("<p>Testing it out</p>");
});
var $head = document.getElementsByTagName('head')[0].innerHTML;
$(document).ready(function() {
$('.' + iframeClass).contents().find('head').append($head);
});
}
EDIT
I've realised this problem is occurring because when I try to run that code, the DOM isn't ready yet.
So new question;
How do I get the DOM ready?
check out this post:
addEventListener to iFrame
you need to use
$('#myIFrame').load(function(){
....
$('.' + iframeClass).ready(function() {
...
}
Doesn't work because an iframe being ready doesn't trigger the Event 'DOMContentLoaded' which .ready() is waiting for. You'll need to refer directly to a document, which will then trigger the DOMContentLoaded event. This should work based on that.
$(iframeClass document).ready(function() {
...
}
I will stress though that this isn't something that I've tried before, but it seems like it's just a matter of which document you're referring to.

Loading JavaScript when div has loaded?

I have a script that will reload the page (content) to a random DIV
How do I implement this so that the script loads after the div is loaded?
I have the following code ready:
<script>
$(document).ready(function() {
$("#getAssignment").click(function() {
var $divs = $(".assignment");
if ($divs.length > 0) {
window.location.hash = "#" + $divs[ Math.floor(Math.random() *
$divs.length) ].id;
}
});
});
</script>
$("div").load(function(){
blah();
});
This will do what you wanted, but it does not make sense though, since div is not like an image or <script> or a page. (You can't really "load" a <div> anyway.)

Categories

Resources