Relative Path Reference - Ajax Patterns

Relative Path Reference

From Ajax Patterns

See http://softwareas.com/relative-paths-and-on-demand-calls-in-gadgets

This should eventually be made trivial by an OpenSocial spec enhancement.

The function below loads a script dynamically, i.e. after the gadget has loaded. It exploits the fact that even for an XML gadget, which comes from the container rather than the source domain, the original URL is embedded in the iframe. For example, a typical URL for the gadget's iframe is:

http://161.gmodules.com/ig/ifr?url=http://ajaxify.com/run/widgets/opensuite/todo/todo.xml&nocache=2147483647&up_tasks=%5B%5D&upt_tasks=hidden&lang=en&country=us&.lang=en&.country=us&synd=ig&mid=161&ifpctok=8592012488487540063&parent=http://www.google.com&extern_js=/extern_js/f/CgJlbhICdXMrMAo4ACwrMBI4ACwrMBM4ACw/z3DLmokYxOY.js

As you can see, the gadget is coming from gmodules.com rather than the source URL at ajaxify.com. However, the URL happens to contain the source URL as well. This is a hack, because OpenSocial doesn't require it so; but it seems that all containers do this in practice. So some string manipulation gets us the original source URL, and we can then use that to build absolute URLs from relative ones. The following function accepts a relative URL and converts it to an absolute one. It also happens to accept absolute URLs, for the sake of convenience.

var gadgetURL = _args()["url"];
function loadScript(scriptURL, onLoaded) {
 var baseURL=gadgetURL.replace(/[a-zA-Z0-9_]+\.xml(\?.*)?/,"")
 if (scriptURL.indexOf("http")!=0) scriptURL = baseURL + scriptURL;
 if (debugMode) scriptURL+="?" + (new Date()).getTime();
 var script = document.createElement("script");
 script.src = scriptURL;
 if (onLoaded) script.onload = onLoaded;
   document.body.appendChild(script);
}