Search code examples
javascriptframes

Javascript: Checking if function exists in sibling frame before calling


I have two frames in a window. Frame A and frame B.

I want to call a function which is in frame A from frame B. To do this I use:

 parent.frames['mainframe'].myfunction();

The catch is that the function may not actually exist in frame A.

I want to check if it exists before calling.

I tried this but got a JS error.

if ( typeof parent.frames['mainframe'].myfunction == 'function' ) { 
        //function_name is a function
}

Error:

TypeError: undefined is not a function

Update:

You are all correct- the actual code I was running was typeof parent.frames['mainframe'].myfunction() with parenthesis. Sorry :/ What do I do about best answer?


Solution

  • Your code should definitely work. It does appear that myfunction isn't in the global scope on the child window. When you refer to parent.frames['mainframe'] you are essentially referencing the window object in the 'mainframe' iframe. Here's a JSFiddle where the child function is explicitly set on the window object and works just fine.

    JSFiddle Example