Mental Jetsam

By Peter Finch

Archive for March, 2010

Get HTTP cookies as associative array in Javascript.

Posted by pcfinch on March 23, 2010

The following snippet of Javscsript code can be used to retrieve a documents cookies as an associative array so that the values can be easily retrieved using associative array lookup methods like cookies[“username”] or cookies.username .

function getCookies() {
    var cookies = document.cookie.split( ';' );
    var list = {} ; 
    for ( i = 0; i < cookies.length; i++ ) {
        var cv = cookies[i].split( '=' );
        var name = cv[0].replace(/\s+/g, "").replace(/\s+$/g,"") ;
        list[name] =  cv[1] ;
   return (list) ; 
cookies = getCookies() ;

Posted in javascript | Leave a Comment »

Communicating between iframes and windows in Javascript

Posted by pcfinch on March 15, 2010

Sometimes it is not possible to keep your entire web application in one window, you may need to “pop-up” a new window or even embed an IFRAME containing another part of your application. If you need to communicate between the two windows the following code can be used in the “child” frames and windows to access Javascript functions in the parent window. Using this method it is possible to make the child window send notifications back to the parent window in order to update the parent windows state, etc. Note that this will only work when the windows and IFRAME’s come from the same domain.

In the parent window (main window) define any javascript functions as normal e.g in “index.html”.

tstFunction = function(message) {
  alert("Main Window " + message) ;

Include the following code in the child windows or IFRAMEs e.g. in “popup.html”.

function getParentFunction(funcName) {
  var func = null;
  // Child opened in new window e.g. target="blank"
  if (top.window.opener && !top.window.opener.closed) {
    try { func = eval("top.window.opener."+funcName); } catch (error) {}
  if (!(func)) {
    // Child opened in IFRAME
    try { func = eval("top."+funcName); } catch (error) { }
  if (!(func)) {
    throw new Error("function \""+funcName+"\" is not in parent window.");
  return func; 

If you need to call a function defined in the parent window from the child do this.

var foo = getParentFunction("tstFunction") ;
foo("Hello from iframe") ;

Posted in javascript | 4 Comments »