XWorm XWorm - 4 years ago 241
Javascript Question

Iframe and attaching events through jquery

What I am trying to do, is to pull files from the server side to the client side by using iframes.

The code below receives a json string with paths to files on the server. If the file exists, the file is downloaded, if it fails it should alert me. The alert functionality doesnt work. That is because I fail to attach the 'load' event.
The load eventhandler should give me the content of the iframe, but that doesnt happen. why? I receive nothing in the console.
var file_directory="http://localhost/test/";

$.getJSON('http://localhost/file.php', function(data) {
for(index in data) {
if(data[index]=='.' || data[index]=='..')
continue;

console.log(file_directory+data[index]);


var frame= $('<iframe />'); // Create an iframe element
$('<iframe />', {
name: 'frame1',
id: 'frame1'+index,
src: file_directory+"d"+data[index]
}).appendTo('body');

$('body').on('onload',frame,function() {
console.log(1);
try {
// Displays the first 50 chars in the innerHTML of the
// body of the page that the iframe is showing.
// EDIT 2012-04-17: for wider support, fallback to contentWindow.document
var doc = frame.contentDocument || frame.contentWindow.document;
console.log(doc);
alert(doc.body.innerHTML.substring(0, 50));
} catch (e) {
// This can happen if the src of the iframe is
// on another domain TypeError:Cannot read property 'document' of undefined
alert('exception: ' + e);
}
});
}

});

Answer Source

The load eventhandler should give me the content of the iframe, but that doesnt happen. why?

frame variable is not appended to document , "onload" is not a jQuery event

$('body').on('onload',frame,function() {

is not called for

$('<iframe />', {
                name: 'frame1',
                id: 'frame1'+index,
                src: file_directory+"d"+data[index]                 
            }).appendTo('body');

load event.


Try adjusting js to

var frame = $("<iframe />", {
    name: "frame1",
    id: "frame1" + index,
    src: file_directory + "d" + data[index]
})
// attach `load` event to `frame` before appending `frame` to `body`
.on("load", function() {
    // do stuff
    console.log(1);
    try {
        // Displays the first 50 chars in the innerHTML of the
        // body of the page that the iframe is showing.
        // EDIT 2012-04-17: for wider support, fallback to contentWindow.document
        var doc = frame.contentDocument || frame.contentWindow.document;
        console.log(doc);
        alert(doc.body.innerHTML.substring(0, 50));
    } catch (e) {
        // This can happen if the src of the iframe is
        // on another domain TypeError:Cannot read property "document" of undefined
        alert("exception: " + e);
    }
})
// append `frame` to `body` after attaching `.on("load")` to `frame`
.appendTo("body")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download