Access elements within dynamically created iframe (jquery 1.x) - javascript

I created an iframe with content dynamically loaded with jquery like this and I want the iframe document to access its content as soon as it has been loaded:
jQuery('<iframe>', {
id: 'widgetFrm',
width: '100%'
})
.appendTo('#widgetDiv')
.on('load', function () {
jQuery(this).contents().find('body').append(data.html);
})
The frame document knows about jquery because I use
if (typeof(jQuery) == "undefined") {
var iframeBody = document.getElementsByTagName("body")[0];
var jQuery = function (selector) { return parent.jQuery(selector, iframeBody);
}
there. Within the iframe, I'd like to access its div elements after everything got loaded, I'm using jQuery(document).ready for that (within the dynamically loaded content).
Problem: Accessing its own elements in the frame document somehow does not work with jquery 1.x in document ready block!
document.getElementById('#someDiv') returns null and jQuery('#someDiv').prop('scrollHeight') returns undefined, although the frame content has that element (accessing it when clicking a button works!). With newer jQuery versions (for instance 3.3.1) it works, but I can't change that version currently. Is there another way to do that?
Thank you!

Related

How to resize appened iframe to its content?

As the title, how to resize appened iframe to content?
I have already referred other questions:
jquery get height of iframe content when loaded
Resize iframe to content with Jquery
Get height of element inside iframe with jQuery
, but it is still not working. The following are my codes:
$(function() {
$('#appendIframeHere').append("<iframe src=\"http://www.w3schools.com/\"></iframe>");
var iframe = $('#appendIframeHere').find('iframe');
iframe.css("width", "100%");
iframe.css("height", iframe.contents().find('body').height() );
$('#appendIframeHere').text(iframe.contents().find('body').height());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<div id="appendIframeHere"></div>
------------------------------------------------------------update------------------------------------------------------------
I use the same way to get height() but it has different value, 0 and 2786. I tried to add a callback function to append() but I have seen some reference said that append() complete immediately so I don't have to use callback. After that I also tried promise().done(function(){...}) to append() but it still get different value from js file and console.

Scripts not running when using get function in jquery

I'm using the $.get() function to extract some data from my site. Everything works great however on one of the pages the information I need to extract is dynamically created and then inserted into a <div> tag.
So in the <script> tag, a function is run and then the data is inserted into <div id="infoContainer"></div>. I need to get the information from #infoContainer, however when I try to do so in the $.get() function, it just says it's empty. I have figured out that it is because the <script> tag is not being run. Is there another way to do this?
Edit:I am making a PhoneGap application for my site using jQuery to move content around so it's more streamlined for mobiles.
This is the code on my page:
$(document).ready(function () {
var embedTag = document.createElement("embed");
var infoContainer = document.getElementById("infoContainer");
if (infoContainer != null) {
embedTag.setAttribute("height", "139");
embedTag.setAttribute("width", "356");...other attributes
infoContainer.appendChild(embedTag);
});
});
As you can see, it puts content into the #infoContainer tag. However, when I try to extract info from that tag through the get function it shows it as empty.I have done the same to extract headings and it works great. All I can gather is the script tag is not firing.
This should provide you the contents of the element:
$('#infoContainer').html();
Maybe your script is executing before the DOM is loaded.
So if you are manipulating DOM elements you should wait till DOM is loaded to manipulate it. Alternately you can place your script tag at the end of your HTML document.
// These three are equivalent, choose one:
document.addEventListener('DOMContentLoaded', initializeOrWhatever);
$( initializeOrWhatever );
$.ready( initializeOrWhatever );
function initializeOrWhatever(){
// By the time this is called, the DOM is loaded and you can read/write to it
$.getJSON('/foo/', { myData: $('#myInput').val() }, onResponse);
function onResponse(res){
$(document).html('<h1>Hello '+res+'</h1>');
};
};
Otherwise... post more specifics and code
You have no ID to reference. Try setting one before you append
embedTag.setAttribute("id", "uniqueID");
It looks like you are wanting to use jQuery, but your example code has vanilla JavaScript. Your entire function can be simplified using the following jQuery (jsFiddle):
(function () {
var embedTag = $(document.createElement("embed"));
var infoContainer = $("#infoContainer");
if (infoContainer.length) {
embedTag.attr({"height": 139, "width": 356});
infoContainer.append(embedTag);
}
console.log(infoContainer.html()); // This gets you the contents of #infoContainer
})();
jQuery's .get() method is for sending GET requests to a server-side script. I don't think it does what you are wanting to do.

Make document.ready take into account elements from external iframe

The position I find my self in is the following. I have a jQuery plugin which needs to be nested within the document.ready function. This plugin applies some styling to elements of the page. One of elements affected by this plugin contains an iframe. This iframe is not from my website. The issue is that document.ready doesn't take into account contents of iframe, and when it gets loaded it's height changes, but jQuery plugin was already applied before this, therefore layout of the page is screwed up.
I tried the following to make sure plugin get's called only if document is ready and iframe is ready as well:
$(document).ready(function() {
$('#frameId').ready(function() {
//plugin code
});
});
But this doesn't work and I'm looking for another solution.
Only the document has a ready() event, for iFrame's it would be onload :
$(document).ready(function() {
$('#frameId').on('load', function() {
//plugin code
});
});
But why does your plugin require access to an iFrame ?
The solution is $.holdReady();
$.holdReady(true);
$(document).ready(function() {
//plugin code
});
$('#frameId').on('load', function() {
$.holdReady(false);
});
For accessing the height of cross-domain iFrame contents, you need the postMessage. Check out this post

Check if a parent iFrame has jQuery already loaded

I'm trying to create a login widget in an iframe that can be used on a clients website. This iframe will be using jQuery, but I first wont to be able to check if the parent document has jQuery loaded, if not, load it.
I've tried several different techniques but none seem to wont to work, or decide to load the jQuery library twice.
Any help would be greatly appreciated.
This code block is within the page loaded inside the iframe, which refuses to co-operate.
<script>
var jQOutput = false;
function initjQuery() {
if (typeof(jQuery) == 'undefined'){
if (!jQOutput){
jQOutput = true;
var jScript = document.createElement('script');
jScript.setAttribute("type", "text/javascript");
jScript.setAttribute("src", "js/libs/jquery/jquery-min.js");
}
setTimeout("initjQuery()", 50);
} else {
$(function() {
$("#email").css({"background":"red"});
//visual aid to see if jQuery is loaded.
});
}
}
</script>
I just want to check and see if the parent to the iframe has loaded jQuery, and if not, load it myself, as I'll be using it to perform several tasks needed to complete the login proceedure.
Entented comment:
I dont think what you want to archive is posible because of same origin policy (Cross domain access via JavaScript) - look it op on Google... http://google.com/search?q=same+origin+policy
If you on the other hand dont violate the same origin policy you can archive what you want using something like this:
var parent = window.parent; // This refers to parent's window object
if ( parent && parent.jQuery ) { // Check to see if parent and parent.jQuery is truly
window.jQuery = parent.jQuery;
window.$ = parent.jQuery;
}
else {
// load jQuery here
}
The JavaScript code of your widget has to be divided into two parts. One of them would be loaded on a client's site. It would have permissions to access the DOM of the site: load jQuery if needed, create an iframe, etc. (Be especially careful with global variables there! Try not to use them at all since they can conflict with the code of the site.) Note that this part wouldn't have access to the DOM of the iframe. That's why you need the second part, which would be loaded inside of the iframe. You can use cross-domain techniques for the parts to exchange messages with each other. I'd advise you to check out the easyXDM library.

Checking if iframe is ready to be written to

A 3rd party script on my web page creates an iframe. I need to know when this iframe is ready, so I can manipulate its DOM.
I can think of a hacky approach: repeatedly try to modify the iFrame's DOM, and return success when a change we make sticks between two attempts. For this to work, I would prefer a property I can check on the iframe repeatedly.
Is there an alternative, cross-browser evented approach to knowing that the iframe is ready? E.g. can we redefine the onLoad function to call into our code (but I don't know if I can do this, since I didn't create the iframe).
using jquery?
function callIframe(url, callback) {
$(document.body).append('<IFRAME id="myId" ...>');
$('iframe#myId').attr('src', url);
$('iframe#myId').load(function()
{
callback(this);
});
}
Question answered in jQuery .ready in a dynamically inserted iframe
Have a variable in the parent:
var setToLoad = false;
Follow it up with a function to set it:
function SetToLoad() {
setToLoad = true;
}
Then in the child iframe call this function using the window.opener
function CallSetToLoad() {
window.opener.SetToLoad();
}
window.onload = CallSetToLoad;
This won't run until the iframe is finished loading, and if it's in the same domain it'll allow access to the opener. This would require editing a small portion of the 3rd party script.
EDIT: Alternative solution
Given that you can't edit the script, you might try something like:
frames["myiframe"].onload = function()
{
// do your stuff here
}
Can you inject arbitrary scripting code into your iframe? If so, you should be able to make it so that some code executes in the iframe upon the the iframe loading that calls code in the parent page.
First: You probably won't be able to manipulate its dom when it loads html from other domain
And You probably are interested in DOMready.
Look here:
jQuery .ready in a dynamically inserted iframe
Bilal,
There's a document.readyState property that you can check (works in IE).
foo(){
if([your iframe id].document.readyState != "complete")
{
setTimeout("foo()", 500); //wait 500 ms then call foo
}
else
{
//iframe doc is ready
}
}
Arkady

Categories