javascript setAttribute iFrame 名称和 Chrome

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19458395/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 15:39:10  来源:igfitidea点击:

setAttribute iFrame name and Chrome

javascriptgoogle-chrome

提问by Pawel Urbanski

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

这是一个用于 iFrame 附加名称的简单 setAttribute。

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

问题是下面的代码在除 Chrome 之外的所有浏览器中都能很好地工作。

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

Parent javascript:

父javascript:

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

})();

in the iFrame:

在 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.

Alert 在所有浏览器中调用“Hello”,Chrome 调用“frame”——这是 iFrame 的 ID。查看源代码(通过元素检查器),在 Chrome 中,我看到了 iFrame 的正确名称:name="Hello" ...但警报调用了 id。

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

为什么会这样?我错过了什么吗?

采纳答案by Pawel Urbanski

Creating iframe by createElement fixes the issue:

通过 createElement 创建 iframe 解决了这个问题:

 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.

有点黑客,但它适用于这种情况。

回答by Karim Ayachi

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

6 年半后,我遇到了同样的问题。

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.

似乎 Chrome 设置了 window.name 属性一次,并且在更新封闭 iFrame 的名称(属性或属性)时不会更新它。

Setting the window.name directly does work however.

然而,直接设置 window.name 确实有效。

So, changing the OP's example from:

因此,将 OP 的示例更改为:

(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...

作品...