【问题标题】:Get Value of iframe Attribute from Within That iframe从该 iframe 中获取 iframe 属性的值
【发布时间】:2015-09-16 07:37:26
【问题描述】:

我有一个带有 custom data-* 属性的 iframe,它采用我的选择标记中的一个选项的值。我正在尝试通过引用该 iframe 属性在 iframe 中呈现的表单中检索此 data-id 的值。

编辑:我的 iframe 和原始 DOM 在同一个域中

我的表格:

<select id="option-dropdown">
    <option value="opt-1">Option 1</option>
    <option value="opt-2">Option 2</option>
</select>

用于拉取所选选项的脚本:

var optionSelected = $('#option-dropdown').val();

这里我的 iframe 是用 data-id 声明的:

'<iframe id="edit-iframe" data-id="' + optionSelected + '" src="/somePage + '"></iframe>'

最后是我在 iframe 中呈现的表单。这个表单可以引用 iframe 的data-id吗?

<form action="/someAction" method="post>
    <input id="input-1" value="optionSelected"/>
    <input id="input-2" value="someOtherValue"/>
    <button id="save" >Save</button>
</form>

【问题讨论】:

    标签: javascript jquery html forms iframe


    【解决方案1】:

    不,应该是cross site scripting

    基本上,来自一个域的 javascript 在没有各种潜在问题的情况下无法访问另一个域,因此它被浏览器阻止。

    您可以做到这一点的唯一方法是同时拥有源和目标并确保它们在同一个域中,在这种情况下您可能不需要 IFrame。

    【讨论】:

      【解决方案2】:

      使用window.opener。 例如,在 iframe 内部:window.opener.document.getElementById('edit-iframe').getAttribute('data-id')

      (当然,假设两个页面在同一个域中)

      【讨论】:

        【解决方案3】:

        由于我的 iframe 源与原始页面位于同一域中,因此我可以使用此方法检索 iframe 属性的值:

        var optionSelected = window.frameElement.getAttribute("data-id");
        

        虽然我确实同意@Toni Leigh 的观点,即我可能首先不需要 iframe,但目前上述方法就可以了。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-09-23
          • 2021-10-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-09-17
          • 2016-04-11
          相关资源
          最近更新 更多