Tuesday, August 10, 2010

Referencing a parent window object of a frame child in chrome

Google chrome is giving errors in javascript if you try to reference the parent window object of a frame element from the file system. Works very well in IE and Firefox. The problem occurs when you are trying to open the files from your local system. However when i open the files from my server, they work perfectly find. Let me give a quick example of what i'm talking about.
Say we have a function defined in our main frameset document (frameset-defining page) called showPicture() as follows:

<script type="text/javascript">
function showPicture(){
// do something

Now, let me call this function from a frame element defined in the frameset page element and both of these documents are in thesame location on my hard drive. Let's say we have something like this(remember that this is defined in the frame element and will reference the showPicture() function in the parent window object of the frameset element):

<html xmlns="http://www.w3.org/1999/xhtml">
    <title>My Child Frame</title>
<body onload="window.parent.showPicture()">
    <h2>This is the child frame page</h2>

In this case, chrome gives an error stating that "window.parent" is undefined and when I checked the developer console, the message states:
Unsafe Javascript attempt to access frame with URL file:///C:/myscripts/mainpage.htm from frame with URL file:///C:/myscripts/mainpagesub.htm. Domains , protocols and ports must match.
The only remedy i found was to run the pages inside a web server and not from my file system for it to work in chrome. However, this works perfectly fine in both IE and Firefox. It seems chrome does not like the fact that we are accessing the parent window object using the file protocol and gives a warning. Kinda strict if you ask me, but i guess there must be a reason behind this "feature".
So if you run into this problem, when developing and testing your site, don't throw in the towel yet, keep on baking.