Accessing Javascript Variables Within An Iframe

2019-07-23 08:13发布

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.

2条回答
女痞
2楼-- · 2019-07-23 09:05

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.

查看更多
Fickle 薄情
3楼-- · 2019-07-23 09:11

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;
查看更多
登录 后发表回答