2

I have an iframe with that needs to change a global variable in the parent page.

I tried

parent.myvar = "myvalue";
parent.myfunction();

However, it's not working for me. The function executes but the variable remains unchanged.

EDIT: both the iframe and the parent are in the same domain.

parap
  • 1,844
  • 5
  • 19
  • 28
  • possible duplicate of [Set variable in parent window from iframe](http://stackoverflow.com/questions/1301540/set-variable-in-parent-window-from-iframe) – George Aug 16 '13 at 09:17
  • yes, both are in the same domain – parap Aug 16 '13 at 09:19
  • Your code works as it is. If you're using Chrome and run this in a local machine, you need to see [this SO answer](http://stackoverflow.com/questions/5660116/unsafe-javascript-attempt-to-access-frame-in-google-chrome). Notice also, that it's possible, that the function within `iframe` is not executed at a time you use `myvalue` in the main window. This appears for example if you read `myvalue` within `$(document).ready();` in the main window, or have placed your at parsing time executed script just before closing `body` tag. – Teemu Aug 16 '13 at 10:01

2 Answers2

1

Not possible if the iframe and the main document are not in the same domain.

If iframe and main document are in the same domain, you can access their global variables. Try this maybe.

document.getElementById('iframeid').contentWindow['myvar'];
geekchic
  • 2,371
  • 4
  • 29
  • 41
0

There is nothing wrong with that code : https://stackoverflow.com/a/1301645/390330

// set the global variable 'foo' in the parent global scope
parent.foo = 'bar';
Community
  • 1
  • 1
basarat
  • 261,912
  • 58
  • 460
  • 511