从同一域的 iframe 中的 .js 访问父页面的输入字段
我有一个在页面上运行并与现有数据交互的 .js 文件。该 .js 文件创建一个 iframe,该 iframe 加载另一个也安装了 .js 文件的页面(均带有 GreaseMonkey)。我试图让 iframe 中运行的 .js 文件从父页面获取 var 。两者都在同一域中,但不会访问数据。这是我所拥有的:
js1:
var myvar1 = document.getElementsByName('nameofinputfromparentpage')[0].value;
js2:
var myvar2 = parent.document.getElementsByID('page1').getElementsByName('nameofinputfromparentpage')[0].value;
或者
var myvar2 = myvar1 (or parent.myvar1 or window.myvar1 or a dozen other variances...)
我尝试使用以下内容将 var 从 js1 推送到 js2: window.frames[iframeName].variableName
或使用 contentDocument
/contentWindow
。 我似乎无法获得正确的语法来使其实际提取数据...
所以...父页面的页面源有一个输入框,如何在运行的 .js 中访问该信息在父页面上另一个 .js 的 iframe 中?谢谢大家的帮助! :)
I have a .js file that runs on a page and interacts with the data already there. That .js file creates an iframe which loads another page that also has a .js file installed (both with GreaseMonkey). I'm trying to make the .js file running in the iframe grab a var from the parent page. Both are on the same domain, but it will not access the data. Here's what I have:
js1:
var myvar1 = document.getElementsByName('nameofinputfromparentpage')[0].value;
js2:
var myvar2 = parent.document.getElementsByID('page1').getElementsByName('nameofinputfromparentpage')[0].value;
or
var myvar2 = myvar1 (or parent.myvar1 or window.myvar1 or a dozen other variances...)
I've tried pushing the var from js1 to js2 with something like:window.frames[iframeName].variableName
or using contentDocument
/contentWindow
.
I just can't seem to get the syntax right to make it actually pull the data...
So... the page source of the parent page has an input box, how do I get that info to be accessed in .js running in an iframe of another .js on the parent page? Thank you everyone for your help! :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从 IFrame 内部,parent 属性引用父级,因此:
将访问位于此文档父级中 ID 为“myInputBox”的元素的内容。如果脚本是从框架对象外部的顶级文档执行的,则属性parent=self。请注意,ID 属性在单个 HTML 文档中必须是唯一的,因此该函数是 getElementByID() 而不是 getElementsByID()。此外,也不需要索引,因为只会返回一个元素。
From inside the IFrame the parent property refers to the parent, so:
will access the contents of an element with the ID 'myInputBox' located in the parent of this document. In the case that the script is executed from a top level document outside a frame object, the property parent=self. Please note that the ID property must be unique within a single HTML document, so the function is getElementByID() not getElementsByID(). Also there is no need for an index because there will only be one element returned.