Fri 22 Feb 2008
As pointed out by Jon’s blog post, simply use the dojo/dijit objects on the top window within an iframe won’t work for dojo APIs in most cases, because “the top level dojo object has no Out of the Box knowledge of the iframes or their content”.
Actually, dojo has two APIs in the core to support running code in the context of an iframe: dojo.withGlobal and dojo.withDoc. However, they do not have much attention, as most of their usage is only seen in the dijit.Editor code. Actually, they were introduced for the sole purpose of dojo.widget.Editor (which is the dojo 0.4 Editor widget) for dojo 0.4 in the first place.
Both of them have identical signature:
dojo.withGlobal(/*Object*/globalObject, /*Function*/callback,/*Object?*/thisObject, /*Array?*/cbArguments)
In order to use them, you can wrap your code in a function first, like this:
function iframefunc(){
dojo.byId(‘foo’);
dijit.byId(‘foo’);
dojo.query(‘a.foo’);
}
and call the function as this in an iframe:
dojo.withGlobal(window,iframefunc)
You can also call dojo APIs directly use dojo.withGlobal. Say you want to run dojo.byId(‘foo’) in an iframe, you can do:
dojo.withGlobal(window,'byId',dojo,['foo'])
Note that, the above code can also run correctly in the context of the top window.
The differences between dojo.withGlobal and dojo.withDoc is the first argument: if you want to only change document of a function call operates on, you can use dojo.withDoc instead and pass it with the document of an iframe.