DevMobile
DevMobile

Reputation: 209

Javascript: HTML CODE in javascript into a frame

I'm trying to put a HTML code into a frame.

Out of frame I have used: document.write and into?

The frame is:

var frameTwitter = document.getElementById('FrameTwitter');

Upvotes: 0

Views: 3308

Answers (3)

thewebguy
thewebguy

Reputation: 1520

Since you're using 2 files that are on the same domain this should work. It's probably ideal to use a relative path on the iframe since you've got to match domains, protocols & ports or this will stop working.

MainPage.html

<iframe src="Frame.html" id="FrameTwitter"></iframe>

<script type="text/javascript">
var frame = document.getElementById('FrameTwitter');
frame.writeInto('Some text here');
</script>

Frame.html

<script type="text/javascript">
function writeInto(str) {
    document.writeln(str);
}
</script>

That way you can set up the functionality you need for Frame.html within the file, test functionality there without worrying about cross-frame development yet. Then once your features are set up you can fire them from the parent.

Upvotes: 0

gen_Eric
gen_Eric

Reputation: 227240

In order to write to an iFrame, you need to get its contentWindow or contentDocument.

var frameTwitter = document.getElementById('FrameTwitter'),
    frameDocument = frameTwitter.contentWindow || frameTwitter.contentDocument;
frameDocument = frameDocument.document || frameDocument;

frameDocument.write('<p>Hello World!</p>');

DEMO: http://jsfiddle.net/NTICompass/8Ekrs/1/

UPDATE: You can also use window.frames to get the iFrame's window object.

var frameDocument = window.frames.FrameTwitter.document;
frameDocument.write('<p>Hello World!</p>');

DEMO: http://jsfiddle.net/NTICompass/8Ekrs/2/

Upvotes: 3

balafi
balafi

Reputation: 2153

you have to use the postmessage API see https://developer.mozilla.org/en-US/docs/DOM/window.postMessage

Rocket Hazmat is also correct

Normally, scripts on different pages are only allowed to access each other if and only if the pages which executed them are at locations with the same protocol (usually both http), port number (80 being the default for http), and host (modulo document.domain being set by both pages to the same value)

Upvotes: 0

Related Questions