Chamnap Chhorn

Ruby, Rails, and JavaScript Developer

Cross-window Javascript Communication

| Comments

It reminds me about uploading via iframe that I did a year ago when my colleague asked me to help with login openid in a popup window. It’s a similar story with this problem. Actually, login with openid could not place in a iframe because you could the code that prevents this. view plainprint?

1
if(top == self) { document.write(""); } else  { top.location.href = "http://www.yahoo.com"; }

Now, let’s see a quick summary on this basic communication.

Communication from parent to child window, you need to a reference of the child window so that can call any function in the child window.

1
2
3
4
5
    // Create a new popup window  
    var popupWin = window.open(url, "popupWin");

    // To call functions defined in the popup:  
    popupWin.doSomething();

Communication from child to parent window, you need to use this way:

1
    window.opener.doSomethingOnParent();

Here is the problem, the parent window needs to know when the uploading (in iframe) or logging in (in popup window) is done. The only way that the parent window can notified by the child window after finish processing. Usually, for uploading and logging in with openid, the action in your controller would render a view back. The trick is here on the onload of the body, you could notify the parent window.

1
2
3
    def login
      @status = "something"
    end
1
2
3
4
    <html><head></head>
    <body onload="window.opener.handleOpenIDResponse('" + @status + "');window.close();">
    </body>
    </html>

That would solve the problem, and you could send any information back through your view.

JavaScript in Object-Oriented Way Presentation

| Comments

I conducted a training to some developers in my office about one full day, yesterday. It is quite exhausted anyway, but everyone seems understand really well. This slide covers many advanced features of JavaScript: Function, Object, Closure,…. Some other points I have pointed out in this slide are about how to make private variable, public variable, static variable, privileged variable and how to do inheritance. I took about 20 different sources as my references and three famous authors. It took me two weeks, at every weekend, to finish this slide.