Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
128 views
in Technique[技术] by (71.8m points)

javascript - How to expose IFrame's DOM using jQuery?

I have a prototype representing a particual IFrame. That prototype have a function called GoToUrl(...) that opens the given url within the IFrame.

My question is: How do I create an "InternalDOM" property and make this property refer to the "window" object (the root DOM object) of the IFrame inside? In such way that: If my IFrame exposes a page which has an object X in it's "window" object I could do:

MyFrameObject.GoToUrl(pageXurl);
MyFrameObject.InternalDOM.X

Any help would be appreciated.

PS: I would accept answers not necessarily related to jQuery but I would prefer a jQuery solution.

question from:https://stackoverflow.com/questions/1654017/how-to-expose-iframes-dom-using-jquery

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To get the window object for a frame you can use the window.frames array:

var iframewindow= frames['iframe_name'];

This requires that you give the <iframe> an old-school name attribute instead-of-or-as-well-as the id. Alternatively if you know the order of iframes on the page you can index them numerically:

var iframewindow= frames[0];

It's generally more flexible to get the iframe window from the iframe element in the DOM, but this requires some compatibility code to cope with IE:

var iframe= document.getElementById('iframe_id');
var iframewindow= iframe.contentWindow? iframe.contentWindow : iframe.contentDocument.defaultView;

jQuery defines the contents() method to grab the document node, but it doesn't give you a cross-browser way to go from the document to the window, so you're still stuck with:

var iframe= $('#iframe_id')[0];
var iframewindow= iframe.contentWindow? iframe.contentWindow : iframe.contentDocument.defaultView;

which isn't really a big win.

(Note: be very careful using jQuery for cross-frame-scripting. Each frame needs its own copy of jQuery and methods from one frame's copy won't necessarily work on nodes from the other. Cross-frame-scripting is a topic fraught with traps.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

Just Browsing Browsing

1.4m articles

1.4m replys

5 comments

57.0k users

...