Pawel Urbanski
Pawel Urbanski

Reputation: 201

setAttribute iFrame name and Chrome

Here is a simple setAttribute for an iFrame to append a name.

Issue is that the below code works great in all browsers except Chrome.

<iframe id="frame" frameborder="0" src="http://website.ca/"></iframe>

Parent javascript:

(function() {
    var newFrameName = "hello";
    document.getElementById("frame").setAttribute("name", newFrameName);

})();

in the iFrame:

    var iframeName = window.name;
    alert (iframeName );

Alert calls "Hello" in all browsers, Chrome calls "frame" -- which is the ID of the iFrame. looking at source (through the elements inspector), in Chrome, I see the correct name for the iFrame: name="Hello" ... but the alert calls the id.

why would that be? I'm i missing anything?

Upvotes: 2

Views: 22525

Answers (2)

Karim Ayachi
Karim Ayachi

Reputation: 717

6 and a half years later I ran into the same problem.

It seems that Chrome sets the window.name property once and doesn't update it when the enclosing iFrame's name (either property or attribute) is updated.

Setting the window.name directly does work however.

So, changing the OP's example from:

(function() {
    var newFrameName = "hello";
    document.getElementById("frame").setAttribute("name", newFrameName);
})();

into

(function() {
    var newFrameName = "hello";
    document.getElementById("frame").name = newFrameName; // keep for other browsers
    document.getElementById("frame").contentWindow.name = newFrameName;
})();

works...

Upvotes: 1

Pawel Urbanski
Pawel Urbanski

Reputation: 201

Creating iframe by createElement fixes the issue:

 function createFrame() {
        frame= document.createElement("iframe");
        frame.setAttribute("src", "https://website.ca/");
        frame.setAttribute("name", "Hello");
        frame.setAttribute("id", "frame");
        frame.frameBorder = 0;
        frame.style.width = 100 + "%";
        frame.style.height = 2300 + "px";
        document.getElementById("iframeHolder").appendChild(frame);

    }
    createFrame();

<div id="iframeHolder"> </div>

Bit of a hack, but it works for this situation.

Upvotes: 4

Related Questions