Accessing Javascript Variables Within An Iframe

妖精的绣舞 提交于 2019-12-13 01:26:33

问题


If i was to visit the source of my iframe, I notice that it has a value "srt" , I can access this variable by simply typing "srt" When in the iframes Source. However when it is an "iframe" typing "srt" no longer works since the variable is nested within the iframe.

How can i store the value of a variable that is in an iframe, To a variable that is not In the iframe, to access this value Outside.


回答1:


You can use the frames collection by index or by the frame's name. Each element in the collection is the window object for that frame, which is where global variables are stored.

frames[0].srt // if there's just one
frames['frameName'].srt  // accessing by the name property

Or you can get the iframe element and use contentWindow to retrieve the iframe's window object

 document.getElementById('frameId').contentWindow.srt;

Also remember that you can't access a frame that is not in the same domain.




回答2:


Assuming the iframe has an id frame, from the parent:

var innerValue = document.getElementById('frame').contentWindow['srt'];

Or the other way round, from within the iframe:

parent.iframeValue = srt;


来源:https://stackoverflow.com/questions/19693984/accessing-javascript-variables-within-an-iframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!