user1381745
user1381745

Reputation: 3900

Inserting an iFrame with Javascript

Taking inspiration from Javascript to insert IFRAME, I am trying to insert an iFrame via Javascript:

function display(selector) {

    var i = document.createElement('iframe');
    i.scrolling = 'no';
    i.frameborder = '0';
    i.allowtransparency = 'true';
    i.style.border = 'none';
    i.style.overflow = 'hidden';
    i.style.width = $(selector).css('width');
    i.style.height = $(selector).css('height');
    i.src = '//localhost/content';
    $(selector).append(i);
}

Forgive the lazy jQuery.

Anyway, this works as expected on Firefox, but Chrome bails out with the following error:

Port: Could not establish connection. Receiving end does not exist.

Chrome does add the expected HTML, but doesn't display the iFrame. What's the reason for this and, if there is one, what's a better way to achieve what I'm trying to do?

Upvotes: 1

Views: 79

Answers (1)

dezman
dezman

Reputation: 19388

Your code seems to work for me, maybe you need to add a port to your localhost url.

Here is a working fiddle

function display(selector) {

    var i = document.createElement('iframe');
    i.scrolling = 'no';
    i.frameborder = '0';
    i.allowtransparency = 'true';
    i.style.border = 'none';
    i.style.overflow = 'hidden';
    i.style.width = $(selector).css('width');
    i.style.height = $(selector).css('height');
    i.src = 'http://www.wikipedia.com';
    $(selector).append(i);
}

display($('#cont'));

html:

<div id="cont"></div>

css:

#cont {
     width: 200px;
    height: 200px;
}

personally i would use a function like this, and do the rest with css:

function iframeIt(where, url) {
    where.append('<iframe src="' + url + '"></iframe>');
}

iframeIt($('#cont'), 'http://www.wikipedia.com');

Upvotes: 1

Related Questions