Web Services - Sample 03: Using an IFRAME with JavaScript

toggle iframe quit pymol (FireFox only: view page source)

In order to make it possible to issue multiple PyMOL command from a single JavaScript event, we create a queue and use the IFRAME's onload method to iteratively request every URL placed on the queue.

var pymol_queue = [];

var pymol_active = false;

function pymol_queue_flush() {
   if (pymol_queue.length>0) {
      document.getElementById("pymol_response_iframe").src = pymol_queue.shift(); 
      pymol_active = true;
   } else {
      pymol_active = false;
   }
}

We then modify the Javascript "cmd" function to accept a list of query suffixes, each of which is converted to a unique URL and placed on the queue.

function cmd() {
    for(var i=0; i < arguments.length; i++) {
        pymol_queue.push( "/apply/pymol.cmd."+ arguments[i] + 
                          ( arguments[i].indexOf('?') < 0 ? '?' : '&' ) + 
                          "_ts=" + new Date().getTime());
    }
    if(!pymol_active) {
        pymol_queue_flush();
    }
}

This approach is probably the simplest practical way to call multiple PyMOL methods from a web page without doing JavaScript development or relying upon XMLHttpRequest (AJAX). The downside is that you need to manually encode your requests as URL query strings with keyword arguments and (where necessary) URL escaping.

cmd('set?name=suspend_updates',
    'delete?name=all',
    'reset',
    'load?filename=$PYMOL_PATH/test/dat/1tii.pdb',
    'show?representation=cartoon',
    'show_as?representation=sticks&selection=chain A',
    'orient?selection=chain A&animate=5',
    'unset?name=suspend_updates')

cmd('count_atoms')

cmd('reinitialize')