3

Is it possible to create an Iframe using document.createElement("iframe"); and then set a variable in the iframe's window object such as a namespace?

I have tried doing something like this:

var Namespace = {}; 
var iframe = document.createElement("iframe"); 
iframe.src = "page.html"; 
document.body.appendChild(iframe);
var iwin = iframe.contentWindow || iframe.contentDocument.defaultView; 
iwin.Namespace = Namespace;

But in page.html I try to log Namespace and it throws an undefined error.

2 Answers 2

5

The same-origin policy is probably blocking you from doing this. This can also happen in some browsers if both pages use a file:// uri scheme.

If the iframe and the outer windows will be using the same domain, this problem should go away once your code is on a server. Try serving it from localhost using apache to check, or test it with google chrome with same-origin policy disabled as per this post:

Disable same origin policy in Chrome

On the other hand, if the iframe needs to be at a different domain, or this needs to work with the file:// uri scheme, you'll need to use some kind of workaround.

One way to pass data into an iframe at another domain is via a fragment identifier in the iframe element's src attribute, which will be visible in the iframe window's 'location' object's 'hash' property; for example:

Outer page:

<!doctype html>
<html><head></head><body>
<script>
  var Namespace = {foo:1, bar:2}; 
  var iframe = document.createElement("iframe"); 
  iframe.src = "frame.html#" + JSON.stringify(Namespace);
  document.body.appendChild(iframe);
</script>
</body></html>

Inner page "frame.html":

<!doctype html>
<html><head></head><body>
<a href="#" onclick="alert(location.hash.substring(1))">click me</a>
</body></html>
1
  • My hero; thank you very much. Didn't know same origin applied to file://
    – Louis
    Commented Jul 5, 2010 at 8:18
0

document.appendChild(iframe);

I'm pretty sure you need to add the node you created to the DOM.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.