dojo.setContext

since:V?

Changes the behavior of many core Dojo functions that deal with namespace and DOM lookup.

Introduction

“dojo.setContext” allows many of Dojo’s core functions to easily switch context (e.g. from the current window to an iframe) with a single function call.

For example, dojo.query references the “window” global variable when performing searches by default.

[ Dojo 1.7 AMD ]

require(["dojo/query"], function(query){
   var dojoLinks = query('a');
   var nativeLinks = document.getElementsByTagName('a');

   // Returns true, as they're searching the same window.document
   console.log(dojoLinks.length === nativeLinks.length);
});

[ Dojo < 1.7 ]

var dojoLinks = dojo.query('a');
var nativeLinks = document.getElementsByTagName('a');

// Returns true, as they're searching the same window.document
console.log(dojoLinks.length === nativeLinks.length);

This is because dojo stores many of the common global variables:

window:dojo.global
document:dojo.doc
body:dojo.body()

By calling “dojo.setContext” (which modifies the convenience variables above), you can easily query another frame’s content.

Usage

Dojo 1.7 (AMD)

require(["dojo/_base/window"], function(win){
  win.setContext(window, window.document);
  // or
  win.setContext(myIframe.contentWindow, myIframe.contentWindow.document);
});

Dojo < 1.7

dojo.setContext(window, window.document);
// or
dojo.setContext(myIframe.contentWindow, myIframe.contentWindow.document);

Examples

Error in the documentation? Can’t find what you are looking for? Let us know!