简体   繁体   English

从该iframe中获取iframe属性的值

[英]Get Value of iframe Attribute from Within That iframe

I have an iframe with a custom data-* attribute that takes the value of an option in my select tag. 我有一个带有自定义data-*属性的iframe,该属性在我的select标签中带有一个选项的值。 I'm trying to retrieve the value of this data-id within a form that is rendered in an iframe by referencing that iframe attribute. 我正在尝试通过引用iframe属性在iframe中呈现的表单中检索此data-id的值。

EDIT: My iframe is and original DOM are on the same domain 编辑:我的iframe和原始DOM在同一域中

My form: 我的表格:

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

Script to pull the option selected: 脚本来拉选择的选项:

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

And here my iframe is declared with the data-id: 在这里,我的iframe用data-id声明:

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

And finally my form that is rendered within the iframe. 最后是我在iframe中呈现的表单。 Can this form get reference to the iframe's data-id ? 此表单可以引用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>

No, this would be cross site scripting . 不,这将是跨站点脚本

Basically javascript from one domain cannot access another domain without all sorts of potential problems so it's blocked by the browsers. 基本上,来自一个域的javascript在没有各种潜在问题的情况下无法访问另一个域,因此它被浏览器阻止。

The only way you could do it would be by owning both the source and the target and making sure they were on the same domain, in which case you probably wouldn't need an IFrame. 唯一的方法是拥有源和目标,并确保它们位于同一域中,在这种情况下,您可能不需要IFrame。

Use window.opener . 使用window.opener for instance, inside the iframe: window.opener.document.getElementById('edit-iframe').getAttribute('data-id') 例如,在iframe中: window.opener.document.getElementById('edit-iframe').getAttribute('data-id')

(of course, assuming both pages are on the same domain) (当然,假设两个页面都在同一个域中)

Being that my iframe source is on the same domain as my original page, I can retrieve the value of my iframe attribute with this method: 由于我的iframe源与我的原始网页位于同一域中,因此可以使用以下方法检索iframe属性的值:

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

Though I do agree with @Toni Leigh on the fact that I probably don't need an iframe in the first place, but for the time being the above method will do fine. 尽管我确实同意@Toni Leigh的事实,即我可能首先不需要iframe,但暂时使用上述方法会很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM