parap
parap

Reputation: 1985

How to define javascript variable from within a iframe

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.

Upvotes: 2

Views: 1212

Answers (2)

geekchic
geekchic

Reputation: 2431

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'];

Upvotes: 1

basarat
basarat

Reputation: 276239

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';

Upvotes: 0

Related Questions