Search code examples
javascriptiframecross-domain

access function in iframe from cross domain parent


I have done some research on this and what i found was in same domain's case you can use

document.getElementById('iframe_id').contentWindow.function_name()

I tried this on cross-domain (just experimenting) It gave a cross domain error &

Exception: TypeError: Property 'function_name' of object [object Window] is not a function

So I have a three part question

a) It is understandable if I have trouble accessing parent from child (and I am already handling this, using another iframe(from parent's domain) within child iframe). But why do we have issue accessing child from parent, isn't that the same thing as having a

b) When I debug, using the chrome inspector tool & try to see the value of document.getElementById('iframe_id').contentWindow, I see my function_name under it, but cannot access it by document.getElementById('iframe_id').contentWindow.function_name(). Why is that?

c) How do I successfully call a javascript function in my iframe from the parent(without easyXDM or any other plugin)?

More details:
I am more of looking for two way communication as in, my parent will call a function in iframe that returns a result & based on that result the parent will decide if it wants to redirect or not


Solution

  • I used postMessage. Seemed like a simpler solution.

    What I wanted to do: 'beforeunload', send a message to child iframe, receive a response as callback. based on response show message or navigate.

    But this was not possible.

    This is how I solved it:

    Every time a change was made in my child frame, I sent a message to the parent. I collected these messages & used them on 'beforeunload' to decide if i should navigate or show the message