Bug 911573 - Mochitest fixup to prepare removing Components-in-content with UniversalXPConnect. r=bholley
authorMasatoshi Kimura <VYV03354@nifty.ne.jp>
Thu, 05 Sep 2013 01:02:34 +0900
changeset 145463 45446ab0c72656eaa3afd505db47d94a686fa301
parent 145462 d1737d0cb67557d8e22fddb933ca3f0e461fab16
child 145464 fb8dac49d9dca3f4079bc2b866029eb96c0c9d8f
push id33285
push userVYV03354@nifty.ne.jp
push dateWed, 04 Sep 2013 16:03:50 +0000
treeherdermozilla-inbound@fb8dac49d9dc [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersbholley
bugs911573
milestone26.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Bug 911573 - Mochitest fixup to prepare removing Components-in-content with UniversalXPConnect. r=bholley
caps/tests/mochitest/test_disallowInheritPrincipal.html
content/base/test/copypaste.js
content/base/test/fileutils.js
content/base/test/test_XHRSendData.html
content/base/test/test_bug270145.xhtml
content/base/test/test_bug401662.html
content/base/test/test_bug403852.html
content/base/test/test_bug417384.html
content/base/test/test_bug422403-2.xhtml
content/base/test/test_bug424359-1.html
content/base/test/test_bug424359-2.html
content/base/test/test_bug498433.html
content/base/test/test_bug498897.html
content/base/test/test_bug541937.html
content/base/test/test_bug578096.html
content/base/test/test_copyimage.html
content/base/test/test_fileapi.html
content/base/test/test_htmlcopyencoder.html
content/base/test/test_htmlcopyencoder.xhtml
content/base/test/test_websocket.html
content/base/test/websocket_hybi/test_send-blob.html
content/events/test/test_bug336682.js
content/events/test/test_bug508479.html
content/html/content/test/forms/test_formnovalidate_attribute.html
content/html/content/test/forms/test_max_attribute.html
content/html/content/test/forms/test_min_attribute.html
content/html/content/test/forms/test_required_attribute.html
content/html/content/test/forms/test_step_attribute.html
content/html/content/test/forms/test_submit_invalid_file.html
content/html/content/test/test_bug557087-3.html
content/html/content/test/test_bug561636.html
content/html/content/test/test_bug590353-2.html
content/html/content/test/test_bug598643.html
content/html/content/test/test_bug605124-1.html
content/html/content/test/test_bug605125-1.html
content/media/test/file_access_controls.html
content/media/webspeech/recognition/test/head.js
content/xml/document/test/test_bug392338.html
content/xul/content/test/test_bug486990.xul
dom/plugins/test/mochitest/cocoa_window_focus.html
dom/plugins/test/mochitest/test_GCrace.html
dom/plugins/test/mochitest/test_getauthenticationinfo.html
dom/plugins/test/mochitest/test_visibility.html
dom/plugins/test/mochitest/utils.js
dom/tests/mochitest/ajax/offline/foreign2.html
dom/tests/mochitest/ajax/offline/offlineTests.js
dom/tests/mochitest/ajax/offline/test_bug460353.html
dom/tests/mochitest/ajax/offline/test_missingManifest.html
dom/tests/mochitest/ajax/offline/test_obsolete.html
dom/tests/mochitest/bugs/test_bug61098.html
dom/tests/mochitest/general/test_clipboard_events.html
dom/tests/mochitest/general/test_focusrings.xul
dom/tests/mochitest/localstorage/test_localStorageBaseSessionOnly.html
dom/tests/mochitest/localstorage/test_localStorageEnablePref.html
dom/tests/mochitest/localstorage/test_localStorageQuota.html
dom/tests/mochitest/localstorage/test_localStorageQuotaSessionOnly.html
dom/workers/test/test_suspend.html
editor/libeditor/html/tests/test_CF_HTML_clipboard.html
editor/libeditor/html/tests/test_contenteditable_focus.html
editor/libeditor/html/tests/test_htmleditor_keyevent_handling.html
editor/libeditor/text/tests/test_bug569988.html
editor/libeditor/text/tests/test_bug596333.html
editor/libeditor/text/tests/test_texteditor_keyevent_handling.html
embedding/test/test_bug293834.html
embedding/test/test_bug449141.html
embedding/test/test_bug499115.html
embedding/test/test_nsFind.html
extensions/cookie/test/file_testcommon.js
extensions/cookie/test/file_testloadflags.js
gfx/tests/mochitest/test_bug509244.html
gfx/tests/mochitest/test_bug513439.html
image/test/mochitest/imgutils.js
image/test/mochitest/test_bug512435.html
image/test/mochitest/test_bug601470.html
intl/uconv/tests/test_long_doc.html
js/jsd/test/jsd-test.js
js/jsd/test/test_bug507448.html
js/jsd/test/test_bug617870-callhooks.html
js/jsd/test/test_bug638178-execlines.html
layout/base/tests/test_bug394057.html
layout/base/tests/test_bug399284.html
layout/base/tests/test_bug416896.html
layout/base/tests/test_bug548545.xhtml
layout/base/tests/test_bug603550.html
layout/generic/test/test_bug263683.html
security/manager/ssl/tests/mochitest/bugs/test_bug483440.html
security/manager/ssl/tests/mochitest/mixedcontent/test_bug383369.html
security/manager/ssl/tests/mochitest/stricttransportsecurity/test_stricttransportsecurity.html
toolkit/components/alerts/test/test_alerts.html
toolkit/components/alerts/test/test_alerts_noobserve.html
toolkit/components/microformats/tests/test_Microformats.html
toolkit/components/microformats/tests/test_Microformats_add.html
toolkit/components/microformats/tests/test_Microformats_adr.html
toolkit/components/microformats/tests/test_Microformats_count.html
toolkit/components/microformats/tests/test_Microformats_geo.html
toolkit/components/microformats/tests/test_Microformats_getters.html
toolkit/components/microformats/tests/test_Microformats_hCalendar.html
toolkit/components/microformats/tests/test_Microformats_hCard.html
toolkit/components/microformats/tests/test_Microformats_negative.html
toolkit/components/microformats/tests/test_framerecursion.html
toolkit/components/places/tests/Makefile.in
toolkit/components/places/tests/mochitest/bug_411966/redirect.js
toolkit/components/places/tests/mochitest/test_bug_411966.html
toolkit/components/places/tests/mochitest/test_bug_94514.html
toolkit/components/url-classifier/tests/mochitest/test_classifier.html
toolkit/components/url-classifier/tests/mochitest/test_classifier_worker.html
uriloader/exthandler/tests/mochitest/test_unsafeBidiChars.xhtml
widget/tests/test_bug565392.html
--- a/caps/tests/mochitest/test_disallowInheritPrincipal.html
+++ b/caps/tests/mochitest/test_disallowInheritPrincipal.html
@@ -17,29 +17,28 @@ https://bugzilla.mozilla.org/show_bug.cg
 <pre id="test">
 <script type="application/javascript">
 
 /** Test for Bug 732413
     Passing DISALLOW_INHERIT_PRINCIPAL flag should be effective even if
     aPrincipal is the system principal.
  **/
 
-netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
-const nsIScriptSecurityManager = Components.interfaces.nsIScriptSecurityManager;
-var secMan = Components.classes["@mozilla.org/scriptsecuritymanager;1"]
+const nsIScriptSecurityManager = SpecialPowers.Ci.nsIScriptSecurityManager;
+var secMan = SpecialPowers.Cc["@mozilla.org/scriptsecuritymanager;1"]
                        .getService(nsIScriptSecurityManager);
 var sysPrincipal = secMan.getSystemPrincipal();
 isnot(sysPrincipal, undefined, "Should have a principal");
 isnot(sysPrincipal, null, "Should have a non-null principal");
 is(secMan.isSystemPrincipal(sysPrincipal), true,
    "Should have system principal here");
 
 
-var ioService = Components.classes["@mozilla.org/network/io-service;1"].
-                getService(Components.interfaces.nsIIOService);
+var ioService = SpecialPowers.Cc["@mozilla.org/network/io-service;1"].
+                getService(SpecialPowers.Ci.nsIIOService);
 var inheritingURI = ioService.newURI("javascript:1+1", null, null);
 
 // First try a normal call to checkLoadURIWithPrincipal
 try {
   secMan.checkLoadURIWithPrincipal(sysPrincipal, inheritingURI,
                                    nsIScriptSecurityManager.STANDARD);
   ok(true, "checkLoadURI allowed the load");
 } catch (e) {
--- a/content/base/test/copypaste.js
+++ b/content/base/test/copypaste.js
@@ -18,38 +18,38 @@ function modifySelection(s) {
   window.setTimeout(function () {
       e.parentNode.removeChild(e);
       g.removeAllRanges();
       g.addRange(l);
   }, 0)
 }
 
 function getLoadContext() {
-  var Ci = SpecialPowers.wrap(Components).interfaces;
+  var Ci = SpecialPowers.Ci;
   return SpecialPowers.wrap(window).QueryInterface(Ci.nsIInterfaceRequestor)
                                    .getInterface(Ci.nsIWebNavigation)
                                    .QueryInterface(Ci.nsILoadContext);
 }
 
 function testCopyPaste (isXHTML) {
   netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
 
   var suppressUnicodeCheckIfHidden = !!isXHTML;
   var suppressHTMLCheck = !!isXHTML;
 
-  var webnav = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
-                     .getInterface(Components.interfaces.nsIWebNavigation)
+  var webnav = window.QueryInterface(SpecialPowers.Ci.nsIInterfaceRequestor)
+                     .getInterface(SpecialPowers.Ci.nsIWebNavigation)
 
-  var docShell = webnav.QueryInterface(Components.interfaces.nsIDocShell);
+  var docShell = webnav.QueryInterface(SpecialPowers.Ci.nsIDocShell);
 
   var documentViewer = docShell.contentViewer
-                               .QueryInterface(Components.interfaces.nsIContentViewerEdit);
+                               .QueryInterface(SpecialPowers.Ci.nsIContentViewerEdit);
 
-  var clipboard = Components.classes["@mozilla.org/widget/clipboard;1"]
-                            .getService(Components.interfaces.nsIClipboard);
+  var clipboard = SpecialPowers.Cc["@mozilla.org/widget/clipboard;1"]
+                            .getService(SpecialPowers.Ci.nsIClipboard);
 
   var textarea = SpecialPowers.wrap(document.getElementById('input'));
 
   function copySelectionToClipboard(suppressUnicodeCheck) {
     documentViewer.copySelection();
     if (!suppressUnicodeCheck)
       ok(clipboard.hasDataMatchingFlavors(["text/unicode"], 1,1), "check text/unicode");
     if (!suppressHTMLCheck)
@@ -78,31 +78,31 @@ function testCopyPaste (isXHTML) {
   }
   function copyChildrenToClipboard(id) {
     textarea.blur();
     clipboard.emptyClipboard(1);
     window.getSelection().selectAllChildren(document.getElementById(id));
     copySelectionToClipboard();
   }
   function getClipboardData(mime) {
-    var transferable = Components.classes['@mozilla.org/widget/transferable;1']
-                                 .createInstance(Components.interfaces.nsITransferable);
+    var transferable = SpecialPowers.Cc['@mozilla.org/widget/transferable;1']
+                                    .createInstance(SpecialPowers.Ci.nsITransferable);
     transferable.init(getLoadContext());
     transferable.addDataFlavor(mime);
     clipboard.getData(transferable, 1);
     var data = {};
     transferable.getTransferData(mime, data, {}) ;
     return data;
   }
   function testClipboardValue(mime, expected) {
     if (suppressHTMLCheck && mime == "text/html")
       return null;
     var data = getClipboardData(mime);
     is (data.value == null ? data.value :
-        data.value.QueryInterface(Components.interfaces.nsISupportsString).data,
+        data.value.QueryInterface(SpecialPowers.Ci.nsISupportsString).data,
       expected,
       mime + " value in the clipboard");
     return data.value;
   }
   function testPasteText(expected) {
     textarea.value="";
     textarea.focus();
     textarea.editor.paste(1);
@@ -252,17 +252,16 @@ if (false) {
   // ============ manipulating Selection in oncopy
 
   copyRangeToClipboard($("div11").childNodes[0],0, $("div11").childNodes[1],2);
   testClipboardValue("text/unicode", "Xdiv11");
   testClipboardValue("text/html", "<div><p>X<span>div</span>11</p></div>");
   setTimeout(function(){testSelectionToString("div11")},0);
 
   setTimeout(function(){
-    netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
     copyRangeToClipboard($("div12").childNodes[0],0, $("div12").childNodes[1],2);
     testClipboardValue("text/unicode", "Xdiv12");
     testClipboardValue("text/html", "<div><p>X<span>div</span>12</p></div>");
     setTimeout(function(){ 
       testSelectionToString("div12"); 
       setTimeout(SimpleTest.finish,0);
     },0);
   },0);
--- a/content/base/test/fileutils.js
+++ b/content/base/test/fileutils.js
@@ -129,37 +129,35 @@ function testHasRun() {
  //alert(testRanCounter);
  ++testRanCounter;
  if (testRanCounter == expectedTestCount) {
     SimpleTest.finish();
   }
 }
 
 function createFileWithData(fileData) {
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-  var dirSvc = Components.classes["@mozilla.org/file/directory_service;1"].getService(Components.interfaces.nsIProperties);
-  var testFile = dirSvc.get("ProfD", Components.interfaces.nsIFile);
+  var dirSvc = SpecialPowers.Cc["@mozilla.org/file/directory_service;1"].getService(SpecialPowers.Ci.nsIProperties);
+  var testFile = dirSvc.get("ProfD", SpecialPowers.Ci.nsIFile);
   testFile.append("fileAPItestfile2-" + fileNum);
   fileNum++;
-  var outStream = Components.classes["@mozilla.org/network/file-output-stream;1"].createInstance(Components.interfaces.nsIFileOutputStream);
+  var outStream = SpecialPowers.Cc["@mozilla.org/network/file-output-stream;1"].createInstance(SpecialPowers.Ci.nsIFileOutputStream);
   outStream.init(testFile, 0x02 | 0x08 | 0x20, // write, create, truncate
                  0666, 0);
   outStream.write(fileData, fileData.length);
   outStream.close();
 
   var fileList = document.getElementById('fileList');
-  fileList.value = testFile.path;
+  SpecialPowers.wrap(fileList).value = testFile.path;
 
   return fileList.files[0];
 }
 
 function gc() {
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-  window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
-        .getInterface(Components.interfaces.nsIDOMWindowUtils)
+  window.QueryInterface(SpecialPowers.Ci.nsIInterfaceRequestor)
+        .getInterface(SpecialPowers.Ci.nsIDOMWindowUtils)
         .garbageCollect();
 }
 
 function checkMPSubmission(sub, expected) {
   function getPropCount(o) {
     var x, l = 0;
     for (x in o) ++l;
     return l;
--- a/content/base/test/test_XHRSendData.html
+++ b/content/base/test/test_XHRSendData.html
@@ -73,20 +73,20 @@ extensions.forEach(
 
       var fileList = document.getElementById('fileList');
       fileList.value = testFile.path;
       testDOMFiles.push(fileList.files[0]);
     }
 );
 
 function createFileWithDataExt(fileData, extension) {
-  var dirSvc = Components.classes["@mozilla.org/file/directory_service;1"].getService(Components.interfaces.nsIProperties);
-  var testFile = dirSvc.get("ProfD", Components.interfaces.nsIFile);
+  var dirSvc = SpecialPowers.Cc["@mozilla.org/file/directory_service;1"].getService(SpecialPowers.Ci.nsIProperties);
+  var testFile = dirSvc.get("ProfD", SpecialPowers.Ci.nsIFile);
   testFile.append("testfile" + extension);
-  var outStream = Components.classes["@mozilla.org/network/file-output-stream;1"].createInstance(Components.interfaces.nsIFileOutputStream);
+  var outStream = SpecialPowers.Cc["@mozilla.org/network/file-output-stream;1"].createInstance(SpecialPowers.Ci.nsIFileOutputStream);
   outStream.init(testFile, 0x02 | 0x08 | 0x20, 0666, 0);
   outStream.write(fileData, fileData.length);
   outStream.close();
 
   return testFile;
 }
 
 tests = [{ body: null,
--- a/content/base/test/test_bug270145.xhtml
+++ b/content/base/test/test_bug270145.xhtml
@@ -12,20 +12,19 @@ https://bugzilla.mozilla.org/show_bug.cg
 <p id="display"></p>
 <div id="content" >
 <p id="foo"><![CDATA[a text to copy]]></p>
 </div>
 <pre id="test">
 <script class="testbody" type="text/javascript">
 //<![CDATA[
 function testHtmlCopyEncoder () {
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-  const de = Components.interfaces.nsIDocumentEncoder;
-  var encoder = Components.classes["@mozilla.org/layout/htmlCopyEncoder;1"]
-                   .createInstance(Components.interfaces.nsIDocumentEncoder);
+  const de = SpecialPowers.Ci.nsIDocumentEncoder;
+  var encoder = SpecialPowers.Cc["@mozilla.org/layout/htmlCopyEncoder;1"]
+                   .createInstance(SpecialPowers.Ci.nsIDocumentEncoder);
   var out, expected;
   
   var node = document.getElementById('draggable');
 
   var select = window.getSelection();
   select.removeAllRanges();
 
   node = document.getElementById("foo").firstChild;
--- a/content/base/test/test_bug401662.html
+++ b/content/base/test/test_bug401662.html
@@ -19,19 +19,18 @@ https://bugzilla.mozilla.org/show_bug.cg
 <pre id="test">
 <script class="testbody" type="text/javascript">
 
 /** Test for Bug 401662 - don't serialize style elements in body into
     plaintext**/
 SimpleTest.waitForExplicitFinish();
 
 window.onload = function() {
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-  const Cc = Components.classes;
-  const Ci = Components.interfaces;
+  const Cc = SpecialPowers.Cc;
+  const Ci = SpecialPowers.Ci;
 
   var encoder = Cc["@mozilla.org/layout/documentEncoder;1?type=text/html"]
                    .createInstance(Ci.nsIDocumentEncoder);
 
   var doc = $("testframe").contentDocument;
 
   encoder.init(doc, "text/plain", encoder.OutputBodyOnly);
   encoder.setCharset("UTF-8");
--- a/content/base/test/test_bug403852.html
+++ b/content/base/test/test_bug403852.html
@@ -18,18 +18,18 @@ https://bugzilla.mozilla.org/show_bug.cg
 <div id="content" style="display: none">
 </div>
 
 <pre id="test">
 <script class="testbody" type="text/javascript">
 
 netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
 
-var dirSvc = Components.classes["@mozilla.org/file/directory_service;1"].getService(Components.interfaces.nsIProperties);
-var testFile = dirSvc.get("ProfD", Components.interfaces.nsIFile);
+var dirSvc = SpecialPowers.Cc["@mozilla.org/file/directory_service;1"].getService(SpecialPowers.Ci.nsIProperties);
+var testFile = dirSvc.get("ProfD", SpecialPowers.Ci.nsIFile);
 testFile.append("prefs.js");
 
 var fileList = document.getElementById('fileList');
 fileList.value = testFile.path;
 
 // Make sure the file is accessible with indexed notation
 var domFile = fileList.files[0];
 
--- a/content/base/test/test_bug417384.html
+++ b/content/base/test/test_bug417384.html
@@ -16,31 +16,29 @@ https://bugzilla.mozilla.org/show_bug.cg
 </div>
 <pre id="test">
 <script class="testbody" type="text/javascript">
 
 /** Test for Bug 417384 **/
 
 var expectedSerialization = "about:blank document";
 function testSerializer() {
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-
   var doc = document.getElementById('test_iframe').contentDocument;
   doc.body.textContent = expectedSerialization;
   var head1 = doc.createElement("head");
   doc.body.appendChild(head1);
   var span = doc.createElement("span");
   head1.appendChild(span);
   span.appendChild(doc.createTextNode("before inner head\n"));
   span.appendChild(doc.createElement("head"));
   span.appendChild(doc.createTextNode("\nafter inner head"));
 
   var encoder =
-    Components.classes["@mozilla.org/layout/documentEncoder;1?type=text/html"]
-      .createInstance(Components.interfaces.nsIDocumentEncoder);
+    SpecialPowers.Cc["@mozilla.org/layout/documentEncoder;1?type=text/html"]
+      .createInstance(SpecialPowers.Ci.nsIDocumentEncoder);
   encoder.init(doc, "text/plain", 0);
   encoder.setCharset("UTF-8");
   var out = encoder.encodeToString();
   ok(out == expectedSerialization, "Wrong serialization!");
 }
 
 SimpleTest.waitForExplicitFinish();
 addLoadEvent(testSerializer);
--- a/content/base/test/test_bug422403-2.xhtml
+++ b/content/base/test/test_bug422403-2.xhtml
@@ -18,42 +18,41 @@
 <script class="testbody" type="text/javascript">
 //<![CDATA[
 
 function loadFileContent(aFile, aCharset) {
     //if(aAsIso == undefined) aAsIso = false;
     if(aCharset == undefined)
         aCharset = 'UTF-8';
 
-    var baseUri = Components.classes['@mozilla.org/network/standard-url;1']
-                   .createInstance(Components.interfaces.nsIURI);
+    var baseUri = SpecialPowers.Cc['@mozilla.org/network/standard-url;1']
+                   .createInstance(SpecialPowers.Ci.nsIURI);
     baseUri.spec = window.location.href;
 
-    var ios = Components.classes['@mozilla.org/network/io-service;1']
-            .getService(Components.interfaces.nsIIOService);
+    var ios = SpecialPowers.Cc['@mozilla.org/network/io-service;1']
+            .getService(SpecialPowers.Ci.nsIIOService);
     var chann = ios.newChannel(aFile, aCharset, baseUri);
 
-    var cis = Components.interfaces.nsIConverterInputStream;
+    var cis = SpecialPowers.Ci.nsIConverterInputStream;
 
-    var inputStream = Components.classes["@mozilla.org/intl/converter-input-stream;1"]
+    var inputStream = SpecialPowers.Cc["@mozilla.org/intl/converter-input-stream;1"]
                        .createInstance(cis);
     inputStream.init(chann.open(), aCharset, 1024, cis.DEFAULT_REPLACEMENT_CHARACTER);
     var str = {}, content = '';
     while (inputStream.readString(4096, str) != 0) {
         content += str.value;
     }
     return content;
 }
 
 
 function testHtmlSerializer_1 () {
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-  const de = Components.interfaces.nsIDocumentEncoder
-  var encoder = Components.classes["@mozilla.org/layout/documentEncoder;1?type=application/xhtml+xml"]
-                   .createInstance(Components.interfaces.nsIDocumentEncoder);
+  const de = SpecialPowers.Ci.nsIDocumentEncoder
+  var encoder = SpecialPowers.Cc["@mozilla.org/layout/documentEncoder;1?type=application/xhtml+xml"]
+                   .createInstance(SpecialPowers.Ci.nsIDocumentEncoder);
 
   var doc = $("testframe").contentDocument;
   var out, expected;
 
   // in the following tests, we must use the OutputLFLineBreak flag, to avoid
   // to have the default line break of the platform in the result, so the test
   // can pass on all platform
 
--- a/content/base/test/test_bug424359-1.html
+++ b/content/base/test/test_bug424359-1.html
@@ -18,47 +18,46 @@
 <script class="testbody" type="text/javascript">
 
 
 function loadFileContent(aFile, aCharset) {
     //if(aAsIso == undefined) aAsIso = false;
     if(aCharset == undefined)
         aCharset = 'UTF-8';
 
-    var baseUri = Components.classes['@mozilla.org/network/standard-url;1']
-                   .createInstance(Components.interfaces.nsIURI);
+    var baseUri = SpecialPowers.Cc['@mozilla.org/network/standard-url;1']
+                   .createInstance(SpecialPowers.Ci.nsIURI);
     baseUri.spec = window.location.href;
 
-    var ios = Components.classes['@mozilla.org/network/io-service;1']
-            .getService(Components.interfaces.nsIIOService);
+    var ios = SpecialPowers.Cc['@mozilla.org/network/io-service;1']
+            .getService(SpecialPowers.Ci.nsIIOService);
     var chann = ios.newChannel(aFile, aCharset, baseUri);
 
-    var cis = Components.interfaces.nsIConverterInputStream;
+    var cis = SpecialPowers.Ci.nsIConverterInputStream;
 
-    var inputStream = Components.classes["@mozilla.org/intl/converter-input-stream;1"]
+    var inputStream = SpecialPowers.Cc["@mozilla.org/intl/converter-input-stream;1"]
                        .createInstance(cis);
     inputStream.init(chann.open(), aCharset, 1024, cis.DEFAULT_REPLACEMENT_CHARACTER);
     var str = {}, content = '';
     while (inputStream.readString(4096, str) != 0) {
         content += str.value;
     }
     return content;
 }
 
 function isRoughly(actual, expected, message) {
   return is(actual.replace("<!DOCTYPE HTML", "<!DOCTYPE html"), 
             expected, 
             message);
 }
 
 function testHtmlSerializer_1 () {
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-  const de = Components.interfaces.nsIDocumentEncoder
-  var encoder = Components.classes["@mozilla.org/layout/documentEncoder;1?type=text/html"]
-                   .createInstance(Components.interfaces.nsIDocumentEncoder);
+  const de = SpecialPowers.Ci.nsIDocumentEncoder;
+  var encoder = SpecialPowers.Cc["@mozilla.org/layout/documentEncoder;1?type=text/html"]
+                   .createInstance(SpecialPowers.Ci.nsIDocumentEncoder);
 
   var doc = $("testframe").contentDocument;
   var out, expected;
 
   // in the following tests, we must use the OutputLFLineBreak flag, to avoid
   // to have the default line break of the platform in the result, so the test
   // can pass on all platform
 
--- a/content/base/test/test_bug424359-2.html
+++ b/content/base/test/test_bug424359-2.html
@@ -18,47 +18,46 @@
 <script class="testbody" type="text/javascript">
 
 
 function loadFileContent(aFile, aCharset) {
     //if(aAsIso == undefined) aAsIso = false;
     if(aCharset == undefined)
         aCharset = 'UTF-8';
 
-    var baseUri = Components.classes['@mozilla.org/network/standard-url;1']
-                   .createInstance(Components.interfaces.nsIURI);
+    var baseUri = SpecialPowers.Cc['@mozilla.org/network/standard-url;1']
+                   .createInstance(SpecialPowers.Ci.nsIURI);
     baseUri.spec = window.location.href;
 
-    var ios = Components.classes['@mozilla.org/network/io-service;1']
-            .getService(Components.interfaces.nsIIOService);
+    var ios = SpecialPowers.Cc['@mozilla.org/network/io-service;1']
+            .getService(SpecialPowers.Ci.nsIIOService);
     var chann = ios.newChannel(aFile, aCharset, baseUri);
 
-    var cis = Components.interfaces.nsIConverterInputStream;
+    var cis = SpecialPowers.Ci.nsIConverterInputStream;
 
-    var inputStream = Components.classes["@mozilla.org/intl/converter-input-stream;1"]
+    var inputStream = SpecialPowers.Cc["@mozilla.org/intl/converter-input-stream;1"]
                        .createInstance(cis);
     inputStream.init(chann.open(), aCharset, 1024, cis.DEFAULT_REPLACEMENT_CHARACTER);
     var str = {}, content = '';
     while (inputStream.readString(4096, str) != 0) {
         content += str.value;
     }
     return content;
 }
 
 function isRoughly(actual, expected, message) {
   return is(actual.replace("<!DOCTYPE HTML", "<!DOCTYPE html"), 
             expected, 
             message);
 }
 
 function testHtmlSerializer_1 () {
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-  const de = Components.interfaces.nsIDocumentEncoder
-  var encoder = Components.classes["@mozilla.org/layout/documentEncoder;1?type=text/html"]
-                   .createInstance(Components.interfaces.nsIDocumentEncoder);
+  const de = SpecialPowers.Ci.nsIDocumentEncoder;
+  var encoder = SpecialPowers.Cc["@mozilla.org/layout/documentEncoder;1?type=text/html"]
+                   .createInstance(SpecialPowers.Ci.nsIDocumentEncoder);
 
   var doc = $("testframe").contentDocument;
   var out, expected;
 
   // in the following tests, we must use the OutputLFLineBreak flag, to avoid
   // to have the default line break of the platform in the result, so the test
   // can pass on all platform
 
--- a/content/base/test/test_bug498433.html
+++ b/content/base/test/test_bug498433.html
@@ -17,47 +17,46 @@
 <pre id="test">
 <script class="testbody" type="text/javascript">
 
 
 function loadFileContent(aFile, aCharset) {
     if (aCharset == undefined)
         aCharset = 'UTF-8';
 
-    var baseUri = Components.classes['@mozilla.org/network/standard-url;1']
-                   .createInstance(Components.interfaces.nsIURI);
+    var baseUri = SpecialPowers.Cc['@mozilla.org/network/standard-url;1']
+                   .createInstance(SpecialPowers.Ci.nsIURI);
     baseUri.spec = window.location.href;
 
-    var ios = Components.classes['@mozilla.org/network/io-service;1']
-            .getService(Components.interfaces.nsIIOService);
+    var ios = SpecialPowers.Cc['@mozilla.org/network/io-service;1']
+            .getService(SpecialPowers.Ci.nsIIOService);
     var chann = ios.newChannel(aFile, aCharset, baseUri);
 
-    var cis = Components.interfaces.nsIConverterInputStream;
+    var cis = SpecialPowers.Ci.nsIConverterInputStream;
 
-    var inputStream = Components.classes["@mozilla.org/intl/converter-input-stream;1"]
+    var inputStream = SpecialPowers.Cc["@mozilla.org/intl/converter-input-stream;1"]
                        .createInstance(cis);
     inputStream.init(chann.open(), aCharset, 1024, cis.DEFAULT_REPLACEMENT_CHARACTER);
     var str = {}, content = '';
     while (inputStream.readString(4096, str) != 0) {
         content += str.value;
     }
     return content;
 }
 
 function isRoughly(actual, expected, message) {
   return is(actual.replace("<!DOCTYPE HTML", "<!DOCTYPE html"), 
             expected, 
             message);
 }
 
 function testHtmlSerializer_1 () {
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-  const de = Components.interfaces.nsIDocumentEncoder
-  var encoder = Components.classes["@mozilla.org/layout/documentEncoder;1?type=text/html"]
-                   .createInstance(Components.interfaces.nsIDocumentEncoder);
+  const de = SpecialPowers.Ci.nsIDocumentEncoder;
+  var encoder = SpecialPowers.Cc["@mozilla.org/layout/documentEncoder;1?type=text/html"]
+                   .createInstance(SpecialPowers.Ci.nsIDocumentEncoder);
 
   var doc = $("testframe").contentDocument;
   var out, expected;
 
   // in the following tests, we must use the OutputLFLineBreak flag, to avoid
   // to have the default line break of the platform in the result, so the test
   // can pass on all platform
 
--- a/content/base/test/test_bug498897.html
+++ b/content/base/test/test_bug498897.html
@@ -18,84 +18,74 @@ https://bugzilla.mozilla.org/show_bug.cg
 <script type="application/javascript">
 
 /** Test for Bug 498897 **/
 
 var checkedLoad = false;
 
 netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
 
-const Cc = Components.classes;
-const Ci = Components.interfaces;
+const Cc = SpecialPowers.Cc;
+const Ci = SpecialPowers.Ci;
 
 // Content policy / factory implementation for the test
-var policyID = Components.ID("{65944d64-2390-422e-bea3-80d0af7f69ef}");
+var policyID = SpecialPowers.wrap(SpecialPowers.Components).ID("{65944d64-2390-422e-bea3-80d0af7f69ef}");
 var policyName = "@mozilla.org/498897_testpolicy;1";
 var policy = {
   // nsISupports implementation
   QueryInterface: function(iid) {
-    netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-
     if (iid.equals(Ci.nsISupports) ||
         iid.equals(Ci.nsIFactory) ||
         iid.equals(Ci.nsIContentPolicy))
       return this;
 
-    throw Components.results.NS_ERROR_NO_INTERFACE;
+    throw SpecialPowers.Cr.NS_ERROR_NO_INTERFACE;
   },
 
   // nsIFactory implementation
   createInstance: function(outer, iid) {
     return this.QueryInterface(iid);
   },
 
   // nsIContentPolicy implementation
   shouldLoad: function(contentType, contentLocation, requestOrigin, context,
                        mimeTypeGuess, extra) {
-    netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-
     if (contentLocation instanceof Ci.nsIURL &&
         contentLocation.fileName == "file_bug498897.css" &&
         requestOrigin instanceof Ci.nsIURL &&
         requestOrigin.fileName == "file_bug498897.html") {
       checkedLoad = true;
     }
 
     return Ci.nsIContentPolicy.ACCEPT;
   },
 
   shouldProcess: function(contentType, contentLocation, requestOrigin, context,
                           mimeTypeGuess, extra) {
-    netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-
     return Ci.nsIContentPolicy.ACCEPT;
   }
 }
 
-var componentManager = Components.manager
+var componentManager = SpecialPowers.wrap(SpecialPowers.Components).manager
                                  .QueryInterface(Ci.nsIComponentRegistrar);
 componentManager.registerFactory(policyID, "Test content policy for bug 498897",
                                  policyName, policy);
 
 var categoryManager =
   Cc["@mozilla.org/categorymanager;1"].getService(Ci.nsICategoryManager);
 categoryManager.addCategoryEntry("content-policy", policyName, policyName,
                                  false, true);
 
 function testFinished()
 {
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-
   ok(checkedLoad, "Content policy didn't get called!");
 
   categoryManager.deleteCategoryEntry("content-policy", policyName, false);
 
   setTimeout(function() {
-    netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-
     componentManager.unregisterFactory(policyID, policy);
 
     SimpleTest.finish();
   }, 0);
 }
 
 SimpleTest.waitForExplicitFinish();
 
--- a/content/base/test/test_bug541937.html
+++ b/content/base/test/test_bug541937.html
@@ -16,20 +16,19 @@
   <iframe id="testframe2" src="file_bug541937.xhtml">
   </iframe>
 </div>
 
 <pre id="test">
 <script class="testbody" type="text/javascript">
 
 function testSerializer () {
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-  const de = Components.interfaces.nsIDocumentEncoder
-  var encoder = Components.classes["@mozilla.org/layout/documentEncoder;1?type=text/html"]
-                   .createInstance(Components.interfaces.nsIDocumentEncoder);
+  const de = SpecialPowers.Ci.nsIDocumentEncoder;
+  var encoder = SpecialPowers.Cc["@mozilla.org/layout/documentEncoder;1?type=text/html"]
+                   .createInstance(SpecialPowers.Ci.nsIDocumentEncoder);
 
   var parser = new DOMParser();
   var serializer = new XMLSerializer();
 
   // with content
   var str = '<?xml version="1.0"?><doc>\n<link xmlns="http://www.w3.org/1999/xhtml"><!-- child nodes -->  \n<content xmlns=""/></link>\n</doc>';
   var expected = '<?xml version="1.0" encoding="UTF-8"?>\n<doc>\n<link xmlns="http://www.w3.org/1999/xhtml"><!-- child nodes -->  \n<content xmlns=""/></link>\n</doc>';
 
--- a/content/base/test/test_bug578096.html
+++ b/content/base/test/test_bug578096.html
@@ -12,34 +12,31 @@ https://bugzilla.mozilla.org/show_bug.cg
 <body>
 <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=578096">Mozilla Bug 578096</a>
 <p id="display"></p>
 <div id="content">
    <input type="file" id="file" onchange="fireXHR()">
 </div>
 <pre id="test">
 <script class="testbody" type="text/javascript">
-netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
-
-const Cc = Components.classes;
-const Ci = Components.interfaces;
+const Cc = SpecialPowers.Cc;
+const Ci = SpecialPowers.Ci;
 
 var file = Cc["@mozilla.org/file/directory_service;1"]
            .getService(Ci.nsIProperties)
            .get("TmpD", Ci.nsIFile);
 file.append("foo.txt");
 file.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, 0600);
 
 SimpleTest.waitForExplicitFinish();
-document.getElementById('file').value = file.path;
+SpecialPowers.wrap(document.getElementById('file')).value = file.path;
 
 var xhr = new XMLHttpRequest();
 xhr.onreadystatechange = function(event) {
   if (xhr.readyState == 4) {
-    netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
     file.remove(false);
     ok(true, "We didn't throw! Yay!");
     SimpleTest.finish();
   }
 }
 xhr.open('POST', window.location, true);
 xhr.send(document.getElementById('file').files[0]);
 </script>
--- a/content/base/test/test_copyimage.html
+++ b/content/base/test/test_copyimage.html
@@ -11,35 +11,34 @@
 <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=518249">Mozilla Bug 518249</a>
 <p id="display"></p>
 <div id="content" style="display: none">
 </div>
 <pre id="test">
 <script class="testbody" type="text/javascript">
 
 function testCopyImage () {
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-
   // selection of the node
   var node = document.getElementById('logo');
-  var webnav = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
-                     .getInterface(Components.interfaces.nsIWebNavigation)
+  var webnav = SpecialPowers.wrap(window)
+               .QueryInterface(SpecialPowers.Ci.nsIInterfaceRequestor)
+               .getInterface(SpecialPowers.Ci.nsIWebNavigation)
 
-  var docShell = webnav.QueryInterface(Components.interfaces.nsIDocShell);
+  var docShell = webnav.QueryInterface(SpecialPowers.Ci.nsIDocShell);
 
   docShell.chromeEventHandler.ownerDocument.popupNode = node;
 
   // let's copy the node
   var documentViewer = docShell.contentViewer
-                               .QueryInterface(Components.interfaces.nsIContentViewerEdit);
+                               .QueryInterface(SpecialPowers.Ci.nsIContentViewerEdit);
   documentViewer.copyImage(documentViewer.COPY_IMAGE_ALL);
   
   //--------- now check the content of the clipboard
-  var clipboard = Components.classes["@mozilla.org/widget/clipboard;1"]
-                            .getService(Components.interfaces.nsIClipboard);
+  var clipboard = SpecialPowers.Cc["@mozilla.org/widget/clipboard;1"]
+                               .getService(SpecialPowers.Ci.nsIClipboard);
   
   // does the clipboard contain text/unicode data ?
   ok(clipboard.hasDataMatchingFlavors(["text/unicode"], 1, clipboard.kGlobalClipboard), "clipboard contains unicode text");
   // does the clipboard contain text/html data ?
   ok(clipboard.hasDataMatchingFlavors(["text/html"], 1, clipboard.kGlobalClipboard), "clipboard contains html text");
   // does the clipboard contain image data ?
   ok(clipboard.hasDataMatchingFlavors(["image/png"], 1, clipboard.kGlobalClipboard), "clipboard contains image");
 
--- a/content/base/test/test_fileapi.html
+++ b/content/base/test/test_fileapi.html
@@ -28,17 +28,16 @@ try {
   ok(true, "Threw on an unprivileged attempt to construct a File");
 }
 
 const minFileSize = 20000;
 var fileNum = 1;
 var testRanCounter = 0;
 var expectedTestCount = 0;
 SimpleTest.waitForExplicitFinish();
-netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
 
 is(FileReader.EMPTY, 0, "correct EMPTY value");
 is(FileReader.LOADING, 1, "correct LOADING value");
 is(FileReader.DONE, 2, "correct DONE value");
 
 // Create strings containing data we'll test with. We'll want long
 // strings to ensure they span multiple buffers while loading
 var testTextData = "asd b\tlah\u1234w\u00a0r";
@@ -60,17 +59,17 @@ while (testBinaryData.length < minFileSi
 }
 
 
 //Set up files for testing
 var asciiFile = createFileWithData(testASCIIData);
 var binaryFile = createFileWithData(testBinaryData);
 
 var fileList = document.getElementById('fileList');
-fileList.value = "/none/existing/path/fileAPI/testing";
+SpecialPowers.wrap(fileList).value = "/none/existing/path/fileAPI/testing";
 var nonExistingFile = fileList.files[0];
 
 // Test that plain reading works and fires events as expected, both
 // for text and binary reading
 
 var onloadHasRunText = false;
 var onloadStartHasRunText = false;
 r = new FileReader();
@@ -419,28 +418,28 @@ function testHasRun() {
  if (testRanCounter == expectedTestCount) {
     is(onloadHasRunText, true, "onload text should have fired by now"); 
     is(onloadHasRunBinary, true, "onload binary should have fired by now"); 
     SimpleTest.finish();
   }
 }
 
 function createFileWithData(fileData) {
-  var dirSvc = Components.classes["@mozilla.org/file/directory_service;1"].getService(Components.interfaces.nsIProperties);
-  var testFile = dirSvc.get("ProfD", Components.interfaces.nsIFile);
+  var dirSvc = SpecialPowers.Cc["@mozilla.org/file/directory_service;1"].getService(SpecialPowers.Ci.nsIProperties);
+  var testFile = dirSvc.get("ProfD", SpecialPowers.Ci.nsIFile);
   testFile.append("fileAPItestfile" + fileNum);
   fileNum++;
-  var outStream = Components.classes["@mozilla.org/network/file-output-stream;1"].createInstance(Components.interfaces.nsIFileOutputStream);
+  var outStream = SpecialPowers.Cc["@mozilla.org/network/file-output-stream;1"].createInstance(SpecialPowers.Ci.nsIFileOutputStream);
   outStream.init(testFile, 0x02 | 0x08 | 0x20, // write, create, truncate
                  0666, 0);
   outStream.write(fileData, fileData.length);
   outStream.close();
 
   var fileList = document.getElementById('fileList');
-  fileList.value = testFile.path;
+  SpecialPowers.wrap(fileList).value = testFile.path;
 
   return fileList.files[0];
 }
 
 function convertToUTF16(s) {
   res = "";
   for (var i = 0; i < s.length; ++i) {
     c = s.charCodeAt(i);
--- a/content/base/test/test_htmlcopyencoder.html
+++ b/content/base/test/test_htmlcopyencoder.html
@@ -11,20 +11,19 @@
 <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=422403">Mozilla Bug </a>
 <p id="display"></p>
 <div id="content" style="display: none">
 </div>
 <pre id="test">
 <script class="testbody" type="text/javascript">
 
 function testHtmlCopyEncoder () {
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-  const de = Components.interfaces.nsIDocumentEncoder;
-  var encoder = Components.classes["@mozilla.org/layout/htmlCopyEncoder;1"]
-                   .createInstance(Components.interfaces.nsIDocumentEncoder);
+  const de = SpecialPowers.Ci.nsIDocumentEncoder;
+  var encoder = SpecialPowers.Cc["@mozilla.org/layout/htmlCopyEncoder;1"]
+                   .createInstance(SpecialPowers.Ci.nsIDocumentEncoder);
   var out, expected;
 
   var node = document.getElementById('draggable');
 
 
   // in the following tests, we must use the OutputLFLineBreak flag, to avoid
   // to have the default line break of the platform in the result, so the test
   // can pass on all platform
--- a/content/base/test/test_htmlcopyencoder.xhtml
+++ b/content/base/test/test_htmlcopyencoder.xhtml
@@ -11,20 +11,19 @@
 <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=422403">Mozilla Bug </a>
 <p id="display"></p>
 <div id="content" style="display: none">
 </div>
 <pre id="test">
 <script class="testbody" type="text/javascript">
 //<![CDATA[
 function testHtmlCopyEncoder () {
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-  const de = Components.interfaces.nsIDocumentEncoder;
-  var encoder = Components.classes["@mozilla.org/layout/htmlCopyEncoder;1"]
-                   .createInstance(Components.interfaces.nsIDocumentEncoder);
+  const de = SpecialPowers.Ci.nsIDocumentEncoder;
+  var encoder = SpecialPowers.Cc["@mozilla.org/layout/htmlCopyEncoder;1"]
+                   .createInstance(SpecialPowers.Ci.nsIDocumentEncoder);
   var out, expected;
 
   var node = document.getElementById('draggable');
 
 
   // in the following tests, we must use the OutputLFLineBreak flag, to avoid
   // to have the default line break of the platform in the result, so the test
   // can pass on all platform
--- a/content/base/test/test_websocket.html
+++ b/content/base/test/test_websocket.html
@@ -1220,25 +1220,25 @@ function test41()
         wsc.close();
       }
 
       wsc.onclose = function(e)
       {
         ok(true, "test 41c close");
 
         // clean up the STS state
-        netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
-        const Cc = Components.classes;
-        const Ci = Components.interfaces;
+        const Cc = SpecialPowers.Cc;
+        const Ci = SpecialPowers.Ci;
         var ios = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);
         var thehost = ios.newURI("http://example.com", null, null);
         var sss = Cc["@mozilla.org/ssservice;1"].getService(Ci.nsISiteSecurityService);
-        var loadContext = window.QueryInterface(Ci.nsIInterfaceRequestor)
-                                .getInterface(Ci.nsIWebNavigation)
-                                .QueryInterface(Ci.nsILoadContext);
+        var loadContext = SpecialPowers.wrap(window)
+                          .QueryInterface(Ci.nsIInterfaceRequestor)
+                          .getInterface(Ci.nsIWebNavigation)
+                          .QueryInterface(Ci.nsILoadContext);
         var flags = 0;
         if (loadContext.usePrivateBrowsing)
           flags |= Ci.nsISocketProvider.NO_PERMANENT_STORAGE;
         sss.removeState(Ci.nsISiteSecurityService.HEADER_HSTS, thehost, flags);
         doTest(42);
        }
      }
   }
@@ -1333,34 +1333,30 @@ function test44()
     ok(ws.readyState == 3, "onclose bad readyState in test-44!");
     shouldCloseCleanly(e);
     doTest(45);
   }
 }
 
 function createDOMFile(fileName, fileData)
 {
-  // enablePrivilege is picky about where it's called? if I put it in global
-  // scope at start of  <script> it doesn't work...
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-
   // create File in profile dir 
-  var dirSvc = Components.classes["@mozilla.org/file/directory_service;1"]
-                         .getService(Components.interfaces.nsIProperties);
-  var testFile = dirSvc.get("ProfD", Components.interfaces.nsIFile);
+  var dirSvc = SpecialPowers.Cc["@mozilla.org/file/directory_service;1"]
+                         .getService(SpecialPowers.Ci.nsIProperties);
+  var testFile = dirSvc.get("ProfD", SpecialPowers.Ci.nsIFile);
   testFile.append(fileName);
-  var outStream = Components.classes["@mozilla.org/network/file-output-stream;1"]
-                            .createInstance(Components.interfaces.nsIFileOutputStream);
+  var outStream = SpecialPowers.Cc["@mozilla.org/network/file-output-stream;1"]
+                            .createInstance(SpecialPowers.Ci.nsIFileOutputStream);
   outStream.init(testFile, 0x02 | 0x08 | 0x20, 0666, 0);
   outStream.write(fileData, fileData.length);
   outStream.close();
 
   // Set filename into DOM <input> field, as if selected by user 
   var fileList = document.getElementById('fileList');
-  fileList.value = testFile.path;
+  SpecialPowers.wrap(fileList).value = testFile.path;
 
   // return JS File object, aka Blob
   return fileList.files[0];
 }
 
 function test45()
 {
   var blobFile = createDOMFile("testBlobFile", "flob");
--- a/content/base/test/websocket_hybi/test_send-blob.html
+++ b/content/base/test/websocket_hybi/test_send-blob.html
@@ -17,36 +17,32 @@
 
 function startsWith(target, prefix)
 {
     return target.indexOf(prefix) === 0;
 }
 
 function createDOMFile(fileName, fileData)
 {
-    // enablePrivilege is picky about where it's called? if I put it in global
-    // scope at start of  <script> it doesn't work...
-    netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-
     // create File in profile dir 
-    var dirSvc = Components.classes["@mozilla.org/file/directory_service;1"]
-                         .getService(Components.interfaces.nsIProperties);
-    var testFile = dirSvc.get("ProfD", Components.interfaces.nsIFile);
+    var dirSvc = SpecialPowers.Cc["@mozilla.org/file/directory_service;1"]
+                         .getService(SpecialPowers.Ci.nsIProperties);
+    var testFile = dirSvc.get("ProfD", SpecialPowers.Ci.nsIFile);
     testFile.append(fileName);
-    var outStream = Components.classes["@mozilla.org/network/file-output-stream;1"]
-                               .createInstance(Components.interfaces.nsIFileOutputStream);
+    var outStream = SpecialPowers.Cc["@mozilla.org/network/file-output-stream;1"]
+                               .createInstance(SpecialPowers.Ci.nsIFileOutputStream);
     outStream.init(testFile, 0x02 | 0x08 | 0x20, 0666, 0);
     if (fileData) {
         outStream.write(fileData, fileData.length);
         outStream.close();
     } 
 
     // Set filename into DOM <input> field, as if selected by user 
     var fileList = document.getElementById('fileList');
-    fileList.value = testFile.path;
+    SpecialPowers.wrap(fileList).value = testFile.path;
 
     // return JS File object, aka Blob
     return fileList.files[0];
 }
 
 
 function createBlobContainingHelloWorld()
 {
--- a/content/events/test/test_bug336682.js
+++ b/content/events/test/test_bug336682.js
@@ -59,19 +59,18 @@ function makeHandler(nameTemplate, event
     ok(!e.cancelable, "event should not be cancelable");
     ok(e.target == (document instanceof HTMLDocument
                     ? document.body : document.documentElement),
        "the event target should be the body element");
   }
 }
 
 function doTest() {
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-  var iosvc = Components.classes["@mozilla.org/network/io-service;1"]
-                        .getService(Components.interfaces.nsIIOService2);
+  var iosvc = SpecialPowers.Cc["@mozilla.org/network/io-service;1"]
+                           .getService(SpecialPowers.Ci.nsIIOService2);
   iosvc.manageOfflineStatus = false;
   iosvc.offline = false;
   ok(navigator.onLine, "navigator.onLine should be true, since we've just " +
                        "set nsIIOService.offline to false");
 
   gState = 0;
 
   trace("setting iosvc.offline = true");
--- a/content/events/test/test_bug508479.html
+++ b/content/events/test/test_bug508479.html
@@ -8,27 +8,25 @@
 <script>
   
 var gGotHandlingDrop = false;
 var gGotNotHandlingDrop = false;
 
 SimpleTest.waitForExplicitFinish();
 
 function fireEvent(target, event) {
-  netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
   var utils =
-    window.QueryInterface(Components.interfaces.nsIInterfaceRequestor).
-           getInterface(Components.interfaces.nsIDOMWindowUtils);
-  utils.dispatchDOMEventViaPresShell(target, event, true);
+    window.QueryInterface(SpecialPowers.Ci.nsIInterfaceRequestor).
+           getInterface(SpecialPowers.Ci.nsIDOMWindowUtils);
+  SpecialPowers.wrap(utils).dispatchDOMEventViaPresShell(target, event, true);
 }
 
 function fireDrop(element, shouldAllowDrop, shouldAllowOnlyChromeDrop) {
-  netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
-  var ds = Components.classes["@mozilla.org/widget/dragservice;1"].
-    getService(Components.interfaces.nsIDragService);
+  var ds = SpecialPowers.Cc["@mozilla.org/widget/dragservice;1"].
+    getService(SpecialPowers.Ci.nsIDragService);
 
   var dataTransfer;
   var trapDrag = function(event) {
     dataTransfer = event.dataTransfer;
     dataTransfer.setData("text/plain", "Hello");;
     dataTransfer.dropEffect = "move";
     event.preventDefault();
     event.stopPropagation();
--- a/content/html/content/test/forms/test_formnovalidate_attribute.html
+++ b/content/html/content/test/forms/test_formnovalidate_attribute.html
@@ -41,19 +41,18 @@ https://bugzilla.mozilla.org/show_bug.cg
     <button id='e' type='submit' formnovalidate></button>
   </form>
 </div>
 <pre id="test">
 <script type="application/javascript">
 
 /** Test for Bug 589696 **/
 
-netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
-var os = Components.classes['@mozilla.org/observer-service;1']
-                   .getService(Components.interfaces.nsIObserverService);
+var os = SpecialPowers.Cc['@mozilla.org/observer-service;1']
+                      .getService(SpecialPowers.Ci.nsIObserverService);
 var observers = os.enumerateObservers("invalidformsubmit");
 
 /**
  * formnovalidate should prevent form validation if set on the submit control
  * used to submit the form.
  *
  * The following test should not be done if there is no observer for
  * "invalidformsubmit" because the form submission will not be canceled in that
--- a/content/html/content/test/forms/test_max_attribute.html
+++ b/content/html/content/test/forms/test_max_attribute.html
@@ -167,31 +167,28 @@ for (var test of data) {
       input.value = 'http://mozilla.org';
       checkValidity(input, true, apply, apply);
       break;
     case 'email':
       input.value = 'foo@bar.com';
       checkValidity(input, true, apply, apply);
       break;
     case 'file':
-      // Need privileges to set a filename with .value.
-      netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-
-      var dirSvc = Components.classes["@mozilla.org/file/directory_service;1"]
-                             .getService(Components.interfaces.nsIProperties);
-      var file = dirSvc.get("ProfD", Components.interfaces.nsIFile);
+      var dirSvc = SpecialPowers.Cc["@mozilla.org/file/directory_service;1"]
+                                .getService(SpecialPowers.Ci.nsIProperties);
+      var file = dirSvc.get("ProfD", SpecialPowers.Ci.nsIFile);
       file.append('635499_file');
-      var outStream = Components.classes["@mozilla.org/network/file-output-stream;1"].
-                      createInstance(Components.interfaces.nsIFileOutputStream);
+      var outStream = SpecialPowers.Cc["@mozilla.org/network/file-output-stream;1"].
+                      createInstance(SpecialPowers.Ci.nsIFileOutputStream);
       outStream.init(file, 0x02 | 0x08 | 0x20, // write, create, truncate
                      0666, 0);
       outStream.write("foo", 3);
       outStream.close();
 
-      input.value = file.path;
+      SpecialPowers.wrap(input).value = file.path;
       checkValidity(input, true, apply, apply);
 
       file.remove(false);
       break;
     case 'date':
       input.max = '2012-06-27';
       input.value = '2012-06-26';
       checkValidity(input, true, apply, apply);
--- a/content/html/content/test/forms/test_min_attribute.html
+++ b/content/html/content/test/forms/test_min_attribute.html
@@ -165,31 +165,28 @@ for (var test of data) {
       input.value = 'http://mozilla.org';
       checkValidity(input, true, apply, apply);
       break;
     case 'email':
       input.value = 'foo@bar.com';
       checkValidity(input, true, apply, apply);
       break;
     case 'file':
-      // Need privileges to set a filename with .value.
-      netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-
-      var dirSvc = Components.classes["@mozilla.org/file/directory_service;1"]
-                             .getService(Components.interfaces.nsIProperties);
-      var file = dirSvc.get("ProfD", Components.interfaces.nsIFile);
+      var dirSvc = SpecialPowers.Cc["@mozilla.org/file/directory_service;1"]
+                                .getService(SpecialPowers.Ci.nsIProperties);
+      var file = dirSvc.get("ProfD", SpecialPowers.Ci.nsIFile);
       file.append('635499_file');
-      var outStream = Components.classes["@mozilla.org/network/file-output-stream;1"].
-                      createInstance(Components.interfaces.nsIFileOutputStream);
+      var outStream = SpecialPowers.Cc["@mozilla.org/network/file-output-stream;1"].
+                      createInstance(SpecialPowers.Ci.nsIFileOutputStream);
       outStream.init(file, 0x02 | 0x08 | 0x20, // write, create, truncate
                      0666, 0);
       outStream.write("foo", 3);
       outStream.close();
 
-      input.value = file.path;
+      SpecialPowers.wrap(input).value = file.path;
       checkValidity(input, true, apply, apply);
 
       file.remove(false);
       break;
     case 'date':
       input.value = '2012-06-28';
       checkValidity(input, true, apply, apply);
 
--- a/content/html/content/test/forms/test_required_attribute.html
+++ b/content/html/content/test/forms/test_required_attribute.html
@@ -79,59 +79,59 @@ function checkSufferingFromBeingMissing(
   is(element.mozMatchesSelector(':-moz-ui-invalid'), hasMozUIInvalid, ":-moz-ui-invalid expected state is " + hasMozUIInvalid);
 }
 
 function checkTextareaRequiredValidity()
 {
   var element = document.createElement('textarea');
   document.forms[0].appendChild(element);
 
-  element.value = '';
+  SpecialPowers.wrap(element).value = '';
   element.required = false;
   checkNotSufferingFromBeingMissing(element);
 
   element.required = true;
   checkSufferingFromBeingMissing(element, true);
 
   element.readOnly = true;
   checkNotSufferingFromBeingMissing(element, true);
 
   element.readOnly = false;
   checkSufferingFromBeingMissing(element, true);
 
-  element.value = 'foo';
+  SpecialPowers.wrap(element).value = 'foo';
   checkNotSufferingFromBeingMissing(element);
 
-  element.value = '';
+  SpecialPowers.wrap(element).value = '';
   checkSufferingFromBeingMissing(element, true);
 
   element.required = false;
   checkNotSufferingFromBeingMissing(element);
 
   element.focus();
   element.required = true;
-  element.value = 'foobar';
+  SpecialPowers.wrap(element).value = 'foobar';
   element.blur();
   element.form.reset();
   checkSufferingFromBeingMissing(element, false);
 
   // TODO: for the moment, a textarea outside of a document is mutable.
-  element.value = ''; // To make -moz-ui-valid apply.
+  SpecialPowers.wrap(element).value = ''; // To make -moz-ui-valid apply.
   element.required = false;
   document.forms[0].removeChild(element);
   checkNotSufferingFromBeingMissing(element);
 }
 
 function checkInputRequiredNotApply(type, isBarred)
 {
   var element = document.createElement('input');
   element.type = type;
   document.forms[0].appendChild(element);
 
-  element.value = '';
+  SpecialPowers.wrap(element).value = '';
   element.required = false;
   checkNotSufferingFromBeingMissing(element, isBarred);
 
   element.required = true;
   checkNotSufferingFromBeingMissing(element, isBarred);
 
   element.required = false;
 
@@ -140,56 +140,56 @@ function checkInputRequiredNotApply(type
 }
 
 function checkInputRequiredValidity(type)
 {
   var element = document.createElement('input');
   element.type = type;
   document.forms[0].appendChild(element);
 
-  element.value = '';
+  SpecialPowers.wrap(element).value = '';
   element.required = false;
   checkNotSufferingFromBeingMissing(element);
 
   element.required = true;
   checkSufferingFromBeingMissing(element, true);
 
   element.readOnly = true;
   checkNotSufferingFromBeingMissing(element, true);
 
   element.readOnly = false;
   checkSufferingFromBeingMissing(element, true);
 
   if (element.type == 'email') {
-    element.value = 'foo@bar.com';
+    SpecialPowers.wrap(element).value = 'foo@bar.com';
   } else if (element.type == 'url') {
-    element.value = 'http://mozilla.org/';
+    SpecialPowers.wrap(element).value = 'http://mozilla.org/';
   } else if (element.type == 'number') {
-    element.value = '42';
+    SpecialPowers.wrap(element).value = '42';
   } else if (element.type == 'date') {
-    element.value = '2010-10-10';
+    SpecialPowers.wrap(element).value = '2010-10-10';
   } else if (element.type == 'time') {
-    element.value = '21:21';
+    SpecialPowers.wrap(element).value = '21:21';
   } else {
-    element.value = 'foo';
+    SpecialPowers.wrap(element).value = 'foo';
   }
   checkNotSufferingFromBeingMissing(element);
 
-  element.value = '';
+  SpecialPowers.wrap(element).value = '';
   checkSufferingFromBeingMissing(element, true);
 
   element.focus();
   element.required = true;
-  element.value = 'foobar';
+  SpecialPowers.wrap(element).value = 'foobar';
   element.blur();
   element.form.reset();
   checkSufferingFromBeingMissing(element, false);
 
   element.required = true;
-  element.value = ''; // To make :-moz-ui-valid apply.
+  SpecialPowers.wrap(element).value = ''; // To make :-moz-ui-valid apply.
   document.forms[0].removeChild(element);
   checkNotSufferingFromBeingMissing(element);
 }
 
 function checkInputRequiredValidityForCheckbox()
 {
   var element = document.createElement('input');
   element.type = 'checkbox';
@@ -302,60 +302,57 @@ function checkInputRequiredValidityForRa
 
 function checkInputRequiredValidityForFile()
 {
   var element = document.createElement('input');
   element.type = 'file'
   document.forms[0].appendChild(element);
 
   function createFileWithData(fileName, fileData) {
-    var dirSvc = Components.classes["@mozilla.org/file/directory_service;1"]
-                           .getService(Components.interfaces.nsIProperties);
-    var testFile = dirSvc.get("ProfD", Components.interfaces.nsIFile);
+    var dirSvc = SpecialPowers.Cc["@mozilla.org/file/directory_service;1"]
+                              .getService(SpecialPowers.Ci.nsIProperties);
+    var testFile = dirSvc.get("ProfD", SpecialPowers.Ci.nsIFile);
     testFile.append(fileName);
-    var outStream = Components.classes["@mozilla.org/network/file-output-stream;1"].
-                    createInstance(Components.interfaces.nsIFileOutputStream);
+    var outStream = SpecialPowers.Cc["@mozilla.org/network/file-output-stream;1"].
+                    createInstance(SpecialPowers.Ci.nsIFileOutputStream);
     outStream.init(testFile, 0x02 | 0x08 | 0x20, // write, create, truncate
                    0666, 0);
     outStream.write(fileData, fileData.length);
     outStream.close();
 
     return testFile;
   }
 
-  // Need privileges to set a filename with .value.
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-
   var file = createFileWithData("345822_file", "file content");
 
-  element.value = "";
+  SpecialPowers.wrap(element).value = "";
   element.required = false;
   checkNotSufferingFromBeingMissing(element);
 
   element.required = true;
   checkSufferingFromBeingMissing(element, true);
 
-  element.value = file.path;
+  SpecialPowers.wrap(element).value = file.path;
   checkNotSufferingFromBeingMissing(element);
 
-  element.value = "";
+  SpecialPowers.wrap(element).value = "";
   checkSufferingFromBeingMissing(element, true);
 
   element.required = false;
   checkNotSufferingFromBeingMissing(element);
 
   element.focus();
-  element.value = file.path;
+  SpecialPowers.wrap(element).value = file.path;
   element.required = true;
   element.blur();
   element.form.reset();
   checkSufferingFromBeingMissing(element, false);
 
   element.required = true;
-  element.value = '';
+  SpecialPowers.wrap(element).value = '';
   file.remove(false);
   document.forms[0].removeChild(element);
   checkNotSufferingFromBeingMissing(element);
 }
 
 checkTextareaRequiredValidity();
 
 // The require attribute behavior depend of the input type.
--- a/content/html/content/test/forms/test_step_attribute.html
+++ b/content/html/content/test/forms/test_step_attribute.html
@@ -119,31 +119,28 @@ for (var test of data) {
       input.value = 'http://mozilla.org';
       checkValidity(input, true, apply);
       break;
     case 'email':
       input.value = 'foo@bar.com';
       checkValidity(input, true, apply);
       break;
     case 'file':
-      // Need privileges to set a filename with .value.
-      netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-
-      var dirSvc = Components.classes["@mozilla.org/file/directory_service;1"]
-                             .getService(Components.interfaces.nsIProperties);
-      var file = dirSvc.get("ProfD", Components.interfaces.nsIFile);
+      var dirSvc = SpecialPowers.Cc["@mozilla.org/file/directory_service;1"]
+                                .getService(SpecialPowers.Ci.nsIProperties);
+      var file = dirSvc.get("ProfD", SpecialPowers.Ci.nsIFile);
       file.append('635499_file');
-      var outStream = Components.classes["@mozilla.org/network/file-output-stream;1"].
-                      createInstance(Components.interfaces.nsIFileOutputStream);
+      var outStream = SpecialPowers.Cc["@mozilla.org/network/file-output-stream;1"].
+                      createInstance(SpecialPowers.Ci.nsIFileOutputStream);
       outStream.init(file, 0x02 | 0x08 | 0x20, // write, create, truncate
                      0666, 0);
       outStream.write("foo", 3);
       outStream.close();
 
-      input.value = file.path;
+      SpecialPowers.wrap(input).value = file.path;
       checkValidity(input, true, apply);
 
       file.remove(false);
       break;
     case 'date':
       // For date, the step is calulated on the timestamp since 1970-01-01
       // which mean that for all dates prior to the epoch, this timestamp is < 0
       // and the behavior might differ, therefore we have to test for these cases.
--- a/content/html/content/test/forms/test_submit_invalid_file.html
+++ b/content/html/content/test/forms/test_submit_invalid_file.html
@@ -26,25 +26,24 @@ https://bugzilla.mozilla.org/show_bug.cg
    * Test invalid file submission by submitting a file that has been deleted
    * from the file system before the form has been submitted.
    * The form submission triggers a sjs file that shows its output in a frame.
    * That means the test might time out if it fails.
    */
 
   SimpleTest.waitForExplicitFinish();
   addLoadEvent(function() {
-    netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-    Components.utils.import("resource://gre/modules/FileUtils.jsm");
+    var FileUtils = SpecialPowers.Cu.import("resource://gre/modules/FileUtils.jsm").FileUtils;
 
     var i = document.getElementsByTagName('input')[0];
 
     var file = FileUtils.getFile("TmpD", ["testfile"]);
-    file.createUnique(Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 0644);
+    file.createUnique(SpecialPowers.Ci.nsIFile.NORMAL_FILE_TYPE, 0644);
 
-    i.value = file.path;
+    SpecialPowers.wrap(i).value = file.path;
     file.remove(/* recursive = */ false);
 
     document.getElementsByName('result')[0].addEventListener('load', function() {
       is(window.frames[0].document.body.textContent, "SUCCESS");
       SimpleTest.finish();
     });
     document.forms[0].submit();
   });
--- a/content/html/content/test/test_bug557087-3.html
+++ b/content/html/content/test/test_bug557087-3.html
@@ -67,19 +67,18 @@ function checkEnabledPseudoClass(aElemen
   ok(aEnabled ? found : !found, msg);
 }
 
 function checkFocus(aElement, aExpected)
 {
   aElement.setAttribute('tabindex', 1);
 
   // We use the focus manager so we can test <label>.
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-  var fm = Components.classes["@mozilla.org/focus-manager;1"]
-                     .getService(Components.interfaces.nsIFocusManager);
+  var fm = SpecialPowers.Cc["@mozilla.org/focus-manager;1"]
+                        .getService(SpecialPowers.Ci.nsIFocusManager);
   fm.setFocus(aElement, 0);
 
   if (aExpected) {
     is(document.activeElement, aElement, "element should be focused");
   } else {
     isnot(document.activeElement, aElement, "element should not be focused");
   }
 
--- a/content/html/content/test/test_bug561636.html
+++ b/content/html/content/test/test_bug561636.html
@@ -42,19 +42,18 @@ https://bugzilla.mozilla.org/show_bug.cg
 SimpleTest.waitForExplicitFinish();
 addLoadEvent(runTest);
 
 function runTest()
 {
   var formSubmitted = [ false, false ];
   var invalidHandled = false;
 
-  netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
-  var os = Components.classes['@mozilla.org/observer-service;1']
-                     .getService(Components.interfaces.nsIObserverService);
+  var os = SpecialPowers.Cc['@mozilla.org/observer-service;1']
+                        .getService(SpecialPowers.Ci.nsIObserverService);
   var observers = os.enumerateObservers("invalidformsubmit");
 
   // The following test should not be done if there is no observer for
   // "invalidformsubmit" because the form submission will not be canceled in that
   // case.
   if (!observers.hasMoreElements()) {
     SimpleTest.finish();
     return;
--- a/content/html/content/test/test_bug590353-2.html
+++ b/content/html/content/test/test_bug590353-2.html
@@ -30,22 +30,22 @@ var testData = [
   [ "reset", "foo", "foo" ],
   [ "submit", "foo", "foo" ],
   [ "checkbox", true, false ],
   [ "radio", true, false ],
   [ "file", "590353_file", "" ],
 ];
 
 function createFileWithData(fileName, fileData) {
-  var dirSvc = Components.classes["@mozilla.org/file/directory_service;1"]
-                         .getService(Components.interfaces.nsIProperties);
-  var testFile = dirSvc.get("ProfD", Components.interfaces.nsIFile);
+  var dirSvc = SpecialPowers.Cc["@mozilla.org/file/directory_service;1"]
+                            .getService(SpecialPowers.Ci.nsIProperties);
+  var testFile = dirSvc.get("ProfD", SpecialPowers.Ci.nsIFile);
   testFile.append(fileName);
-  var outStream = Components.classes["@mozilla.org/network/file-output-stream;1"].
-                  createInstance(Components.interfaces.nsIFileOutputStream);
+  var outStream = SpecialPowers.Cc["@mozilla.org/network/file-output-stream;1"].
+                  createInstance(SpecialPowers.Ci.nsIFileOutputStream);
   outStream.init(testFile, 0x02 | 0x08 | 0x20, // write, create, truncate
                  0666, 0);
   outStream.write(fileData, fileData.length);
   outStream.close();
 
   return testFile;
 }
 
@@ -55,20 +55,18 @@ content.appendChild(form);
 
 for (var data of testData) {
   var e = document.createElement('input');
   e.type = data[0];
 
   if (data[0] == 'checkbox' || data[0] == 'radio') {
     e.checked = data[1];
   } else if (data[0] == 'file') {
-    // Need privileges to set a filename with .value and create a file.
-    netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
     var file = createFileWithData(data[1], "file content");
-    e.value = file.path;
+    SpecialPowers.wrap(e).value = file.path;
   } else {
     e.value = data[1];
   }
 
   form.appendChild(e);
 }
 
 form.reset();
--- a/content/html/content/test/test_bug598643.html
+++ b/content/html/content/test/test_bug598643.html
@@ -13,37 +13,36 @@ https://bugzilla.mozilla.org/show_bug.cg
 <p id="display"></p>
 <pre id="test">
 <script type="application/javascript">
 
 /** Test for Bug 598643 **/
 
 function createFileWithData(fileName, fileData)
 {
-  var dirSvc = Components.classes["@mozilla.org/file/directory_service;1"]
-                         .getService(Components.interfaces.nsIProperties);
-  var testFile = dirSvc.get("ProfD", Components.interfaces.nsIFile);
+  var dirSvc = SpecialPowers.Cc["@mozilla.org/file/directory_service;1"]
+                            .getService(SpecialPowers.Ci.nsIProperties);
+  var testFile = dirSvc.get("ProfD", SpecialPowers.Ci.nsIFile);
   testFile.append(fileName);
-  var outStream = Components.classes["@mozilla.org/network/file-output-stream;1"].
-                  createInstance(Components.interfaces.nsIFileOutputStream);
+  var outStream = SpecialPowers.Cc["@mozilla.org/network/file-output-stream;1"].
+                  createInstance(SpecialPowers.Ci.nsIFileOutputStream);
   outStream.init(testFile, 0x02 | 0x08 | 0x20, // write, create, truncate
                  0666, 0);
   outStream.write(fileData, fileData.length);
   outStream.close();
 
   return testFile;
 }
 
 function testFileControl(aElement)
 {
   aElement.type = 'file';
 
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
   var file = createFileWithData("file_bug598643", "file content");
-  aElement.value = file.path;
+  SpecialPowers.wrap(aElement).value = file.path;
 
   ok(aElement.validity.valid, "the file control should be valid");
   ok(!aElement.validity.tooLong,
      "the file control shouldn't suffer from being too long");
 }
 
 var types = [
   // These types can be too long.
--- a/content/html/content/test/test_bug605124-1.html
+++ b/content/html/content/test/test_bug605124-1.html
@@ -36,19 +36,18 @@ https://bugzilla.mozilla.org/show_bug.cg
 /** Test for Bug 605124 **/
 
 function checkPseudoClass(aElement, aExpected)
 {
   is(aElement.mozMatchesSelector(":-moz-ui-invalid"), aExpected,
      "mozMatchesSelector(':-moz-ui-invalid') should return " + aExpected + " for " + aElement);
 }
 
-netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
-var os = Components.classes['@mozilla.org/observer-service;1']
-                   .getService(Components.interfaces.nsIObserverService);
+var os = SpecialPowers.Cc['@mozilla.org/observer-service;1']
+                      .getService(SpecialPowers.Ci.nsIObserverService);
 var observers = os.enumerateObservers("invalidformsubmit");
 
 if (observers.hasMoreElements()) {
   var content = document.getElementById('content');
   var textarea = document.getElementsByTagName('textarea')[0];
   var input = document.getElementsByTagName('input')[0];
   var select = document.getElementsByTagName('select')[0];
   var button = document.getElementsByTagName('button')[0];
--- a/content/html/content/test/test_bug605125-1.html
+++ b/content/html/content/test/test_bug605125-1.html
@@ -42,19 +42,18 @@ https://bugzilla.mozilla.org/show_bug.cg
  */
 
 function checkPseudoClass(aElement, aExpected)
 {
   is(aElement.mozMatchesSelector(":-moz-ui-valid"), aExpected,
      "mozMatchesSelector(':-moz-ui-valid') should return " + aExpected + " for " + aElement);
 }
 
-netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
-var os = Components.classes['@mozilla.org/observer-service;1']
-                   .getService(Components.interfaces.nsIObserverService);
+var os = SpecialPowers.Cc['@mozilla.org/observer-service;1']
+                      .getService(SpecialPowers.Ci.nsIObserverService);
 var observers = os.enumerateObservers("invalidformsubmit");
 
 if (observers.hasMoreElements()) {
   var content = document.getElementById('content');
   var textarea = document.getElementsByTagName('textarea')[0];
   var input = document.getElementsByTagName('input')[0];
   var button = document.getElementsByTagName('button')[0];
   var select = document.getElementsByTagName('select')[0];
--- a/content/media/test/file_access_controls.html
+++ b/content/media/test/file_access_controls.html
@@ -120,18 +120,17 @@ function nextTest() {
       return;
     }
   }
 
   if (gVideo && gVideo.parentNode)
     gVideo.parentNode.removeChild(gVideo);
 
   gVideo = null;
-  netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
-  Components.utils.forceGC();  
+  opener.SpecialPowers.forceGC();  
   
   gVideo = createVideo();
   gVideo.expectedResult = gTests[gTestNum].result;
   gVideo.testDescription = gTests[gTestNum].description;
   // Uniquify the resource URL to ensure that the resources loaded by earlier or subsequent tests
   // don't overlap with the resources we load here, which are loaded with non-default preferences set.
   // We also want to make sure that an HTTP fetch actually happens for each testcase.
   var url = gTests[gTestNum].url;
--- a/content/media/webspeech/recognition/test/head.js
+++ b/content/media/webspeech/recognition/test/head.js
@@ -10,18 +10,17 @@ var errorCodes = {
   AUDIO_CAPTURE : "audio-capture",
   NETWORK : "network",
   NOT_ALLOWED : "not-allowed",
   SERVICE_NOT_ALLOWED : "service-not-allowed",
   BAD_GRAMMAR : "bad-grammar",
   LANGUAGE_NOT_SUPPORTED : "language-not-supported"
 };
 
-netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-Components.utils.import("resource://gre/modules/Services.jsm");
+var Services = SpecialPowers.Cu.import("resource://gre/modules/Services.jsm").Services;
 
 function EventManager(sr) {
   var self = this;
   var nEventsExpected = 0;
   self.eventsReceived = [];
 
   var allEvents = [
     "audiostart",
--- a/content/xml/document/test/test_bug392338.html
+++ b/content/xml/document/test/test_bug392338.html
@@ -15,48 +15,46 @@ https://bugzilla.mozilla.org/show_bug.cg
   
 </div>
 <pre id="test">
 <script class="testbody" type="text/javascript">
 
 /** Test for Bug 392338 **/
 function obs () {
   netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-  this.observerService = Components.classes["@mozilla.org/observer-service;1"]
-                                     .getService(Components.interfaces.nsIObserverService);
+  this.observerService = SpecialPowers.Cc["@mozilla.org/observer-service;1"]
+                                      .getService(SpecialPowers.Ci.nsIObserverService);
   this.observerService.addObserver(this,"http-on-modify-request", false);
   this.window = window;
 }
 
 obs.prototype = {
   observe: function obs_observe (theSubject, theTopic, theData)
   {
     this.timeToFinish = true;
     try{
-      this.window.netscape.security
-          .PrivilegeManager.enablePrivilege("UniversalXPConnect");
-      var ir = theSubject.QueryInterface(this.window.Components.interfaces
+      var ir = theSubject.QueryInterface(this.window.SpecialPowers.Ci
                                              .nsIChannel).notificationCallbacks;
       if (!ir) {
         this.timeToFinish = false;
         return;
       }
       this.window.ok(true, "No exception thrown");
 
       this.window.is(ir instanceof
-                       this.window.Components.interfaces.nsIInterfaceRequestor,
+                       this.window.SpecialPowers.Ci.nsIInterfaceRequestor,
                      true, "Must be an interface requestor");
 
-      if (ir instanceof this.window.Components.interfaces.nsIClassInfo) {
+      if (ir instanceof this.window.SpecialPowers.Ci.nsIClassInfo) {
         var count = {};
         var interfaces = ir.
-                     QueryInterface(this.window.Components.interfaces.nsIClassInfo).
+                     QueryInterface(this.window.SpecialPowers.Ci.nsIClassInfo).
                      getInterfaces(count).
                      map(function(id) {
-                                return this.window.Components.interfacesByID[id].toString();
+                                return this.window.SpecialPowers.CiByID[id].toString();
                          });
         this.window.isnot(interfaces.indexOf("nsIInterfaceRequestor"), -1,
                           "Must have interface requestor classinfo");
       }
     } catch(ex) {
       this.window.is(true, false, "Exception thrown " + ex);
     } finally {
       if (this.timeToFinish) {
@@ -64,17 +62,16 @@ obs.prototype = {
         this.window.SimpleTest.finish();
         this.window = null;
       }
     }
   },
 
   remove: function obs_remove()
   {
-    netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
     this.observerService.removeObserver(this,"http-on-modify-request");
     this.observerService = null;
   }
 }
 
 var o;
 
 SimpleTest.waitForExplicitFinish();
--- a/content/xul/content/test/test_bug486990.xul
+++ b/content/xul/content/test/test_bug486990.xul
@@ -81,21 +81,20 @@ https://bugzilla.mozilla.org/show_bug.cg
     evt.stopPropagation();
   }
 
   function contextMenuPreventer(evt) {
     evt.preventDefault();
   }
 
   function allowDisableContextMenu(allow) {
-    netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
     const prefSvcContractID = "@mozilla.org/preferences-service;1";
-    const prefSvcIID = Components.interfaces.nsIPrefService;
-    var prefs = Components.classes[prefSvcContractID].getService(prefSvcIID)
-                                                     .getBranch("dom.event.contextmenu.");
+    const prefSvcIID = SpecialPowers.Ci.nsIPrefService;
+    var prefs = SpecialPowers.Cc[prefSvcContractID].getService(prefSvcIID)
+                                                   .getBranch("dom.event.contextmenu.");
     try {
       if (allow) {
         if (prefs.prefHasUserValue("enabled")) {
           prefs.clearUserPref("enabled");
         }
       } else {
         prefs.setBoolPref("enabled", allow);
       }
--- a/dom/plugins/test/mochitest/cocoa_window_focus.html
+++ b/dom/plugins/test/mochitest/cocoa_window_focus.html
@@ -49,18 +49,18 @@
 
         is(plugin2.getTopLevelWindowActivationState(), true, "Activation state should be: activated");
         is(plugin2.getTopLevelWindowActivationEventCount(), expectedEventCount, "Window focus event count should be " + expectedEventCount);
       } catch (e) {
         ok(false, "Plugin does not know its initial top-level window activation state!");
       }
 
       netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-      var fm = Components.classes["@mozilla.org/focus-manager;1"].
-                          getService(Components.interfaces.nsIFocusManager);
+      var fm = SpecialPowers.Cc["@mozilla.org/focus-manager;1"].
+                             getService(SpecialPowers.Ci.nsIFocusManager);
 
       waitForFocus(function() {
         // Make sure the plugin handled the focus event before checking.
         executeSoon(function() {
           expectedEventCount++;
 
           is(plugin1.getTopLevelWindowActivationState(), false, "Activation state should be: deactivated");
           is(plugin1.getTopLevelWindowActivationEventCount(), expectedEventCount, "Window focus event count should be " + expectedEventCount);
--- a/dom/plugins/test/mochitest/test_GCrace.html
+++ b/dom/plugins/test/mochitest/test_GCrace.html
@@ -41,18 +41,17 @@
       }
       SimpleTest.executeSoon(removePlugin);
     }
 
     function removePlugin() {
       var p = document.getElementById('p');
       p.parentNode.removeChild(p);
       p = null;
-      netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
-      Components.utils.forceGC();
+      SpecialPowers.Cu.forceGC();
       SimpleTest.finish();
     }
 
     function checkGCRace() {
       nested = true;
 
       // The plugin will hand back a function and immediately sleep.
       // We will lose our only reference to the function and force GC, followed
@@ -60,13 +59,12 @@
       // call the function and not crash.
       var p = document.getElementById('p');
       var f = p.checkGCRace(cb);
       f = null;  // 'f' should be collected next GC
 
       nested = false;
 
       setTimeout(function() {
-        netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
-        Components.utils.forceGC();
+        SpecialPowers.Cu.forceGC();
       }, 2000);
     }
   </script>
--- a/dom/plugins/test/mochitest/test_getauthenticationinfo.html
+++ b/dom/plugins/test/mochitest/test_getauthenticationinfo.html
@@ -10,20 +10,18 @@ Test for NPN_GetAuthenticationInfo
 <p id="display"></p>
 
 <div id="content">
   <iframe id="iframe"></iframe>
 </div>
 
 <script class="testbody" type="text/javascript">
 
-netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
-
-const Ci = Components.interfaces;
-const Cc = Components.classes;
+const Ci = SpecialPowers.Ci;
+const Cc = SpecialPowers.Cc;
 
 function iframeLoad() {
   var plugin = iframe.contentDocument.getElementById("embedtest");
   // valid request
   is(plugin.getAuthInfo("http", "mochi.test", 8888, "basic", "testrealm"), 
       "user1|password1", 
       "correct user/pass retrieved");
   try {
--- a/dom/plugins/test/mochitest/test_visibility.html
+++ b/dom/plugins/test/mochitest/test_visibility.html
@@ -14,18 +14,16 @@
 
   <script type="application/javascript" src="utils.js"></script>
   <script type="application/javascript">
   SimpleTest.waitForExplicitFinish();
 
   var didPaint = function() {};
 
   function startTest() {
-    netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-
     if (SimpleTest.testPluginIsOOP()) {
       if (p.getPaintCount() < 1) {
         setTimeout(startTest, 0);
         return;
       }
     }
 
     didPaint = function() {
--- a/dom/plugins/test/mochitest/utils.js
+++ b/dom/plugins/test/mochitest/utils.js
@@ -1,18 +1,17 @@
 function paintCountIs(plugin, expected, msg) {
   var count = plugin.getPaintCount();
   var realExpected = expected;
   var isAsync = SimpleTest.testPluginIsOOP();
   if (isAsync) {
     ++realExpected; // extra paint at startup for all async-rendering plugins
   } else {
-    netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
     try {
-      if (Components.classes["@mozilla.org/gfx/info;1"].getService(Components.interfaces.nsIGfxInfo).D2DEnabled) {
+      if (SpecialPowers.Cc["@mozilla.org/gfx/info;1"].getService(SpecialPowers.Ci.nsIGfxInfo).D2DEnabled) {
         realExpected *= 2;
       }
     } catch (e) {}
   }
   ok(realExpected == count, msg + " (expected " + expected +
      " independent paints, expected " + realExpected + " logged paints, got " +
      count + " actual paints)");
 }
--- a/dom/tests/mochitest/ajax/offline/foreign2.html
+++ b/dom/tests/mochitest/ajax/offline/foreign2.html
@@ -5,17 +5,17 @@
 <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
 <script type="text/javascript" src="/tests/dom/tests/mochitest/ajax/offline/offlineTests.js"></script>
 <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
 
 <script class="testbody" type="text/javascript">
 
 function manifestUpdated()
 {
-  var appCacheService = SpecialPowers.Components.classes["@mozilla.org/network/application-cache-service;1"]
+  var appCacheService = SpecialPowers.Cc["@mozilla.org/network/application-cache-service;1"]
     .getService(SpecialPowers.Ci.nsIApplicationCacheService);
 
   var foreign2cache = appCacheService.chooseApplicationCache(
     "http://mochi.test:8888/tests/dom/tests/mochitest/ajax/offline/foreign2.html", OfflineTest.loadContext());
 
   window.opener.OfflineTest.ok(foreign2cache, "Foreign 2 cache present, chosen for foreign2.html");
   window.opener.OfflineTest.is(foreign2cache.manifestURI.asciiSpec, "http://mochi.test:8888/tests/dom/tests/mochitest/ajax/offline/foreign2.cacheManifest")
 
@@ -24,17 +24,17 @@ function manifestUpdated()
   window.opener.OfflineTest.ok(foreign1cache, "Foreign 1 cache loaded");
   foreign1cache.discard();
 
   window.opener.onDone();
 }
 
 function onLoaded()
 {
-  var appCacheService = SpecialPowers.Components.classes["@mozilla.org/network/application-cache-service;1"]
+  var appCacheService = SpecialPowers.Cc["@mozilla.org/network/application-cache-service;1"]
     .getService(SpecialPowers.Ci.nsIApplicationCacheService);
 
   var foreign1cache = window.opener.OfflineTest.getActiveCache(
     "http://mochi.test:8888/tests/dom/tests/mochitest/ajax/offline/foreign1.cacheManifest");
   window.opener.OfflineTest.ok(foreign1cache, "Foreign 1 cache loaded");
 
   var foreign2cache = window.opener.OfflineTest.getActiveCache(
     "http://mochi.test:8888/tests/dom/tests/mochitest/ajax/offline/foreign2.cacheManifest");
--- a/dom/tests/mochitest/ajax/offline/offlineTests.js
+++ b/dom/tests/mochitest/ajax/offline/offlineTests.js
@@ -1,13 +1,11 @@
 // Utility functions for offline tests.
-netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-
-var Cc = Components.classes;
-var Ci = Components.interfaces;
+var Cc = SpecialPowers.Cc;
+var Ci = SpecialPowers.Ci;
 
 const kNetBase = 2152398848; // 0x804B0000
 var NS_ERROR_CACHE_KEY_NOT_FOUND = kNetBase + 61;
 var NS_ERROR_CACHE_KEY_WAIT_FOR_VALIDATION = kNetBase + 64;
 
 // Reading the contents of multiple cache entries asynchronously
 function OfflineCacheContents(urls) {
   this.urls = urls;
@@ -26,18 +24,18 @@ onCacheEntryAvailable: function(desc, ac
     netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
 
     if (!desc) {
       this.fetch(this.callback);
       return;
     }
 
     var stream = desc.QueryInterface(Ci.nsICacheEntryDescriptor).openInputStream(0);
-    var sstream = Components.classes["@mozilla.org/scriptableinputstream;1"]
-                 .createInstance(Components.interfaces.nsIScriptableInputStream);
+    var sstream = SpecialPowers.Cc["@mozilla.org/scriptableinputstream;1"]
+                 .createInstance(SpecialPowers.Ci.nsIScriptableInputStream);
     sstream.init(stream);
     this.contents[desc.key] = sstream.read(sstream.available());
     sstream.close();
     desc.close();
     this.fetch(this.callback);
   },
 
 fetch: function(callback)
@@ -117,17 +115,17 @@ setup: function()
     // enable the pref and spawn a new window to perform the actual
     // tests.  It will use this window to report successes and
     // failures.
     var pm = Cc["@mozilla.org/permissionmanager;1"]
       .getService(Ci.nsIPermissionManager);
     var uri = Cc["@mozilla.org/network/io-service;1"]
       .getService(Ci.nsIIOService)
       .newURI(window.location.href, null, null);
-    var principal = Components.classes["@mozilla.org/scriptsecuritymanager;1"]
+    var principal = SpecialPowers.Cc["@mozilla.org/scriptsecuritymanager;1"]
                       .getService(Ci.nsIScriptSecurityManager)
                       .getNoAppCodebasePrincipal(uri);
 
     if (pm.testPermissionFromPrincipal(principal, "offline-app") != 0) {
       ok(false, "Previous test failed to clear offline-app permission!  Expect failures.");
     }
     pm.addFromPrincipal(principal, "offline-app", Ci.nsIPermissionManager.ALLOW_ACTION);
 
@@ -157,17 +155,17 @@ teardown: function(callback)
 
     netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
 
     var pm = Cc["@mozilla.org/permissionmanager;1"]
              .getService(Ci.nsIPermissionManager);
     var uri = Cc["@mozilla.org/network/io-service;1"]
               .getService(Ci.nsIIOService)
               .newURI(window.location.href, null, null);
-    var principal = Components.classes["@mozilla.org/scriptsecuritymanager;1"]
+    var principal = SpecialPowers.Cc["@mozilla.org/scriptsecuritymanager;1"]
                       .getService(Ci.nsIScriptSecurityManager)
                       .getNoAppCodebasePrincipal(uri);
 
     pm.removeFromPrincipal(principal, "offline-app");
 
     // Clear all overrides on the server
     for (override in self._pathOverrides)
       self.deleteData(self._pathOverrides[override]);
@@ -326,20 +324,20 @@ manifestURL: function(overload)
             .getService(Ci.nsIIOService)
 
   var baseURI = ios.newURI(window.location.href, null, null);
   return ios.newURI(manifestURLspec, null, baseURI);
 },
 
 loadContext: function()
 {
-  return SpecialPowers.wrap(window).QueryInterface(Components.interfaces.nsIInterfaceRequestor)
-                                   .getInterface(Components.interfaces.nsIWebNavigation)
-                                   .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
-                                   .getInterface(Components.interfaces.nsILoadContext);
+  return SpecialPowers.wrap(window).QueryInterface(SpecialPowers.Ci.nsIInterfaceRequestor)
+                                   .getInterface(SpecialPowers.Ci.nsIWebNavigation)
+                                   .QueryInterface(SpecialPowers.Ci.nsIInterfaceRequestor)
+                                   .getInterface(SpecialPowers.Ci.nsILoadContext);
 },
 
 getActiveCache: function(overload)
 {
   // Note that this is the current active cache in the cache stack, not the
   // one associated with this window.
   var serv = Cc["@mozilla.org/network/application-cache-service;1"]
              .getService(Ci.nsIApplicationCacheService);
--- a/dom/tests/mochitest/ajax/offline/test_bug460353.html
+++ b/dom/tests/mochitest/ajax/offline/test_bug460353.html
@@ -23,26 +23,24 @@ init();
 function onUpdatePassed()
 {
   if (!(--expectedUpdates))
     SimpleTest.executeSoon(finish);
 }
 
 function init()
 {
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-
-  var Cc = Components.classes;
-  var Ci = Components.interfaces;
+  var Cc = SpecialPowers.Cc;
+  var Ci = SpecialPowers.Ci;
   var pm = Cc["@mozilla.org/permissionmanager;1"]
     .getService(Ci.nsIPermissionManager);
   var uri = Cc["@mozilla.org/network/io-service;1"]
     .getService(Ci.nsIIOService)
     .newURI(window.location.href, null, null);
-  var principal = Components.classes["@mozilla.org/scriptsecuritymanager;1"]
+  var principal = SpecialPowers.Cc["@mozilla.org/scriptsecuritymanager;1"]
                     .getService(Ci.nsIScriptSecurityManager)
                     .getNoAppCodebasePrincipal(uri);
   pm.addFromPrincipal(principal, "offline-app", Ci.nsIPermissionManager.ALLOW_ACTION);
 
   applicationCache.oncached = onUpdatePassed;
   applicationCache.onnoupdate = onUpdatePassed;
 }
 
@@ -76,42 +74,38 @@ function finish()
   SimpleTest.ok(result["diff"].updateOK || false, "Frame with different manifest cache update passed OK");
   SimpleTest.is(result["diff"].cacheStatus || -1, 1, "Frame with different manifest cache status was IDLE");
 
   SimpleTest.ok(result["noman"].load || false, "Frame with no manifest loads");
   SimpleTest.ok(result["noman"].update == undefined, "Frame with no manifest cache update didn't notify");
   SimpleTest.ok(result["noman"].updateOK == undefined, "Frame with no manifest cache update didn't pass");
   SimpleTest.is(result["noman"].cacheStatus || -1, -1, "Frame with no manifest cache status was undefined");
 
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-
-  var Cc = Components.classes;
-  var Ci = Components.interfaces;
+  var Cc = SpecialPowers.Cc;
+  var Ci = SpecialPowers.Ci;
   var pm = Cc["@mozilla.org/permissionmanager;1"]
            .getService(Ci.nsIPermissionManager);
   var uri = Cc["@mozilla.org/network/io-service;1"]
             .getService(Ci.nsIIOService)
             .newURI(window.location.href, null, null);
-  var principal = Components.classes["@mozilla.org/scriptsecuritymanager;1"]
+  var principal = SpecialPowers.Cc["@mozilla.org/scriptsecuritymanager;1"]
                     .getService(Ci.nsIScriptSecurityManager)
                     .getNoAppCodebasePrincipal(uri);
   pm.removeFromPrincipal(principal, "offline-app");
 
   OfflineTest.waitForUpdates(function() {
     cleanCache("http://mochi.test:8888/tests/dom/tests/mochitest/ajax/offline/simpleManifest.cacheManifest");
     cleanCache("http://mochi.test:8888/tests/dom/tests/mochitest/ajax/offline/updatingManifest.sjs");
 
     SimpleTest.finish();
   });
 }
 
 function cleanCache(manifestURL)
 {
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-
   var cache = OfflineTest.getActiveCache(manifestURL);
   dump("Discarding cache for " + manifestURL + " cache=" + cache + "\n");
   if (cache)
     cache.discard();
 }
 
 SimpleTest.waitForExplicitFinish();
 
--- a/dom/tests/mochitest/ajax/offline/test_missingManifest.html
+++ b/dom/tests/mochitest/ajax/offline/test_missingManifest.html
@@ -1,41 +1,39 @@
 <html>
 <head>
 <title>Test missing manifest</title>
 
 <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
 
 <script type="text/javascript">
 
 var gTestWin;
 
-netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-
-var Cc = Components.classes;
-var Ci = Components.interfaces;
+var Cc = SpecialPowers.Cc;
+var Ci = SpecialPowers.Ci;
 
 // Enable the offline-app permission before loading the new window
 var pm = Cc["@mozilla.org/permissionmanager;1"]
         .getService(Ci.nsIPermissionManager);
 var uri = Cc["@mozilla.org/network/io-service;1"]
          .getService(Ci.nsIIOService)
          .newURI(window.location.href, null, null);
-var principal = Components.classes["@mozilla.org/scriptsecuritymanager;1"]
+var principal = SpecialPowers.Cc["@mozilla.org/scriptsecuritymanager;1"]
                   .getService(Ci.nsIScriptSecurityManager)
                   .getNoAppCodebasePrincipal(uri);
 
 pm.addFromPrincipal(principal, "offline-app", Ci.nsIPermissionManager.ALLOW_ACTION);
 
 // now this will properly load the manifest.
 gTestWin = window.open("missing.html");
 
 function finish()
 {
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
   pm.removeFromPrincipal(principal, "offline-app");
 
   gTestWin.close();
   SimpleTest.finish();
 }
 
 SimpleTest.waitForExplicitFinish();
 
--- a/dom/tests/mochitest/ajax/offline/test_obsolete.html
+++ b/dom/tests/mochitest/ajax/offline/test_obsolete.html
@@ -1,30 +1,29 @@
 <html>
 <head>
 <title>Test obsolete application caches</title>
 
 <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
 
 <script type="text/javascript">
 
 var gTestWin;
 
-netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-
-var Cc = Components.classes;
-var Ci = Components.interfaces;
+var Cc = SpecialPowers.Cc;
+var Ci = SpecialPowers.Ci;
 
 // Enable the offline-app permission before loading the new window
 var pm = Cc["@mozilla.org/permissionmanager;1"]
         .getService(Ci.nsIPermissionManager);
 var uri = Cc["@mozilla.org/network/io-service;1"]
          .getService(Ci.nsIIOService)
          .newURI(window.location.href, null, null);
-var principal = Components.classes["@mozilla.org/scriptsecuritymanager;1"]
+var principal = SpecialPowers.Cc["@mozilla.org/scriptsecuritymanager;1"]
                   .getService(Ci.nsIScriptSecurityManager)
                   .getNoAppCodebasePrincipal(uri);
 pm.addFromPrincipal(principal, "offline-app", Ci.nsIPermissionManager.ALLOW_ACTION);
 
 // Make the obsoleting.sjs return a valid manifest
 var req = new XMLHttpRequest();
 req.open("GET", "http://mochi.test:8888/tests/dom/tests/mochitest/ajax/offline/obsoletingManifest.sjs?state=manifestPresent");
 req.setRequestHeader("Content-Type", "text/cache-manifest");
@@ -33,17 +32,16 @@ req.onreadystatechange = function() {
   if (req.readyState == 4) {
     // now this will properly load the manifest.
     gTestWin = window.open("obsolete.html");
   }
 }
 
 function finish()
 {
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
   pm.removeFromPrincipal(principal, "offline-app");
 
   gTestWin.close();
   SimpleTest.finish();
 }
 
 SimpleTest.waitForExplicitFinish();
 
--- a/dom/tests/mochitest/bugs/test_bug61098.html
+++ b/dom/tests/mochitest/bugs/test_bug61098.html
@@ -26,18 +26,18 @@ SimpleTest.waitForExplicitFinish();
 
 var mockPromptServiceRegisterer, mockPromptFactoryRegisterer;
 
 var promptState;
 
 function registerMockPromptService()
 {
   netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
-  Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
-  var Ci = Components.interfaces;
+  var XPCOMUtils = SpecialPowers.Cu.import("resource://gre/modules/XPCOMUtils.jsm").XPCOMUtils;
+  var Ci = SpecialPowers.Ci;
 
   function MockPrompt(aDOMWindow) {
     this.domWindow = aDOMWindow;
   }
 
   MockPrompt.prototype = {
     QueryInterface: XPCOMUtils.generateQI([Ci.nsIPrompt]),
 
@@ -215,28 +215,26 @@ function registerMockPromptService()
                              MockPromptService);
 
   mockPromptServiceRegisterer.register();
   mockPromptFactoryRegisterer.register();
 };
 
 function enableDialogLoopBlocking()
 {
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-  var prefs = Components.classes["@mozilla.org/preferences-service;1"].
-    getService(Components.interfaces.nsIPrefBranch);
+  var prefs = SpecialPowers.Cc["@mozilla.org/preferences-service;1"].
+    getService(SpecialPowers.Ci.nsIPrefBranch);
 
   prefs.setIntPref("dom.successive_dialog_time_limit", 3);
 }
 
 function resetDialogLoopBlocking()
 {
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-  var prefs = Components.classes["@mozilla.org/preferences-service;1"].
-    getService(Components.interfaces.nsIPrefBranch);
+  var prefs = SpecialPowers.Cc["@mozilla.org/preferences-service;1"].
+    getService(SpecialPowers.Ci.nsIPrefBranch);
 
   prefs.setIntPref("dom.successive_dialog_time_limit", 0);
 }
 
 var expectedState;
 
 function runtests()
 {
--- a/dom/tests/mochitest/general/test_clipboard_events.html
+++ b/dom/tests/mochitest/general/test_clipboard_events.html
@@ -39,17 +39,16 @@ var delayedTests = [];
 var cachedCutData, cachedCopyData, cachedPasteData;
 
 // Ensure window focus before running tests, otherwise key events can
 // misfire.  We set the onfocus event handler here to actually begin
 // running tests, and call window.focus() afterwards.
 window.onfocus = function()
 {
   window.onfocus = null;
-  netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
 
   // A list of test functions to run.  Before each test function is run, the
   // clipboard is initialized to clipboardInitialValue, and the contents of
   // div#content are set as the window's selection.
   var testFunctions = [
     test_dom_oncopy,
     test_dom_oncut,
     test_dom_onpaste,
@@ -93,65 +92,65 @@ window.onfocus = function()
   SimpleTest.finish();
 }
 
 // Calling .focus begins the test run.
 SimpleTest.waitForExplicitFinish();
 window.focus();
 
 function getLoadContext() {
-  return window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
-               .getInterface(Components.interfaces.nsIWebNavigation)
-               .QueryInterface(Components.interfaces.nsILoadContext);
+  return window.QueryInterface(SpecialPowers.Ci.nsIInterfaceRequestor)
+               .getInterface(SpecialPowers.Ci.nsIWebNavigation)
+               .QueryInterface(SpecialPowers.Ci.nsILoadContext);
 }
 
 function getClipboardText() {
-  var trans = Components.classes["@mozilla.org/widget/transferable;1"]
+  var trans = SpecialPowers.Cc["@mozilla.org/widget/transferable;1"]
     .createInstance();
-  trans = trans.QueryInterface(Components.interfaces.nsITransferable);
+  trans = trans.QueryInterface(SpecialPowers.Ci.nsITransferable);
   trans.init(getLoadContext());
   trans.addDataFlavor("text/unicode");
 
-  var clipboard = Components.classes["@mozilla.org/widget/clipboard;1"]
+  var clipboard = SpecialPowers.Cc["@mozilla.org/widget/clipboard;1"]
     .getService();
-  clipboard = clipboard.QueryInterface(Components.interfaces.nsIClipboard);
+  clipboard = clipboard.QueryInterface(SpecialPowers.Ci.nsIClipboard);
   clipboard.getData(trans, clipboard.kGlobalClipboard);
 
   var str = new Object();
   var strLen = new Object();
 
   try {
     trans.getTransferData("text/unicode", str, strLen);
   } catch(e) {
     // NS_ERROR_FAILURE will occur if the transferable object has no
     // text/unicode data in it.  In that case, it's not an error:
-    if (e instanceof Components.interfaces.nsIXPCException &&
-      e.result == Components.results.NS_ERROR_FAILURE) {
+    if (e instanceof SpecialPowers.Ci.nsIXPCException &&
+      e.result == SpecialPowers.Cr.NS_ERROR_FAILURE) {
       return null;
     } else {
       // if we don't know how to handle it then rethrow
       throw e;
     }
   }
 
   if (!str) return null;
 
-  str = str.value.QueryInterface(Components.interfaces.nsISupportsString);
+  str = str.value.QueryInterface(SpecialPowers.Ci.nsISupportsString);
   if (!str) return null;
 
   str = str.data.substring(0, strLen.value / 2);
   if (!str) return null;
 
   return str;
 }
 
 
 function setClipboardText(text) {
-  var helper = Components.classes["@mozilla.org/widget/clipboardhelper;1"]
-    .getService(Components.interfaces.nsIClipboardHelper);
+  var helper = SpecialPowers.Cc["@mozilla.org/widget/clipboardhelper;1"]
+    .getService(SpecialPowers.Ci.nsIClipboardHelper);
   helper.copyString(text);
 }
 
 function selectContentDiv() {
   // Set selection
   var selection = window.getSelection();
   selection.removeAllRanges();
   selection.selectAllChildren(content);
--- a/dom/tests/mochitest/general/test_focusrings.xul
+++ b/dom/tests/mochitest/general/test_focusrings.xul
@@ -17,20 +17,19 @@
 </html:style>
 
 <script>
 <![CDATA[
 
 SimpleTest.waitForExplicitFinish();
 
 function setOrRestoreTabFocus(newValue) {
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
   const prefSvcContractID = "@mozilla.org/preferences-service;1";
-  const prefSvcIID = Components.interfaces.nsIPrefService;
-  var prefs = Components.classes[prefSvcContractID].getService(prefSvcIID)
+  const prefSvcIID = SpecialPowers.Ci.nsIPrefService;
+  var prefs = SpecialPowers.Cc[prefSvcContractID].getService(prefSvcIID)
                                                    .getBranch("accessibility.");
   if (!newValue) {
     if (prefs.prefHasUserValue("tabfocus")) {
       prefs.clearUserPref("tabfocus");
     }
   } else {
     prefs.setIntPref("tabfocus", newValue);
   }
@@ -70,20 +69,18 @@ function runTest()
   // focus rings until a key is pressed, as the default state depends on what
   // kind of real user input, mouse or key, was last entered. But we can handle
   // the test regardless of which user input last occurred.
   $("l1").focus();
   var expectedVisible = (!isWin || getComputedStyle($("l1"), "").outlineWidth == "2px");
   testHTMLElements(htmlElements, isMac, isWin && !expectedVisible);
 
   if (isMac) {
-    netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
-
-    var prefs = Components.classes["@mozilla.org/preferences-service;1"].
-                  getService(Components.interfaces.nsIPrefBranch);
+    var prefs = SpecialPowers.Cc["@mozilla.org/preferences-service;1"].
+                  getService(SpecialPowers.Ci.nsIPrefBranch);
     prefs.setBoolPref("accessibility.mouse_focuses_formcontrol", true);
 
     testHTMLElements(htmlElementsMacPrefSet, true, false);
 
     prefs.setBoolPref("accessibility.mouse_focuses_formcontrol", false);
   }
 
   $("l1").focus();
--- a/dom/tests/mochitest/localstorage/test_localStorageBaseSessionOnly.html
+++ b/dom/tests/mochitest/localstorage/test_localStorageBaseSessionOnly.html
@@ -4,24 +4,22 @@
 
 <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
 <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
 
 <script type="text/javascript">
 
 function startTest()
 {
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-
-  var io = Components.classes["@mozilla.org/network/io-service;1"]
-    .getService(Components.interfaces.nsIIOService);
+  var io = SpecialPowers.Cc["@mozilla.org/network/io-service;1"]
+    .getService(SpecialPowers.Ci.nsIIOService);
   var uri = io.newURI(window.location, "", null);
-  var cp = Components.classes["@mozilla.org/cookie/permission;1"]
-    .getService(Components.interfaces.nsICookiePermission);
-  cp.setAccess(uri, Components.interfaces.nsICookiePermission.ACCESS_SESSION);
+  var cp = SpecialPowers.Cc["@mozilla.org/cookie/permission;1"]
+    .getService(SpecialPowers.Ci.nsICookiePermission);
+  cp.setAccess(uri, SpecialPowers.Ci.nsICookiePermission.ACCESS_SESSION);
 
 
   // Initially check the localStorage is empty
   is(localStorage.length, 0, "The storage is empty [1]");
   is(localStorage.key(0), null, "key() should return null for out-of-bounds access");
   is(localStorage.key(-1), null, "key() should return null for out-of-bounds access");
   is(localStorage.key(1), null, "key() should return null for out-of-bounds access");
   is(localStorage.getItem("nonexisting"), null, "Nonexisting item is null (getItem())");
@@ -193,17 +191,17 @@ function startTest()
   is(localStorage.getItem("nonexisting"), null, "Nonexisting item is null");
   is(localStorage.getItem("key1"), null, "key1 removed");
   is(localStorage.getItem("key2"), null, "key2 removed");
   localStorage.removeItem("nonexisting"); // Just check there is no exception
   localStorage.removeItem("key1"); // Just check there is no exception
   localStorage.removeItem("key2"); // Just check there is no exception
 
 
-  cp.setAccess(uri, Components.interfaces.nsICookiePermission.ACCESS_DEFAULT);
+  cp.setAccess(uri, SpecialPowers.Ci.nsICookiePermission.ACCESS_DEFAULT);
 
   localStorage.clear();
   SimpleTest.finish();
 }
 
 SimpleTest.waitForExplicitFinish();
 
 </script>
--- a/dom/tests/mochitest/localstorage/test_localStorageEnablePref.html
+++ b/dom/tests/mochitest/localstorage/test_localStorageEnablePref.html
@@ -4,20 +4,18 @@
 
 <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
 <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
 
 <script type="text/javascript">
 
 function setDOMStorageEnabled(enabled)
 {
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-
-  var prefs = Components.classes["@mozilla.org/preferences-service;1"]
-              .getService(Components.interfaces.nsIPrefBranch);
+  var prefs = SpecialPowers.Cc["@mozilla.org/preferences-service;1"]
+              .getService(SpecialPowers.Ci.nsIPrefBranch);
   prefs.setBoolPref("dom.storage.enabled", enabled);
 }
 
 function checkException(func, exc)
 {
   var exceptionThrew = false;
   try {
     func();
--- a/dom/tests/mochitest/localstorage/test_localStorageQuota.html
+++ b/dom/tests/mochitest/localstorage/test_localStorageQuota.html
@@ -3,31 +3,27 @@
 <title>localStorage and DOM quota test</title>
 
 <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
 <script type="text/javascript" src="interOriginTest.js"></script>
 <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
 
 <script type="text/javascript">
 
-netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-
 var currentTest = 1;
-var prefs = Components.classes["@mozilla.org/preferences-service;1"]
-            .getService(Components.interfaces.nsIPrefBranch);
+var prefs = SpecialPowers.Cc["@mozilla.org/preferences-service;1"]
+            .getService(SpecialPowers.Ci.nsIPrefBranch);
 var quota;
 var origBlockDisplay;
 var origBlockActive;
 
 function doNextTest()
 {
   slave = frame;
 
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-
   switch (currentTest)
   {
     // Initialy setup the quota to testing value of 1024B and
     // set a 500 bytes key with name length 1 (allocate 501 bytes)
     case 1:
       try {
         quota = prefs.getIntPref("dom.storage.default_quota");
       } catch (ex) {
--- a/dom/tests/mochitest/localstorage/test_localStorageQuotaSessionOnly.html
+++ b/dom/tests/mochitest/localstorage/test_localStorageQuotaSessionOnly.html
@@ -3,39 +3,35 @@
 <title>localStorage and DOM quota test</title>
 
 <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
 <script type="text/javascript" src="interOriginTest.js"></script>
 <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
 
 <script type="text/javascript">
 
-netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
+var currentTest = 1;
+var prefs = SpecialPowers.Cc["@mozilla.org/preferences-service;1"]
+            .getService(SpecialPowers.Ci.nsIPrefBranch);
+var io = SpecialPowers.Cc["@mozilla.org/network/io-service;1"]
+  .getService(SpecialPowers.Ci.nsIIOService);
+var uri = io.newURI(window.location, "", null);
+var cp = SpecialPowers.Cc["@mozilla.org/cookie/permission;1"]
+  .getService(SpecialPowers.Ci.nsICookiePermission);
 
-var currentTest = 1;
-var prefs = Components.classes["@mozilla.org/preferences-service;1"]
-            .getService(Components.interfaces.nsIPrefBranch);
-var io = Components.classes["@mozilla.org/network/io-service;1"]
-  .getService(Components.interfaces.nsIIOService);
-var uri = io.newURI(window.location, "", null);
-var cp = Components.classes["@mozilla.org/cookie/permission;1"]
-  .getService(Components.interfaces.nsICookiePermission);
-
-cp.setAccess(uri, Components.interfaces.nsICookiePermission.ACCESS_SESSION);
+cp.setAccess(uri, SpecialPowers.Ci.nsICookiePermission.ACCESS_SESSION);
 
 var quota;
 var origBlockDisplay;
 var origBlockActive;
 
 function doNextTest()
 {
   slave = frame;
 
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-
   switch (currentTest)
   {
     // Initialy setup the quota to testing value of 1024B and
     // set a 500 bytes key with name length 1 (allocate 501 bytes)
     case 1:
       try {
         quota = prefs.getIntPref("dom.storage.default_quota");
       } catch (ex) {
@@ -113,17 +109,17 @@ function doNextTest()
       slaveOrigin = "https://test2.example.com";
       slave.location = slaveOrigin + slavePath + "frameQuotaSessionOnly.html?clear";
       break;
 
     default:
       prefs.setIntPref("dom.storage.default_quota", quota);
       prefs.setBoolPref("security.mixed_content.block_display_content", origBlockDisplay);
       prefs.setBoolPref("security.mixed_content.block_active_content", origBlockActive);
-      cp.setAccess(uri, Components.interfaces.nsICookiePermission.ACCESS_DEFAULT);
+      cp.setAccess(uri, SpecialPowers.Ci.nsICookiePermission.ACCESS_DEFAULT);
       SimpleTest.finish();
   }
 
   ++currentTest;
 }
 
 function doStep()
 {
--- a/dom/workers/test/test_suspend.html
+++ b/dom/workers/test/test_suspend.html
@@ -27,19 +27,18 @@
   var resumed = false;
   var finished = false;
 
   var interval;
   var oldMessageCount;
   var waitCount = 0;
 
   function setCachePref(enabled) {
-    netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
-    var prefBranch = Components.classes["@mozilla.org/preferences-service;1"]
-                               .getService(Components.interfaces.nsIPrefBranch);
+    var prefBranch = SpecialPowers.Cc["@mozilla.org/preferences-service;1"]
+                                  .getService(SpecialPowers.Ci.nsIPrefBranch);
     if (enabled) {
       prefBranch.setBoolPref("browser.sessionhistory.cache_subframes", true);
     }
     else {
       try {
         prefBranch.clearUserPref("browser.sessionhistory.cache_subframes");
       } catch (e) { /* Pref didn't exist, meh */ }
     }
--- a/editor/libeditor/html/tests/test_CF_HTML_clipboard.html
+++ b/editor/libeditor/html/tests/test_CF_HTML_clipboard.html
@@ -18,38 +18,37 @@ https://bugzilla.mozilla.org/show_bug.cg
 </div>
 <pre id="test">
 <script type="application/javascript">
 
 /** Test for Bug 572642 **/
 
 function copyCF_HTML(cfhtml, success, failure) {
   netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-  const Cc = Components.classes;
-  const Ci = Components.interfaces;
+  const Cc = SpecialPowers.Cc;
+  const Ci = SpecialPowers.Ci;
   const CF_HTML = "application/x-moz-nativehtml";
 
   function getLoadContext() {
-    return window.QueryInterface(Ci.nsIInterfaceRequestor)
+    return SpecialPowers.wrap(window).QueryInterface(Ci.nsIInterfaceRequestor)
                  .getInterface(Ci.nsIWebNavigation)
                  .QueryInterface(Ci.nsILoadContext);
   }
 
   var cb = Cc["@mozilla.org/widget/clipboard;1"].
            getService(Ci.nsIClipboard);
 
   var counter = 0;
   function copyCF_HTML_worker(success, failure) {
     if (++counter > 50) {
       ok(false, "Timed out while polling clipboard for pasted data");
       failure();
       return;
     }
 
-    netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
     var flavors = [CF_HTML];
     if (!cb.hasDataMatchingFlavors(flavors, flavors.length, cb.kGlobalClipboard)) {
       setTimeout(function() copyCF_HTML_worker(success, failure), 100);
       return;
     }
 
     var trans = Cc["@mozilla.org/widget/transferable;1"].
                 createInstance(Ci.nsITransferable);
--- a/editor/libeditor/html/tests/test_contenteditable_focus.html
+++ b/editor/libeditor/html/tests/test_contenteditable_focus.html
@@ -40,38 +40,33 @@
 
 <script class="testbody" type="application/javascript">
 
 SimpleTest.waitForExplicitFinish();
 SimpleTest.waitForFocus(runTests, window);
 
 function runTests()
 {
-  try {
-    runTestsInternal();
-  } catch (e) {
-    ok(false, "Unexpected error happened: " + e);
-  }
+  runTestsInternal();
   SimpleTest.finish();
 }
 
 function runTestsInternal()
 {
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-  var fm = Components.classes["@mozilla.org/focus-manager;1"].
-             getService(Components.interfaces.nsIFocusManager);
+  var fm = SpecialPowers.Cc["@mozilla.org/focus-manager;1"].
+             getService(SpecialPowers.Ci.nsIFocusManager);
   // XXX using selCon for checking the visibility of the caret, however,
   // selCon is shared in document, cannot get the element of owner of the
   // caret from javascript?
-  var selCon =
-      window.QueryInterface(Components.interfaces.nsIInterfaceRequestor).
-        getInterface(Components.interfaces.nsIWebNavigation).
-        QueryInterface(Components.interfaces.nsIInterfaceRequestor).
-        getInterface(Components.interfaces.nsISelectionDisplay).
-        QueryInterface(Components.interfaces.nsISelectionController);
+  var selCon = SpecialPowers.wrap(window).
+        QueryInterface(SpecialPowers.Ci.nsIInterfaceRequestor).
+        getInterface(SpecialPowers.Ci.nsIWebNavigation).
+        QueryInterface(SpecialPowers.Ci.nsIInterfaceRequestor).
+        getInterface(SpecialPowers.Ci.nsISelectionDisplay).
+        QueryInterface(SpecialPowers.Ci.nsISelectionController);
   var selection = window.getSelection();
 
   var inputText = document.getElementById("inputText");
   var inputTextReadonly = document.getElementById("inputTextReadonly");
   var inputButton = document.getElementById("inputButton");
   var button = document.getElementById("button");
   var editor = document.getElementById("editor");
   var inputTextInEditor = document.getElementById("inputTextInEditor");
@@ -88,101 +83,101 @@ function runTestsInternal()
 
   // XXX if there is a contenteditable element, HTML editor sets dom selection
   // to first editable node, but this makes inconsistency with normal document
   // behavior.
   todo_is(selection.rangeCount, 0, "unexpected selection range is there");
   ok(!selCon.caretVisible, "caret is visible in the document");
   // Move focus to inputTextInEditor
   inputTextInEditor.focus();
-  is(fm.focusedElement, inputTextInEditor,
+  is(SpecialPowers.unwrap(fm.focusedElement), inputTextInEditor,
      "inputTextInEditor didn't get focus");
   todo_is(selection.rangeCount, 0, "unexpected selection range is there");
   ok(selCon.caretVisible, "caret isn't visible in the inputTextInEditor");
   // Move focus to the editor
   editor.focus();
-  is(fm.focusedElement, editor,
+  is(SpecialPowers.unwrap(fm.focusedElement), editor,
      "editor didn't get focus");
   is(selection.rangeCount, 1,
      "there is no selection range when editor has focus");
   var range = selection.getRangeAt(0);
   ok(range.collapsed, "the selection range isn't collapsed");
   var startNode = range.startContainer;
   is(startNode.nodeType, 1, "the caret isn't set to the div node");
   is(startNode, editor, "the caret isn't set to the editor");
   ok(selCon.caretVisible, "caret isn't visible in the editor");
   // Move focus to other editor
   otherEditor.focus();
-  is(fm.focusedElement, otherEditor,
+  is(SpecialPowers.unwrap(fm.focusedElement), otherEditor,
      "the other editor didn't get focus");
   is(selection.rangeCount, 1,
      "there is no selection range when the other editor has focus");
   range = selection.getRangeAt(0);
   ok(range.collapsed, "the selection range isn't collapsed");
   var startNode = range.startContainer;
   is(startNode.nodeType, 1, "the caret isn't set to the div node");
   is(startNode, otherEditor, "the caret isn't set to the other editor");
   ok(selCon.caretVisible, "caret isn't visible in the other editor");
   // Move focus to inputTextInEditor
   inputTextInEditor.focus();
-  is(fm.focusedElement, inputTextInEditor,
+  is(SpecialPowers.unwrap(fm.focusedElement), inputTextInEditor,
      "inputTextInEditor didn't get focus #2");
   is(selection.rangeCount, 1, "selection range is lost from the document");
   range = selection.getRangeAt(0);
   ok(range.collapsed, "the selection range isn't collapsed");
   var startNode = range.startContainer;
   is(startNode.nodeType, 1, "the caret isn't set to the div node");
   // XXX maybe, the caret can stay on the other editor if it's better.
   is(startNode, editor,
      "the caret should stay on the other editor");
   ok(selCon.caretVisible,
      "caret isn't visible in the inputTextInEditor");
   // Move focus to the other editor again
   otherEditor.focus();
-  is(fm.focusedElement, otherEditor,
+  is(SpecialPowers.unwrap(fm.focusedElement), otherEditor,
      "the other editor didn't get focus #2");
   // Set selection to the span element in the editor (unfocused)
   range = document.createRange();
   range.setStart(spanInEditor.firstChild, 5);
   selection.removeAllRanges();
   selection.addRange(range);
   is(selection.rangeCount, 1, "selection range is lost from the document");
-  is(fm.focusedElement, otherEditor,
+  is(SpecialPowers.unwrap(fm.focusedElement), otherEditor,
      "the other editor shouldn't lose focus by selection range change");
   ok(selCon.caretVisible, "caret isn't visible in inputTextInEditor");
   // Move focus to the editor
   editor.focus();
-  is(fm.focusedElement, editor,
+  is(SpecialPowers.unwrap(fm.focusedElement), editor,
      "the editor didn't get focus #2");
   is(selection.rangeCount, 1, "selection range is lost from the document");
   range = selection.getRangeAt(0);
   ok(range.collapsed, "the selection range isn't collapsed");
   is(range.startOffset, 5,
      "the caret is moved when the editor was focused (offset)");
   var startNode = range.startContainer;
   is(startNode.nodeType, 3, "the caret isn't in text node");
   is(startNode.parentNode, spanInEditor,
      "the caret is moved when the editor was focused (node)");
   ok(selCon.caretVisible, "caret isn't visible in the editor (spanInEditor)");
 
   // Move focus to each focusable element in the editor.
   function testFocusMove(aSetFocusElementID, aFocusable, aCaretVisible)
   {
     editor.focus();
-    is(fm.focusedElement, editor,
+    is(SpecialPowers.unwrap(fm.focusedElement), editor,
        "testFocusMove: the editor didn't get focus at initializing (" +
        aSetFocusElementID + ")");
     var setFocusElement = document.getElementById(aSetFocusElementID);
     setFocusElement.focus();
     if (aFocusable) {
-      is(fm.focusedElement, setFocusElement,
+      is(SpecialPowers.unwrap(fm.focusedElement), setFocusElement,
          "testFocusMove: the " + aSetFocusElementID +
          " didn't get focus");
     } else {
-      is(fm.focusedElement, editor,
+      is(SpecialPowers.unwrap(fm.focusedElement), editor,
          "testFocusMove: the editor lost focus by focus() of the " +
          aSetFocusElementID);
     }
     if (aCaretVisible) {
       ok(selCon.caretVisible,
          "testFocusMove: caret isn't visible when the " +
          aSetFocusElementID + " has focus");
     } else {
--- a/editor/libeditor/html/tests/test_htmleditor_keyevent_handling.html
+++ b/editor/libeditor/html/tests/test_htmleditor_keyevent_handling.html
@@ -27,20 +27,19 @@ var htmlEditor = document.getElementById
 
 const kIsMac = navigator.platform.indexOf("Mac") == 0;
 const kIsWin = navigator.platform.indexOf("Win") == 0;
 const kIsLinux = navigator.platform.indexOf("Linux") == 0 || navigator.platform.indexOf("SunOS") == 0 ;
 
 function runTests()
 {
   document.execCommand("stylewithcss", false, "true");
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
 
-  var fm = Components.classes["@mozilla.org/focus-manager;1"].
-    getService(Components.interfaces.nsIFocusManager);
+  var fm = SpecialPowers.Cc["@mozilla.org/focus-manager;1"].
+    getService(SpecialPowers.Ci.nsIFocusManager);
 
   var capturingPhase = { fired: false, prevented: false };
   var bubblingPhase = { fired: false, prevented: false };
 
   var listener = {
     handleEvent: function _hv(aEvent)
     {
       is(aEvent.type, "keypress", "unexpected event is handled");
@@ -121,17 +120,17 @@ function runTests()
 
     if (document.activeElement) {
       document.activeElement.blur();
     }
 
     aDescription += ": "
 
     aElement.focus();
-    is(fm.focusedElement, aElement, aDescription + "failed to move focus");
+    is(SpecialPowers.unwrap(fm.focusedElement), aElement, aDescription + "failed to move focus");
 
     // Modifier keys:
     //   Basically, modifier keys shouldn't cause keypress event.  However,
     //   even if it were dispatched by widget's bug, editor should consume
     //   it when editor is editable.
     reset("");
     synthesizeKey("VK_META", { type: "keypress" });
     check(aDescription + "Meta", true, true, !aIsReadonly);
@@ -296,332 +295,332 @@ function runTests()
     reset("a");
     synthesizeKey("VK_TAB", { });
     check(aDescription + "Tab",
           true, true, !aIsTabbable && !aIsReadonly);
     is(aElement.innerHTML,
        aIsTabbable || aIsReadonly ? "a" :
          aIsPlaintext ? "a\t" : "a&nbsp;&nbsp;&nbsp; <br>",
        aDescription + "Tab");
-    is(fm.focusedElement, aElement,
+    is(SpecialPowers.unwrap(fm.focusedElement), aElement,
        aDescription + "focus moved unexpectedly (Tab)");
 
     reset("a");
     synthesizeKey("VK_TAB", { shiftKey: true });
     check(aDescription + "Shift+Tab", true, true, false);
     is(aElement.innerHTML, "a", aDescription + "Shift+Tab");
-    is(fm.focusedElement, aElement,
+    is(SpecialPowers.unwrap(fm.focusedElement), aElement,
        aDescription + "focus moved unexpectedly (Shift+Tab)");
 
     // Ctrl+Tab may be consumed by tabbrowser but editor shouldn't consume this.
     reset("a");
     synthesizeKey("VK_TAB", { ctrlKey: true });
     check(aDescription + "Ctrl+Tab", true, true, false);
     is(aElement.innerHTML, "a", aDescription + "Ctrl+Tab");
-    is(fm.focusedElement, aElement,
+    is(SpecialPowers.unwrap(fm.focusedElement), aElement,
        aDescription + "focus moved unexpectedly (Ctrl+Tab)");
 
     reset("a");
     synthesizeKey("VK_TAB", { altKey: true });
     check(aDescription + "Alt+Tab", true, true, false);
     is(aElement.innerHTML, "a", aDescription + "Alt+Tab");
-    is(fm.focusedElement, aElement,
+    is(SpecialPowers.unwrap(fm.focusedElement), aElement,
        aDescription + "focus moved unexpectedly (Alt+Tab)");
 
     reset("a");
     synthesizeKey("VK_TAB", { metaKey: true });
     check(aDescription + "Meta+Tab", true, true, false);
     is(aElement.innerHTML, "a", aDescription + "Meta+Tab");
-    is(fm.focusedElement, aElement,
+    is(SpecialPowers.unwrap(fm.focusedElement), aElement,
        aDescription + "focus moved unexpectedly (Meta+Tab)");
 
     reset("a");
     synthesizeKey("VK_TAB", { osKey: true });
     check(aDescription + "OS+Tab", true, true, false);
     is(aElement.innerHTML, "a", aDescription + "OS+Tab");
-    is(fm.focusedElement, aElement,
+    is(SpecialPowers.unwrap(fm.focusedElement), aElement,
        aDescription + "focus moved unexpectedly (OS+Tab)");
 
     // Indent/Outdent tests:
     // UL
     resetForIndent("<ul><li id=\"target\">ul list item</li></ul>");
     synthesizeKey("VK_TAB", { });
     check(aDescription + "Tab on UL",
           true, true, !aIsTabbable && !aIsReadonly);
     is(aElement.innerHTML,
        aIsReadonly || aIsTabbable ?
          "<ul><li id=\"target\">ul list item</li></ul>" :
          aIsPlaintext ? "<ul><li id=\"target\">ul list item\t</li></ul>" :
            "<ul><ul><li id=\"target\">ul list item</li></ul></ul>",
        aDescription + "Tab on UL");
-    is(fm.focusedElement, aElement,
+    is(SpecialPowers.unwrap(fm.focusedElement), aElement,
        aDescription + "focus moved unexpectedly (Tab on UL)");
     synthesizeKey("VK_TAB", { shiftKey: true });
     check(aDescription + "Shift+Tab after Tab on UL",
           true, true, !aIsTabbable && !aIsReadonly && !aIsPlaintext);
     is(aElement.innerHTML,
        aIsReadonly || aIsTabbable || (!aIsPlaintext) ?
          "<ul><li id=\"target\">ul list item</li></ul>" :
          "<ul><li id=\"target\">ul list item\t</li></ul>",
        aDescription + "Shift+Tab after Tab on UL");
-    is(fm.focusedElement, aElement,
+    is(SpecialPowers.unwrap(fm.focusedElement), aElement,
        aDescription + "focus moved unexpectedly (Shift+Tab after Tab on UL)");
 
     resetForIndent("<ul><li id=\"target\">ul list item</li></ul>");
     synthesizeKey("VK_TAB", { shiftKey: true });
     check(aDescription + "Shift+Tab on UL",
           true, true, !aIsTabbable && !aIsReadonly && !aIsPlaintext);
     is(aElement.innerHTML,
        aIsReadonly || aIsTabbable || aIsPlaintext ?
          "<ul><li id=\"target\">ul list item</li></ul>" : "ul list item",
        aDescription + "Shift+Tab on UL");
-    is(fm.focusedElement, aElement,
+    is(SpecialPowers.unwrap(fm.focusedElement), aElement,
        aDescription + "focus moved unexpectedly (Shift+Tab on UL)");
 
     // Ctrl+Tab may be consumed by tabbrowser but editor shouldn't consume this.
     resetForIndent("<ul><li id=\"target\">ul list item</li></ul>");
     synthesizeKey("VK_TAB", { ctrlKey: true });
     check(aDescription + "Ctrl+Tab on UL", true, true, false);
     is(aElement.innerHTML, "<ul><li id=\"target\">ul list item</li></ul>",
        aDescription + "Ctrl+Tab on UL");
-    is(fm.focusedElement, aElement,
+    is(SpecialPowers.unwrap(fm.focusedElement), aElement,
        aDescription + "focus moved unexpectedly (Ctrl+Tab on UL)");
 
     resetForIndent("<ul><li id=\"target\">ul list item</li></ul>");
     synthesizeKey("VK_TAB", { altKey: true });
     check(aDescription + "Alt+Tab on UL", true, true, false);
     is(aElement.innerHTML, "<ul><li id=\"target\">ul list item</li></ul>",
        aDescription + "Alt+Tab on UL");
-    is(fm.focusedElement, aElement,
+    is(SpecialPowers.unwrap(fm.focusedElement), aElement,
        aDescription + "focus moved unexpectedly (Alt+Tab on UL)");
 
     resetForIndent("<ul><li id=\"target\">ul list item</li></ul>");
     synthesizeKey("VK_TAB", { metaKey: true });
     check(aDescription + "Meta+Tab on UL", true, true, false);
     is(aElement.innerHTML, "<ul><li id=\"target\">ul list item</li></ul>",
        aDescription + "Meta+Tab on UL");
-    is(fm.focusedElement, aElement,
+    is(SpecialPowers.unwrap(fm.focusedElement), aElement,
        aDescription + "focus moved unexpectedly (Meta+Tab on UL)");
 
     resetForIndent("<ul><li id=\"target\">ul list item</li></ul>");
     synthesizeKey("VK_TAB", { osKey: true });
     check(aDescription + "OS+Tab on UL", true, true, false);
     is(aElement.innerHTML, "<ul><li id=\"target\">ul list item</li></ul>",
        aDescription + "OS+Tab on UL");
-    is(fm.focusedElement, aElement,
+    is(SpecialPowers.unwrap(fm.focusedElement), aElement,
        aDescription + "focus moved unexpectedly (OS+Tab on UL)");
 
     // OL
     resetForIndent("<ol><li id=\"target\">ol list item</li></ol>");
     synthesizeKey("VK_TAB", { });
     check(aDescription + "Tab on OL",
           true, true, !aIsTabbable && !aIsReadonly);
     is(aElement.innerHTML,
        aIsReadonly || aIsTabbable ?
          "<ol><li id=\"target\">ol list item</li></ol>" :
          aIsPlaintext ? "<ol><li id=\"target\">ol list item\t</li></ol>" :
            "<ol><ol><li id=\"target\">ol list item</li></ol></ol>",
        aDescription + "Tab on OL");
-    is(fm.focusedElement, aElement,
+    is(SpecialPowers.unwrap(fm.focusedElement), aElement,
        aDescription + "focus moved unexpectedly (Tab on OL)");
     synthesizeKey("VK_TAB", { shiftKey: true });
     check(aDescription + "Shift+Tab after Tab on OL",
           true, true, !aIsTabbable && !aIsReadonly && !aIsPlaintext);
     is(aElement.innerHTML,
        aIsReadonly || aIsTabbable || (!aIsPlaintext) ?
          "<ol><li id=\"target\">ol list item</li></ol>" :
          "<ol><li id=\"target\">ol list item\t</li></ol>",
        aDescription + "Shift+Tab after Tab on OL");
-    is(fm.focusedElement, aElement,
+    is(SpecialPowers.unwrap(fm.focusedElement), aElement,
        aDescription + "focus moved unexpectedly (Shift+Tab after Tab on OL)");
 
     resetForIndent("<ol><li id=\"target\">ol list item</li></ol>");
     synthesizeKey("VK_TAB", { shiftKey: true });
     check(aDescription + "Shift+Tab on OL",
           true, true, !aIsTabbable && !aIsReadonly && !aIsPlaintext);
     is(aElement.innerHTML,
        aIsReadonly || aIsTabbable || aIsPlaintext ?
          "<ol><li id=\"target\">ol list item</li></ol>" : "ol list item",
        aDescription + "Shfit+Tab on OL");
-    is(fm.focusedElement, aElement,
+    is(SpecialPowers.unwrap(fm.focusedElement), aElement,
        aDescription + "focus moved unexpectedly (Shift+Tab on OL)");
 
     // Ctrl+Tab may be consumed by tabbrowser but editor shouldn't consume this.
     resetForIndent("<ol><li id=\"target\">ol list item</li></ol>");
     synthesizeKey("VK_TAB", { ctrlKey: true });
     check(aDescription + "Ctrl+Tab on OL", true, true, false);
     is(aElement.innerHTML, "<ol><li id=\"target\">ol list item</li></ol>",
        aDescription + "Ctrl+Tab on OL");
-    is(fm.focusedElement, aElement,
+    is(SpecialPowers.unwrap(fm.focusedElement), aElement,
        aDescription + "focus moved unexpectedly (Ctrl+Tab on OL)");
 
     resetForIndent("<ol><li id=\"target\">ol list item</li></ol>");
     synthesizeKey("VK_TAB", { altKey: true });
     check(aDescription + "Alt+Tab on OL", true, true, false);
     is(aElement.innerHTML, "<ol><li id=\"target\">ol list item</li></ol>",
        aDescription + "Alt+Tab on OL");
-    is(fm.focusedElement, aElement,
+    is(SpecialPowers.unwrap(fm.focusedElement), aElement,
        aDescription + "focus moved unexpectedly (Alt+Tab on OL)");
 
     resetForIndent("<ol><li id=\"target\">ol list item</li></ol>");
     synthesizeKey("VK_TAB", { metaKey: true });
     check(aDescription + "Meta+Tab on OL", true, true, false);
     is(aElement.innerHTML, "<ol><li id=\"target\">ol list item</li></ol>",
        aDescription + "Meta+Tab on OL");
-    is(fm.focusedElement, aElement,
+    is(SpecialPowers.unwrap(fm.focusedElement), aElement,
        aDescription + "focus moved unexpectedly (Meta+Tab on OL)");
 
     resetForIndent("<ol><li id=\"target\">ol list item</li></ol>");
     synthesizeKey("VK_TAB", { osKey: true });
     check(aDescription + "OS+Tab on OL", true, true, false);
     is(aElement.innerHTML, "<ol><li id=\"target\">ol list item</li></ol>",
        aDescription + "OS+Tab on OL");
-    is(fm.focusedElement, aElement,
+    is(SpecialPowers.unwrap(fm.focusedElement), aElement,
        aDescription + "focus moved unexpectedly (OS+Tab on OL)");
 
     // TD
     resetForIndent("<table><tr><td id=\"target\">td</td></tr></table>");
     synthesizeKey("VK_TAB", { });
     check(aDescription + "Tab on TD",
           true, true, !aIsTabbable && !aIsReadonly);
     is(aElement.innerHTML,
        aIsTabbable || aIsReadonly ?
          "<table><tbody><tr><td id=\"target\">td</td></tr></tbody></table>" :
          aIsPlaintext ? "<table><tbody><tr><td id=\"target\">td\t</td></tr></tbody></table>" :
            "<table><tbody><tr><td id=\"target\">td</td></tr><tr><td style=\"vertical-align: top;\"><br></td></tr></tbody></table>",
        aDescription + "Tab on TD");
-    is(fm.focusedElement, aElement,
+    is(SpecialPowers.unwrap(fm.focusedElement), aElement,
        aDescription + "focus moved unexpectedly (Tab on TD)");
     synthesizeKey("VK_TAB", { shiftKey: true });
     check(aDescription + "Shift+Tab after Tab on TD",
           true, true, !aIsTabbable && !aIsReadonly && !aIsPlaintext);
     is(aElement.innerHTML,
        aIsTabbable || aIsReadonly ?
          "<table><tbody><tr><td id=\"target\">td</td></tr></tbody></table>" :
          aIsPlaintext ? "<table><tbody><tr><td id=\"target\">td\t</td></tr></tbody></table>" :
            "<table><tbody><tr><td id=\"target\">td</td></tr><tr><td style=\"vertical-align: top;\"><br></td></tr></tbody></table>",
        aDescription + "Shift+Tab after Tab on TD");
-    is(fm.focusedElement, aElement,
+    is(SpecialPowers.unwrap(fm.focusedElement), aElement,
        aDescription + "focus moved unexpectedly (Shift+Tab after Tab on TD)");
 
     resetForIndent("<table><tr><td id=\"target\">td</td></tr></table>");
     synthesizeKey("VK_TAB", { shiftKey: true });
     check(aDescription + "Shift+Tab on TD", true, true, false);
     is(aElement.innerHTML,
        "<table><tbody><tr><td id=\"target\">td</td></tr></tbody></table>",
        aDescription + "Shift+Tab on TD");
-    is(fm.focusedElement, aElement,
+    is(SpecialPowers.unwrap(fm.focusedElement), aElement,
        aDescription + "focus moved unexpectedly (Shift+Tab on TD)");
 
     // Ctrl+Tab may be consumed by tabbrowser but editor shouldn't consume this.
     resetForIndent("<table><tr><td id=\"target\">td</td></tr></table>");
     synthesizeKey("VK_TAB", { ctrlKey: true });
     check(aDescription + "Ctrl+Tab on TD", true, true, false);
     is(aElement.innerHTML,
        "<table><tbody><tr><td id=\"target\">td</td></tr></tbody></table>",
        aDescription + "Ctrl+Tab on TD");
-    is(fm.focusedElement, aElement,
+    is(SpecialPowers.unwrap(fm.focusedElement), aElement,
        aDescription + "focus moved unexpectedly (Ctrl+Tab on TD)");
 
     resetForIndent("<table><tr><td id=\"target\">td</td></tr></table>");
     synthesizeKey("VK_TAB", { altKey: true });
     check(aDescription + "Alt+Tab on TD", true, true, false);
     is(aElement.innerHTML,
        "<table><tbody><tr><td id=\"target\">td</td></tr></tbody></table>",
        aDescription + "Alt+Tab on TD");
-    is(fm.focusedElement, aElement,
+    is(SpecialPowers.unwrap(fm.focusedElement), aElement,
        aDescription + "focus moved unexpectedly (Alt+Tab on TD)");
 
     resetForIndent("<table><tr><td id=\"target\">td</td></tr></table>");
     synthesizeKey("VK_TAB", { metaKey: true });
     check(aDescription + "Meta+Tab on TD", true, true, false);
     is(aElement.innerHTML,
        "<table><tbody><tr><td id=\"target\">td</td></tr></tbody></table>",
        aDescription + "Meta+Tab on TD");
-    is(fm.focusedElement, aElement,
+    is(SpecialPowers.unwrap(fm.focusedElement), aElement,
        aDescription + "focus moved unexpectedly (Meta+Tab on TD)");
 
     resetForIndent("<table><tr><td id=\"target\">td</td></tr></table>");
     synthesizeKey("VK_TAB", { osKey: true });
     check(aDescription + "OS+Tab on TD", true, true, false);
     is(aElement.innerHTML,
        "<table><tbody><tr><td id=\"target\">td</td></tr></tbody></table>",
        aDescription + "OS+Tab on TD");
-    is(fm.focusedElement, aElement,
+    is(SpecialPowers.unwrap(fm.focusedElement), aElement,
        aDescription + "focus moved unexpectedly (OS+Tab on TD)");
 
     // TH
     resetForIndent("<table><tr><th id=\"target\">th</th></tr></table>");
     synthesizeKey("VK_TAB", { });
     check(aDescription + "Tab on TH",
           true, true, !aIsTabbable && !aIsReadonly);
     is(aElement.innerHTML,
        aIsTabbable || aIsReadonly ?
          "<table><tbody><tr><th id=\"target\">th</th></tr></tbody></table>" :
          aIsPlaintext ? "<table><tbody><tr><th id=\"target\">th\t</th></tr></tbody></table>" :
            "<table><tbody><tr><th id=\"target\">th</th></tr><tr><td style=\"vertical-align: top;\"><br></td></tr></tbody></table>",
        aDescription + "Tab on TH");
-    is(fm.focusedElement, aElement,
+    is(SpecialPowers.unwrap(fm.focusedElement), aElement,
        aDescription + "focus moved unexpectedly (Tab on TH)");
     synthesizeKey("VK_TAB", { shiftKey: true });
     check(aDescription + "Shift+Tab after Tab on TH",
           true, true, !aIsTabbable && !aIsReadonly && !aIsPlaintext);
     is(aElement.innerHTML,
        aIsTabbable || aIsReadonly ?
          "<table><tbody><tr><th id=\"target\">th</th></tr></tbody></table>" :
          aIsPlaintext ? "<table><tbody><tr><th id=\"target\">th\t</th></tr></tbody></table>" :
            "<table><tbody><tr><th id=\"target\">th</th></tr><tr><td style=\"vertical-align: top;\"><br></td></tr></tbody></table>",
        aDescription + "Shift+Tab after Tab on TH");
-    is(fm.focusedElement, aElement,
+    is(SpecialPowers.unwrap(fm.focusedElement), aElement,
        aDescription + "focus moved unexpectedly (Shift+Tab after Tab on TH)");
 
     resetForIndent("<table><tr><th id=\"target\">th</th></tr></table>");
     synthesizeKey("VK_TAB", { shiftKey: true });
     check(aDescription + "Shift+Tab on TH", true, true, false);
     is(aElement.innerHTML,
        "<table><tbody><tr><th id=\"target\">th</th></tr></tbody></table>",
        aDescription + "Shift+Tab on TH");
-    is(fm.focusedElement, aElement,
+    is(SpecialPowers.unwrap(fm.focusedElement), aElement,
        aDescription + "focus moved unexpectedly (Shift+Tab on TH)");
 
     // Ctrl+Tab may be consumed by tabbrowser but editor shouldn't consume this.
     resetForIndent("<table><tr><th id=\"target\">th</th></tr></table>");
     synthesizeKey("VK_TAB", { ctrlKey: true });
     check(aDescription + "Ctrl+Tab on TH", true, true, false);
     is(aElement.innerHTML,
        "<table><tbody><tr><th id=\"target\">th</th></tr></tbody></table>",
        aDescription + "Ctrl+Tab on TH");
-    is(fm.focusedElement, aElement,
+    is(SpecialPowers.unwrap(fm.focusedElement), aElement,
        aDescription + "focus moved unexpectedly (Ctrl+Tab on TH)");
 
     resetForIndent("<table><tr><th id=\"target\">th</th></tr></table>");
     synthesizeKey("VK_TAB", { altKey: true });
     check(aDescription + "Alt+Tab on TH", true, true, false);
     is(aElement.innerHTML,
        "<table><tbody><tr><th id=\"target\">th</th></tr></tbody></table>",
        aDescription + "Alt+Tab on TH");
-    is(fm.focusedElement, aElement,
+    is(SpecialPowers.unwrap(fm.focusedElement), aElement,
        aDescription + "focus moved unexpectedly (Alt+Tab on TH)");
 
     resetForIndent("<table><tr><th id=\"target\">th</th></tr></table>");
     synthesizeKey("VK_TAB", { metaKey: true });
     check(aDescription + "Meta+Tab on TH", true, true, false);
     is(aElement.innerHTML,
        "<table><tbody><tr><th id=\"target\">th</th></tr></tbody></table>",
        aDescription + "Meta+Tab on TH");
-    is(fm.focusedElement, aElement,
+    is(SpecialPowers.unwrap(fm.focusedElement), aElement,
        aDescription + "focus moved unexpectedly (Meta+Tab on TH)");
 
     resetForIndent("<table><tr><th id=\"target\">th</th></tr></table>");
     synthesizeKey("VK_TAB", { osKey: true });
     check(aDescription + "OS+Tab on TH", true, true, false);
     is(aElement.innerHTML,
        "<table><tbody><tr><th id=\"target\">th</th></tr></tbody></table>",
        aDescription + "OS+Tab on TH");
-    is(fm.focusedElement, aElement,
+    is(SpecialPowers.unwrap(fm.focusedElement), aElement,
        aDescription + "focus moved unexpectedly (OS+Tab on TH)");
 
     // Esc key:
     //   In all cases, esc key events are not consumed
     reset("abc");
     synthesizeKey("VK_ESCAPE", { });
     check(aDescription + "Esc", true, true, false);
 
@@ -665,21 +664,21 @@ function runTests()
     check(aDescription + "' '", true, true, !aIsReadonly);
     is(aElement.innerHTML,
        aIsReadonly ? "" : aIsPlaintext ? "Mozilla " : "Mozilla <br>",
        aDescription + "typed \"Mozilla \"");
   }
 
   doTest(htmlEditor, "contenteditable=\"true\"", false, true, false);
 
-  const nsIPlaintextEditor = Components.interfaces.nsIPlaintextEditor;
-  var editor =
-    window.QueryInterface(Components.interfaces.nsIInterfaceRequestor).
-      getInterface(Components.interfaces.nsIWebNavigation).
-      QueryInterface(Components.interfaces.nsIDocShell).editor;
+  const nsIPlaintextEditor = SpecialPowers.Ci.nsIPlaintextEditor;
+  var editor = SpecialPowers.wrap(window).
+      QueryInterface(SpecialPowers.Ci.nsIInterfaceRequestor).
+      getInterface(SpecialPowers.Ci.nsIWebNavigation).
+      QueryInterface(SpecialPowers.Ci.nsIDocShell).editor;
   var flags = editor.flags;
   // readonly
   editor.flags = flags | nsIPlaintextEditor.eEditorReadonlyMask;
   doTest(htmlEditor, "readonly HTML editor", true, true, false);
 
   // non-tabbable
   editor.flags = flags & ~(nsIPlaintextEditor.eEditorAllowInteraction);
   doTest(htmlEditor, "non-tabbable HTML editor", false, false, false);
--- a/editor/libeditor/text/tests/test_bug569988.html
+++ b/editor/libeditor/text/tests/test_bug569988.html
@@ -24,45 +24,43 @@ SimpleTest.waitForExplicitFinish();
 SimpleTest.waitForFocus(runTest);
 
 var gPromptInput = null;
 
 function runTest()
 {
   netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
 
-  var os = Components.classes["@mozilla.org/observer-service;1"].
-             getService(Components.interfaces.nsIObserverService);
+  var os = SpecialPowers.Cc["@mozilla.org/observer-service;1"].
+             getService(SpecialPowers.Ci.nsIObserverService);
 
   os.addObserver(onPromptLoad, "common-dialog-loaded", false);
   os.addObserver(onPromptLoad, "tabmodal-dialog-loaded", false);
 
   info("opening prompt...");
   prompt("summary", "text");
   info("prompt is closed");
 
   os.removeObserver(onPromptLoad, "tabmodal-dialog-loaded");
   os.removeObserver(onPromptLoad, "common-dialog-loaded");
   SimpleTest.finish();
 }
 
 function onPromptLoad(subject, topic, data)
 {
   ok(true, "onPromptLoad is called");
-  netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
   gPromptInput = subject.Dialog.ui.loginTextbox;
   gPromptInput.addEventListener("focus", onPromptFocus, false);
   // shift focus to ensure it fires.
   subject.Dialog.ui.button0.focus();
   gPromptInput.focus();
 }
 
 function onPromptFocus() {
   ok(true, "onPromptFocus is called");
-  netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
   gPromptInput.removeEventListener("focus", onPromptFocus, false);
 
   var listener = {
     handleEvent: function _hv(aEvent)
     {
       var isPrevented = aEvent.defaultPrevented;
       ok(!isPrevented, "ESC key event is prevented by editor");
       SpecialPowers.removeSystemEventListener(gPromptInput, "keypress",
--- a/editor/libeditor/text/tests/test_bug596333.html
+++ b/editor/libeditor/text/tests/test_bug596333.html
@@ -32,39 +32,36 @@ function getEditor() {
 
 function getSpellCheckSelection() {
   var editor = getEditor();
   var selcon = editor.selectionController;
   return selcon.getSelection(selcon.SELECTION_SPELLCHECK);
 }
 
 function append(str) {
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-
   var edit = document.getElementById("edit");
   edit.focus();
   edit.selectionStart = edit.selectionEnd = edit.value.length;
   var editor = getEditor();
 
   for (var i = 0; i < str.length; ++i) {
     synthesizeKey(str[i], {});
   }
 }
 
 function getLoadContext() {
-  return window.QueryInterface(Ci.nsIInterfaceRequestor)
-               .getInterface(Ci.nsIWebNavigation)
-               .QueryInterface(Ci.nsILoadContext);
+  return SpecialPowers.wrap(window)
+         .QueryInterface(Ci.nsIInterfaceRequestor)
+         .getInterface(Ci.nsIWebNavigation)
+         .QueryInterface(Ci.nsILoadContext);
 }
 
 function paste(str) {
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-
   var edit = document.getElementById("edit");
-  var Cc = Components.classes, Ci = Components.interfaces;
+  var Cc = SpecialPowers.Cc, Ci = SpecialPowers.Ci;
   var trans = Cc["@mozilla.org/widget/transferable;1"].createInstance(Ci.nsITransferable);
   trans.init(getLoadContext());
   var s = Cc["@mozilla.org/supports-string;1"].createInstance(Ci.nsISupportsString);
   s.data = str;
   trans.setTransferData("text/unicode", s, str.length * 2);
 
   getEditor().pasteTransferable(trans);
 }
@@ -115,18 +112,16 @@ function runTest()
   var edit = document.getElementById("edit");
   edit.focus();
 
   SpecialPowers.Cu.import("resource://gre/modules/AsyncSpellCheckTestHelper.jsm", window);
   onSpellCheck(edit, runOnFocus);
 }
 
 function isSpellingCheckOk() {
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-
   var sel = getSpellCheckSelection();
   var numWords = sel.rangeCount;
 
   is(numWords, gMisspeltWords.length, "Correct number of misspellings and words.");
 
   if (numWords != gMisspeltWords.length)
     return false;
 
--- a/editor/libeditor/text/tests/test_texteditor_keyevent_handling.html
+++ b/editor/libeditor/text/tests/test_texteditor_keyevent_handling.html
@@ -30,20 +30,18 @@ var passwordField = document.getElementB
 var textarea = document.getElementById("textarea");
 
 const kIsMac = navigator.platform.indexOf("Mac") == 0;
 const kIsWin = navigator.platform.indexOf("Win") == 0;
 const kIsLinux = navigator.platform.indexOf("Linux") == 0;
 
 function runTests()
 {
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-
-  var fm = Components.classes["@mozilla.org/focus-manager;1"].
-    getService(Components.interfaces.nsIFocusManager);
+  var fm = SpecialPowers.Cc["@mozilla.org/focus-manager;1"].
+    getService(SpecialPowers.Ci.nsIFocusManager);
 
   var capturingPhase = { fired: false, prevented: false };
   var bubblingPhase = { fired: false, prevented: false };
 
   var listener = {
     handleEvent: function _hv(aEvent)
     {
       is(aEvent.type, "keypress", "unexpected event is handled");
@@ -108,17 +106,17 @@ function runTests()
 
     if (document.activeElement) {
       document.activeElement.blur();
     }
 
     aDescription += ": "
 
     aElement.focus();
-    is(fm.focusedElement, aElement, aDescription + "failed to move focus");
+    is(SpecialPowers.unwrap(fm.focusedElement), aElement, aDescription + "failed to move focus");
 
     // Modifier keys:
     //   Basically, modifier keys shouldn't cause keypress event.  However,
     //   even if it were dispatched by widget's bug, editor should consume
     //   it when editor is editable.
     reset("");
     synthesizeKey("VK_META", { type: "keypress" });
     check(aDescription + "Meta", true, true, !aIsReadonly);
@@ -306,65 +304,65 @@ function runTests()
     //   If editor is tabbable, editor doesn't consume all tab key events.
     //   Otherwise, editor consumes tab key event without any modifier keys.
     reset("a");
     synthesizeKey("VK_TAB", { });
     check(aDescription + "Tab",
           true, true, !aIsTabbable && !aIsReadonly);
     is(aElement.value, !aIsTabbable && !aIsReadonly ? "a\t" : "a",
        aDescription + "Tab");
-    is(fm.focusedElement, aElement,
+    is(SpecialPowers.unwrap(fm.focusedElement), aElement,
        aDescription + "focus moved unexpectedly (Tab)");
 
     // If the editor is not tabbable, make sure that it accepts tab characters
     // even if it's empty.
     if (!aIsTabbable && !aIsReadonly) {
       reset("");
       synthesizeKey("VK_TAB", {});
       check(aDescription + "Tab on empty textarea",
             true, true, !aIsReadonly);
       is(aElement.value, "\t", aDescription + "Tab on empty textarea");
-      is(fm.focusedElement, aElement,
+      is(SpecialPowers.unwrap(fm.focusedElement), aElement,
          aDescription + "focus moved unexpectedly (Tab on empty textarea");
     }
 
     reset("a");
     synthesizeKey("VK_TAB", { shiftKey: true });
     check(aDescription + "Shift+Tab", true, true, false);
     is(aElement.value, "a", aDescription + "Shift+Tab");
-    is(fm.focusedElement, aElement,
+    is(SpecialPowers.unwrap(fm.focusedElement), aElement,
        aDescription + "focus moved unexpectedly (Shift+Tab)");
 
     // Ctrl+Tab may be consumed by tabbrowser but editor shouldn't consume this.
     reset("a");
     synthesizeKey("VK_TAB", { ctrlKey: true });
     check(aDescription + "Ctrl+Tab", true, true, false);
     is(aElement.value, "a", aDescription + "Ctrl+Tab");
-    is(fm.focusedElement, aElement,
+    is(SpecialPowers.unwrap(fm.focusedElement), aElement,
        aDescription + "focus moved unexpectedly (Ctrl+Tab)");
 
     reset("a");
     synthesizeKey("VK_TAB", { altKey: true });
     check(aDescription + "Alt+Tab", true, true, false);
     is(aElement.value, "a", aDescription + "Alt+Tab");
-    is(fm.focusedElement, aElement,
+    is(SpecialPowers.unwrap(fm.focusedElement), aElement,
        aDescription + "focus moved unexpectedly (Alt+Tab)");
 
     reset("a");
     synthesizeKey("VK_TAB", { metaKey: true });
     check(aDescription + "Meta+Tab", true, true, false);
     is(aElement.value, "a", aDescription + "Meta+Tab");
-    is(fm.focusedElement, aElement,
+    is(SpecialPowers.unwrap(fm.focusedElement), aElement,
        aDescription + "focus moved unexpectedly (Meta+Tab)");
 
     reset("a");
     synthesizeKey("VK_TAB", { osKey: true });
     check(aDescription + "OS+Tab", true, true, false);
     is(aElement.value, "a", aDescription + "OS+Tab");
-    is(fm.focusedElement, aElement,
+    is(SpecialPowers.unwrap(fm.focusedElement), aElement,
        aDescription + "focus moved unexpectedly (OS+Tab)");
 
     // Esc key:
     //   In all cases, esc key events are not consumed
     reset("abc");
     synthesizeKey("VK_ESCAPE", { });
     check(aDescription + "Esc", true, true, false);
 
@@ -422,18 +420,18 @@ function runTests()
 
   doTest(textarea, "<textarea>", false, false, true);
 
   textarea.setAttribute("readonly", "readonly");
   doTest(textarea, "<textarea readonly>", false, true, true);
 
   // make non-tabbable plaintext editor
   textarea.removeAttribute("readonly");
-  const nsIPlaintextEditor = Components.interfaces.nsIPlaintextEditor;
-  const nsIDOMNSEditableElement = Components.interfaces.nsIDOMNSEditableElement;
+  const nsIPlaintextEditor = SpecialPowers.Ci.nsIPlaintextEditor;
+  const nsIDOMNSEditableElement = SpecialPowers.Ci.nsIDOMNSEditableElement;
   var editor = SpecialPowers.wrap(textarea).editor;
   var flags = editor.flags;
   editor.flags = flags & ~(nsIPlaintextEditor.eEditorWidgetMask |
                            nsIPlaintextEditor.eEditorAllowInteraction);
   doTest(textarea, "non-tabbable <textarea>", false, false, false);
 
   textarea.setAttribute("readonly", "readonly");
   doTest(textarea, "non-tabbable <textarea readonly>", false, true, false);
--- a/embedding/test/test_bug293834.html
+++ b/embedding/test/test_bug293834.html
@@ -52,19 +52,18 @@ function checkform(doc) {
     ok(doc.getElementById('a-checkbox').checked,
         "Modified checkbox checked state not preserved!");
     ok(doc.getElementById("radioa").checked,
         "Modified radio checked state not preserved!");
     ok(doc.getElementById("aselect").selectedIndex == 0,
         "Modified select selected index not preserved");
 }
 
-netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
-const Cc = Components.classes;
-const Ci = Components.interfaces;
+const Cc = SpecialPowers.Cc;
+const Ci = SpecialPowers.Ci;
 
 function getTempDir() {
     return Cc["@mozilla.org/file/directory_service;1"]
             .getService(Ci.nsIProperties)
             .get("TmpD", Ci.nsILocalFile);
 }
 
 function getFileContents(aFile) {
@@ -82,27 +81,25 @@ function getFileContents(aFile) {
         var str = inputStream.read(inputStream.available());
         data += str;
     } while(str.length > 0);
 
     return data;
 }
 
 function persistDocument(aDoc) {
-    netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
-
     const nsIWBP = Ci.nsIWebBrowserPersist;
     const persistFlags =
                   nsIWBP.PERSIST_FLAGS_REPLACE_EXISTING_FILES
                 | nsIWBP.PERSIST_FLAGS_FROM_CACHE
                 | nsIWBP.PERSIST_FLAGS_AUTODETECT_APPLY_CONVERSION
     const encodingFlags =
                   nsIWBP.ENCODE_FLAGS_ENCODE_BASIC_ENTITIES;
 
-    var ioService = Components.classes["@mozilla.org/network/io-service;1"]
+    var ioService = Cc["@mozilla.org/network/io-service;1"]
                     .getService(Ci.nsIIOService);
 
 
     var file = getTempDir();
     file.append("bug293834-serialized.html");
 
     var persist = Cc["@mozilla.org/embedding/browser/nsWebBrowserPersist;1"]
                     .createInstance(Ci.nsIWebBrowserPersist);
@@ -116,17 +113,16 @@ function persistDocument(aDoc) {
                          aDoc.contentType,
                          encodingFlags, kWrapColumn);
     return getFileContents(file);
 }
 
 SimpleTest.waitForExplicitFinish();
 
 addLoadEvent(function() {
-    netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
     var srcDoc = document.getElementById('source').contentDocument;
     fillform(srcDoc);
     checkform(srcDoc);
     var serializedString = persistDocument(srcDoc);
 
     // We can't access file:/// URLs directly for security reasons,
     // so we have to parse the serialized content string indirectly
     var targetDoc = document.getElementById('dest').contentDocument;
--- a/embedding/test/test_bug449141.html
+++ b/embedding/test/test_bug449141.html
@@ -16,36 +16,34 @@ https://bugzilla.mozilla.org/show_bug.cg
 <pre id="results"></pre>
 <div id="content" style="display: none">
     <iframe src="bug449141_page.html" id="source"></iframe>
 </div>
 <pre id="test">
 <script class="testbody" type="text/javascript">
 /** Test for Bug 449141 **/
 
-netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
-const Cc = Components.classes;
-const Ci = Components.interfaces;
+const Cc = SpecialPowers.Cc;
+const Ci = SpecialPowers.Ci;
 
 function getTempDir() {
     return Cc["@mozilla.org/file/directory_service;1"]
             .getService(Ci.nsIProperties)
             .get("TmpD", Ci.nsILocalFile);
 }
 
 // STATE_STOP from nsIWebProgressListener.idl
 const STATE_STOP = 0x00000010;
 
 var progressListener = {
   onProgressChange: function() {
     /* Ignore progress callback */
   },
   onStateChange: function(aProgress, aRequest, aStateFlag, aStatus) {
     if (aStateFlag & STATE_STOP) {
-      netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
       var dirExists = false;
       var videoExists = false;
 
       var videoFile = getTempDir();
       videoFile.append(this.dirName);
       dirExists = videoFile.exists();
       videoFile.append("320x240.ogv");
       videoExists = videoFile.exists();
@@ -54,26 +52,24 @@ var progressListener = {
       ok(dirExists, 'Directory containing video file should be created');
       ok(videoExists, 'Video should be persisted with document');
       SimpleTest.finish();
     }    
   }
 };
 
 function persistDocument(aDoc) {
-    netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
-
     const nsIWBP = Ci.nsIWebBrowserPersist;
     const persistFlags =
                   nsIWBP.PERSIST_FLAGS_REPLACE_EXISTING_FILES
                 | nsIWBP.PERSIST_FLAGS_AUTODETECT_APPLY_CONVERSION
     const encodingFlags =
                   nsIWBP.ENCODE_FLAGS_ENCODE_BASIC_ENTITIES;
 
-    var ioService = Components.classes["@mozilla.org/network/io-service;1"]
+    var ioService = Cc["@mozilla.org/network/io-service;1"]
                     .getService(Ci.nsIIOService);
 
     var id = Math.round(Math.random() * 10000);
     var dirName = "bug449141_serialized" + id;
     progressListener.dirName = dirName;
 
     var file = getTempDir();
     file.append("bug449141-serialized" + id + ".html");
--- a/embedding/test/test_bug499115.html
+++ b/embedding/test/test_bug499115.html
@@ -33,19 +33,18 @@ https://bugzilla.mozilla.org/show_bug.cg
 
         var startPoint = searchRange.cloneRange();
         startPoint.collapse(true);
 
         var endPoint = searchRange.cloneRange();
         endPoint.collapse(false);
 
         var retRange = null;
-        netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
-        var finder = Components.classes["@mozilla.org/embedcomp/rangefind;1"]
-                               .createInstance(Components.interfaces.nsIFind);
+        var finder = SpecialPowers.Cc["@mozilla.org/embedcomp/rangefind;1"]
+                                  .createInstance(SpecialPowers.Ci.nsIFind);
 
         finder.caseSensitive = false;
 
         while ((retRange = finder.Find(SEARCH_TEXT, searchRange,
                                        startPoint, endPoint))) {
           numMatches++;
 
           // Start next search from end of current match
--- a/embedding/test/test_nsFind.html
+++ b/embedding/test/test_nsFind.html
@@ -16,65 +16,63 @@ https://bugzilla.mozilla.org/show_bug.cg
 </div>
 <pre id="test">
 <script type="application/javascript">
 
 /** Test for Bug 450048 **/
 
   // Check nsFind class and its nsIFind interface.
 
-  netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
-
-  var rf = Components.classes["@mozilla.org/embedcomp/rangefind;1"]
-                     .getService(Components.interfaces.nsIFind);
+  var rf = SpecialPowers.Cc["@mozilla.org/embedcomp/rangefind;1"]
+                        .getService(SpecialPowers.Ci.nsIFind);
 
   var display = window.document.getElementById("display");
   var searchRange = window.document.createRange();
   searchRange.setStart(display, 0);
   searchRange.setEnd(display, display.childNodes.length);
   var startPt = searchRange;
   var endPt = searchRange;
 
   // Check |null| detection on |aPatText| parameter.
   try {
     rf.Find(null, searchRange, startPt, endPt);
 
     ok(false, "Missing NS_ERROR_NULL_POINTER exception");
-  } catch (e if (e instanceof Components.interfaces.nsIException &&
-                 e.result == Components.results.NS_ERROR_NULL_POINTER)) {
+  } catch (e if (e instanceof SpecialPowers.Ci.nsIException &&
+                 e.result == SpecialPowers.Cr.NS_ERROR_NULL_POINTER)) {
     ok(true, null);
   }
 
   // Check |null| detection on |aSearchRange| parameter.
   try {
     rf.Find("", null, startPt, endPt);
 
     ok(false, "Missing NS_ERROR_ILLEGAL_VALUE exception");
-  } catch (e if (e instanceof Components.interfaces.nsIException &&
-                 e.result == Components.results.NS_ERROR_ILLEGAL_VALUE)) {
+  } catch (e if (e instanceof SpecialPowers.Ci.nsIException &&
+                 e.result == SpecialPowers.Cr.NS_ERROR_ILLEGAL_VALUE)) {
     ok(true, null);
   }
 
   // Check |null| detection on |aStartPoint| parameter.
   try {
     rf.Find("", searchRange, null, endPt);
 
     ok(false, "Missing NS_ERROR_ILLEGAL_VALUE exception");
-  } catch (e if (e instanceof Components.interfaces.nsIException &&
-                 e.result == Components.results.NS_ERROR_ILLEGAL_VALUE)) {
+  } catch (e if (e instanceof SpecialPowers.Ci.nsIException &&
+                 e.result == SpecialPowers.Cr.NS_ERROR_ILLEGAL_VALUE)) {
     ok(true, null);
   }
 
   // Check |null| detection on |aEndPoint| parameter.
   try {
     rf.Find("", searchRange, startPt, null);
 
     ok(false, "Missing NS_ERROR_ILLEGAL_VALUE exception");
-  } catch (e if (e instanceof Components.interfaces.nsIException &&
-                 e.result == Components.results.NS_ERROR_ILLEGAL_VALUE)) {
+  } catch (e if (e instanceof SpecialPowers.Ci.nsIException &&
+                 e.result == SpecialPowers.Cr.NS_ERROR_ILLEGAL_VALUE)) {
     ok(true, null);
   }
 
   var searchValue, retRange;
 
   rf.findBackwards = false;
 
   rf.caseSensitive = false;
--- a/extensions/cookie/test/file_testcommon.js
+++ b/extensions/cookie/test/file_testcommon.js
@@ -3,43 +3,40 @@ var gExpectedLoads;
 
 var gPopup;
 
 var gLoads = 0;
 
 function setupTest(uri, cookies, loads) {
   SimpleTest.waitForExplicitFinish();
 
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
+  SpecialPowers.Cc["@mozilla.org/preferences-service;1"]
+               .getService(SpecialPowers.Ci.nsIPrefBranch)
+               .setIntPref("network.cookie.cookieBehavior", 1);
 
-  Components.classes["@mozilla.org/preferences-service;1"]
-            .getService(Components.interfaces.nsIPrefBranch)
-            .setIntPref("network.cookie.cookieBehavior", 1);
-
-  var cs = Components.classes["@mozilla.org/cookiemanager;1"]
-                     .getService(Components.interfaces.nsICookieManager2);
+  var cs = SpecialPowers.Cc["@mozilla.org/cookiemanager;1"]
+                        .getService(SpecialPowers.Ci.nsICookieManager2);
   cs.removeAll();
 
   gExpectedCookies = cookies;
   gExpectedLoads = loads;
 
   // Listen for MessageEvents.
   window.addEventListener("message", messageReceiver, false);
 
   // load a window which contains an iframe; each will attempt to set
   // cookies from their respective domains.
   gPopup = window.open(uri, 'hai', 'width=100,height=100');
 }
 
 function finishTest()
 {
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-  Components.classes["@mozilla.org/preferences-service;1"]
-            .getService(Components.interfaces.nsIPrefBranch)
-            .clearUserPref("network.cookie.cookieBehavior");
+  SpecialPowers.Cc["@mozilla.org/preferences-service;1"]
+               .getService(SpecialPowers.Ci.nsIPrefBranch)
+               .clearUserPref("network.cookie.cookieBehavior");
 
   SimpleTest.finish();
 }
 
 /** Receives MessageEvents to this window. */
 // Count and check loads.
 function messageReceiver(evt)
 {
@@ -62,20 +59,18 @@ function messageReceiver(evt)
 }
 
 // runTest() is run by messageReceiver().
 // Count and check cookies.
 function runTest() {
   // set a cookie from a domain of "localhost"
   document.cookie = "oh=hai";
 
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-
-  var cs = Components.classes["@mozilla.org/cookiemanager;1"]
-                     .getService(Components.interfaces.nsICookieManager);
+  var cs = SpecialPowers.Cc["@mozilla.org/cookiemanager;1"]
+                        .getService(SpecialPowers.Ci.nsICookieManager);
   var count = 0;
   for(var list = cs.enumerator; list.hasMoreElements(); list.getNext())
     ++count;
   is(count, gExpectedCookies, "total number of cookies");
   cs.removeAll();
 
   finishTest();
 }
--- a/extensions/cookie/test/file_testloadflags.js
+++ b/extensions/cookie/test/file_testloadflags.js
@@ -10,30 +10,28 @@ var gLoads = 0;
 
 // setupTest() is run from 'onload='.
 function setupTest(uri, domain, cookies, loads, headers) {
   ok(true, "setupTest uri: " + uri + " domain: " + domain + " cookies: " + cookies +
            " loads: " + loads + " headers: " + headers);
 
   SimpleTest.waitForExplicitFinish();
 
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
+  SpecialPowers.Cc["@mozilla.org/preferences-service;1"]
+               .getService(SpecialPowers.Ci.nsIPrefBranch)
+               .setIntPref("network.cookie.cookieBehavior", 1);
 
-  Components.classes["@mozilla.org/preferences-service;1"]
-            .getService(Components.interfaces.nsIPrefBranch)
-            .setIntPref("network.cookie.cookieBehavior", 1);
-
-  var cs = Components.classes["@mozilla.org/cookiemanager;1"]
-                     .getService(Components.interfaces.nsICookieManager2);
+  var cs = SpecialPowers.Cc["@mozilla.org/cookiemanager;1"]
+                        .getService(SpecialPowers.Ci.nsICookieManager2);
 
   ok(true, "we are going to remove these cookies");
   var count = 0;
   var list = cs.enumerator;
   while (list.hasMoreElements()) {
-    var cookie = list.getNext().QueryInterface(Components.interfaces.nsICookie);
+    var cookie = list.getNext().QueryInterface(SpecialPowers.Ci.nsICookie);
     ok(true, "cookie: " + cookie);
     ok(true, "cookie host " + cookie.host + " path " + cookie.path + " name " + cookie.name +
        " value " + cookie.value + " isSecure " + cookie.isSecure + " expires " + cookie.expires);
     ++count;
   }
   ok(true, count + " cookies");
 
   cs.removeAll();
@@ -52,48 +50,44 @@ function setupTest(uri, domain, cookies,
   // cookies from their respective domains.
   gPopup = window.open(uri, 'hai', 'width=100,height=100');
 }
 
 function finishTest()
 {
   gObs.remove();
 
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-  Components.classes["@mozilla.org/preferences-service;1"]
-            .getService(Components.interfaces.nsIPrefBranch)
-            .clearUserPref("network.cookie.cookieBehavior");
+  SpecialPowers.Cc["@mozilla.org/preferences-service;1"]
+               .getService(SpecialPowers.Ci.nsIPrefBranch)
+               .clearUserPref("network.cookie.cookieBehavior");
 
   SimpleTest.finish();
 }
 
 // Count headers.
 function obs () {
   netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
 
   ok(true, "adding observer");
 
   this.window = window;
-  this.os = Components.classes["@mozilla.org/observer-service;1"]
-                      .getService(Components.interfaces.nsIObserverService);
+  this.os = SpecialPowers.Cc["@mozilla.org/observer-service;1"]
+                         .getService(SpecialPowers.Ci.nsIObserverService);
   this.os.addObserver(this, "http-on-modify-request", false);
 }
 
 obs.prototype = {
   observe: function obs_observe (theSubject, theTopic, theData)
   {
-    this.window.netscape.security
-        .PrivilegeManager.enablePrivilege("UniversalXPConnect");
-
     ok(true, "theSubject " + theSubject);
     ok(true, "theTopic " + theTopic);
     ok(true, "theData " + theData);
 
     var channel = theSubject.QueryInterface(
-                    this.window.Components.interfaces.nsIHttpChannel);
+                    this.window.SpecialPowers.Ci.nsIHttpChannel);
     ok(true, "channel " + channel);
     try {
       ok(true, "channel.URI " + channel.URI);
       ok(true, "channel.URI.spec " + channel.URI.spec);
       channel.visitRequestHeaders({
         visitHeader: function(aHeader, aValue) {
           ok(true, aHeader + ": " + aValue);
         }});
@@ -158,24 +152,22 @@ function messageReceiver(evt)
 // runTest() is run by messageReceiver().
 // Check headers, and count and check cookies.
 function runTest() {
   // set a cookie from a domain of "localhost"
   document.cookie = "o=noes";
 
   is(gHeaders, gExpectedHeaders, "number of observed request headers");
 
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-
-  var cs = Components.classes["@mozilla.org/cookiemanager;1"]
-                     .getService(Components.interfaces.nsICookieManager);
+  var cs = SpecialPowers.Cc["@mozilla.org/cookiemanager;1"]
+                        .getService(SpecialPowers.Ci.nsICookieManager);
   var count = 0;
   var list = cs.enumerator;
   while (list.hasMoreElements()) {
-    var cookie = list.getNext().QueryInterface(Components.interfaces.nsICookie);
+    var cookie = list.getNext().QueryInterface(SpecialPowers.Ci.nsICookie);
     ok(true, "cookie: " + cookie);
     ok(true, "cookie host " + cookie.host + " path " + cookie.path + " name " + cookie.name +
        " value " + cookie.value + " isSecure " + cookie.isSecure + " expires " + cookie.expires);
     ++count;
   }
   is(count, gExpectedCookies, "total number of cookies");
   cs.removeAll();
 
--- a/gfx/tests/mochitest/test_bug509244.html
+++ b/gfx/tests/mochitest/test_bug509244.html
@@ -26,19 +26,18 @@ var text = document.getElementById("disp
 // layout text, caching monospace font
 text.style.fontFamily = "monospace";
 flush();
 // relayout text so that monospace font is no longer used (but cached)
 text.style.fontFamily = "sans-serif";
 flush();
 
 // flush cache
-netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-var os = Components.classes["@mozilla.org/observer-service;1"]
-         .getService(Components.interfaces.nsIObserverService);
+var os = SpecialPowers.Cc["@mozilla.org/observer-service;1"]
+         .getService(SpecialPowers.Ci.nsIObserverService);
 os.notifyObservers(null, "memory-pressure", "heap-minimize");
 
 // reuse font that was flushed from cache
 text.style.fontFamily = "monospace";
 flush(); 
 
 ok(true, "not crashed");
 
--- a/gfx/tests/mochitest/test_bug513439.html
+++ b/gfx/tests/mochitest/test_bug513439.html
@@ -14,25 +14,24 @@ https://bugzilla.mozilla.org/show_bug.cg
 <div id="content" style="display: none">
   
 </div>
 <pre id="test">
 <script type="application/javascript">
 
 /** Test for Bug 513439 **/
 
-netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-var prefService = Components.classes["@mozilla.org/preferences-service;1"]
-                            .getService(Components.interfaces.nsIPrefService);
+var prefService = SpecialPowers.Cc["@mozilla.org/preferences-service;1"]
+                               .getService(SpecialPowers.Ci.nsIPrefService);
 var layoutCSSBranch = prefService.getBranch("layout.css.");
 var oldVal = layoutCSSBranch.getCharPref("devPixelsPerPx");
 
 try {
-  var domWindowUtils = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
-                             .getInterface(Components.interfaces.nsIDOMWindowUtils);
+  var domWindowUtils = window.QueryInterface(SpecialPowers.Ci.nsIInterfaceRequestor)
+                             .getInterface(SpecialPowers.Ci.nsIDOMWindowUtils);
   var devPxPerCSSPx = domWindowUtils.screenPixelsPerCSSPixel;
 
   layoutCSSBranch.setCharPref("devPixelsPerPx", "2");
   is(domWindowUtils.screenPixelsPerCSSPixel, 2, "devPixelsPerPx wasn't set correctly");
 
   layoutCSSBranch.setCharPref("devPixelsPerPx", "1.5");
   is(domWindowUtils.screenPixelsPerCSSPixel, 1.5, "devPixelsPerPx wasn't set correctly");
 
--- a/image/test/mochitest/imgutils.js
+++ b/image/test/mochitest/imgutils.js
@@ -27,19 +27,16 @@ function isImageLoaded(id)
   return (getImageStatus(id) &
           SpecialPowers.Ci.imgIRequest.STATUS_LOAD_COMPLETE)
          ? true : false;
 }
 
 // Helper function to get the status flags of an image
 function getImageStatus(id)
 {
-  // Escalate
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-
   // Get the image
   var img = SpecialPowers.wrap(document.getElementById(id));
 
   // QI the image to nsImageLoadingContent
   img.QueryInterface(SpecialPowers.Ci.nsIImageLoadingContent);
 
   // Get the request
   var request = img.getRequest(SpecialPowers.Ci
@@ -49,18 +46,16 @@ function getImageStatus(id)
   // Return the status
   return request.imageStatus;
 }
 
 // Forces a synchronous decode of an image by drawing it to a canvas. Only
 // really meaningful if the image is fully loaded first
 function forceDecode(id)
 {
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-
   // Get the image
   var img = document.getElementById(id);
 
   // Make a new canvas
   var canvas = document.createElement("canvas");
 
   // Draw the image to the canvas. This forces a synchronous decode
   var ctx = canvas.getContext("2d");
@@ -76,19 +71,18 @@ function forceDecode(id)
 // Null indicates no pref set
 
 const DISCARD_ENABLED_PREF = {name: "discardable", branch: "image.mem.", type: "bool"};
 const DECODEONDRAW_ENABLED_PREF = {name: "decodeondraw", branch: "image.mem.", type: "bool"};
 const DISCARD_TIMEOUT_PREF = {name: "min_discard_timeout_ms", branch: "image.mem.", type: "int"};
 
 function setImagePref(pref, val)
 {
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-  var prefService = Components.classes["@mozilla.org/preferences-service;1"]
-                              .getService(Components.interfaces.nsIPrefService);
+  var prefService = SpecialPowers.Cc["@mozilla.org/preferences-service;1"]
+                                 .getService(SpecialPowers.Ci.nsIPrefService);
   var branch = prefService.getBranch(pref.branch);
   if (val != null) {
     switch(pref.type) {
       case "bool":
         branch.setBoolPref(pref.name, val);
         break;
       case "int":
         branch.setIntPref(pref.name, val);
@@ -98,19 +92,18 @@ function setImagePref(pref, val)
     }
   }
   else if (branch.prefHasUserValue(pref.name))
     branch.clearUserPref(pref.name);
 }
 
 function getImagePref(pref)
 {
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-  var prefService = Components.classes["@mozilla.org/preferences-service;1"]
-                              .getService(Components.interfaces.nsIPrefService);
+  var prefService = SpecialPowers.Cc["@mozilla.org/preferences-service;1"]
+                                 .getService(SpecialPowers.Ci.nsIPrefService);
   var branch = prefService.getBranch(pref.branch);
   if (branch.prefHasUserValue(pref.name)) {
     switch (pref.type) {
       case "bool":
         return branch.getBoolPref(pref.name);
       case "int":
         return branch.getIntPref(pref.name);
       default:
--- a/image/test/mochitest/test_bug512435.html
+++ b/image/test/mochitest/test_bug512435.html
@@ -14,19 +14,18 @@ https://bugzilla.mozilla.org/show_bug.cg
 <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=512435">Mozilla Bug 512435</a>
 <img id="img_a">
 <img id="img_b">
 </div>
 <pre id="test">
 <script type="application/javascript">
 
 // Boilerplate
-netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-const Ci = Components.interfaces;
-const Cc = Components.classes;
+const Ci = SpecialPowers.Ci;
+const Cc = SpecialPowers.Cc;
 SimpleTest.waitForExplicitFinish();
 
 // We're relying on very particular behavior for certain images - clear the
 // image cache, _then_ set src
 clearImageCache();
 document.getElementById("img_a").src = "damon.jpg";
 document.getElementById("img_b").src = "shaver.png";
 
--- a/image/test/mochitest/test_bug601470.html
+++ b/image/test/mochitest/test_bug601470.html
@@ -17,25 +17,24 @@ https://bugzilla.mozilla.org/show_bug.cg
 </div>
 <pre id="test">
 <script type="application/javascript">
 /** Test for Bug 601470 **/
 
 SimpleTest.waitForExplicitFinish();
 
 window.onload = function() {
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-  var mgr = Components.classes["@mozilla.org/memory-reporter-manager;1"]
-    .getService(Components.interfaces.nsIMemoryReporterManager);
+  var mgr = SpecialPowers.Cc["@mozilla.org/memory-reporter-manager;1"]
+    .getService(SpecialPowers.Ci.nsIMemoryReporterManager);
 
   var e = mgr.enumerateReporters();
   var memoryCounter = 0;
   while (e.hasMoreElements()) {
     var mr =
-      e.getNext().QueryInterface(Components.interfaces.nsIMemoryReporter);
+      e.getNext().QueryInterface(SpecialPowers.Ci.nsIMemoryReporter);
     memoryCounter += mr.amount;
   }
   ok(memoryCounter > 0, "we should be using a nonzero amount of memory");
   ok(true, "yay, didn't crash!");
 
   SimpleTest.finish();
 }
 
--- a/intl/uconv/tests/test_long_doc.html
+++ b/intl/uconv/tests/test_long_doc.html
@@ -18,19 +18,18 @@ https://bugzilla.mozilla.org/show_bug.cg
 /** Test for Bug 718573 **/
 
 /* Text longer than 2K bytes to ensure that it crosses a block boundary
    while decoding */
 const inString = "Many years ago, I contracted an intimacy with a Mr. William Legrand. He was of an ancient Huguenot family, and had once been wealthy; but a series of misfortunes had reduced him to want. To avoid the mortification consequent upon his disasters, he left New Orleans, the city of his forefathers, and took up his residence at Sullivan's Island, near Charleston, South Carolina. This island is a very singular one. It consists of little else than the sea sand, and is about three miles long. Its breadth at no point exceeds a quarter of a mile. It is separated from the mainland by a scarcely perceptible creek, oozing its way through a wilderness of reeds and slime, a favorite resort of the marsh-hen. The vegetation, as might be supposed, is scant, or at least dwarfish. No trees of any magnitude are to be seen. Near the western extremity, where Fort Moultrie stands, and where are some miserable frame buildings, tenanted, during summer, by the fugitives from Charleston dust and fever, may be found, indeed, the bristly palmetto; but the whole island, with the exception of this western point, and a line of hard, white beach on the sea-coast, is covered with a dense undergrowth of the sweet myrtle so much prized by the horticulturists of England. The shrub here often attains the height of fifteen or twenty feet, and forms an almost impenetrable coppice, burthening the air with its fragrance. In the inmost recesses of this coppice, not far from the eastern or more remote end of the island, Legrand had built himself a small hut, which he occupied when I first, by mere accident, made his acquaintance. This soon ripened into friendship -- for there was much in the recluse to excite interest and esteem. I found him well educated, with unusual powers of mind, but infected with misanthropy, and subject to perverse moods of alternate enthusiasm and melancholy. He had with him many books, but rarely employed them. His chief amusements were gunning and fishing, or sauntering along the beach and through the myrtles, in quest of shells or entomological specimens -- his collection of the latter might have been envied by a Swammerdamm. In these excursions he was usually accompanied by an old negro, called Jupiter, who had been manumitted before the reverses of the family, but who could be induced, neither by threats nor by promises, to abandon what he considered his right of attendance upon the footsteps of his young 'Massa Will.' It is not improbable that the relatives of Legrand, conceiving him to be somewhat unsettled in intellect, had contrived to instil this obstinacy into Jupiter, with a view to the supervision and guardianship of the wanderer. ";
 
 const testContent = "<pre id='testPara'>" + inString;
 
-netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-const Ci = Components.interfaces;
-const Cc = Components.classes;
+const Ci = SpecialPowers.Ci;
+const Cc = SpecialPowers.Cc;
 var ccManager = Cc["@mozilla.org/charset-converter-manager;1"].getService(Ci.nsICharsetConverterManager);
 
 var decoderList = ccManager.getDecoderList();
 SimpleTest.waitForExplicitFinish();
 while (decoderList.hasMore()) {
     var decoder =  decoderList.getNext();
 
     // Skip UTF-16 variants. (Other non-ASCII compatible encodings will be
--- a/js/jsd/test/jsd-test.js
+++ b/js/jsd/test/jsd-test.js
@@ -1,16 +1,15 @@
-netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-const Cc = Components.classes;
-const Ci = Components.interfaces;
+const Cc = SpecialPowers.Cc;
+const Ci = SpecialPowers.Ci;
 const RETURN_CONTINUE = Ci.jsdIExecutionHook.RETURN_CONTINUE;
 const DebuggerService = Cc["@mozilla.org/js/jsd/debugger-service;1"];
 
-var jsd = Components.classes['@mozilla.org/js/jsd/debugger-service;1']
-                    .getService(Ci.jsdIDebuggerService);
+var jsd = Cc['@mozilla.org/js/jsd/debugger-service;1']
+          .getService(Ci.jsdIDebuggerService);
 var jsdOnAtStart = false;
 
 function setupJSD(test) {
   netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
   jsdOnAtStart = jsd.isOn;
   if (jsdOnAtStart) {
       runTest();
   } else {
@@ -102,17 +101,16 @@ function breakpointObserver(lines, inter
             return callback(frame, type, breakpoints_hit);
         } else {
             return RETURN_CONTINUE;
         }
     } };
 }
 
 function dumpStack(frame, msg) {
-    netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
     dump(msg + ":\n");
     while(frame) {
         var callee = frame.callee;
         if (callee !== null)
           callee = callee.jsClassName;
         dump("  " + frame.script.fileName + ":" + frame.line + " func=" + frame.script.functionName + " ffunc=" + frame.functionName + " callee=" + callee + " pc=" + frame.pc + "\n");
         frame = frame.callingFrame;
     }
--- a/js/jsd/test/test_bug507448.html
+++ b/js/jsd/test/test_bug507448.html
@@ -63,29 +63,26 @@ function loadScript(url) {
 /** Test for Bug 507448 **/
 function assertArraysEqual(arr1, arr2) {
   is(arr1.length, arr2.length, "Lengths not equal");
   for (var i = 0 ; i < arr1.length; ++i) {
     is(arr1[i], arr2[i], "Element " + i + " not equal");
   }
 }
 
-netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-var jsdIDebuggerService = Components.interfaces.jsdIDebuggerService;
-var jsd = Components.classes['@mozilla.org/js/jsd/debugger-service;1']
-                    .getService(jsdIDebuggerService);
+var jsdIDebuggerService = SpecialPowers.Ci.jsdIDebuggerService;
+var jsd = SpecialPowers.Cc['@mozilla.org/js/jsd/debugger-service;1']
+                       .getService(jsdIDebuggerService);
 var jsdOnAtStart = false;
 
 function setupJSD() {
   // This is somewhat unfortunate: jsd only deals with scripts that have a
   // nonzero line number, so we can't just createElement a script here.
   // So break the test up into three <script>s, of which the middle one has our test functions.
 
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-
   jsdOnAtStart = jsd.isOn;
   if (jsdOnAtStart) {
     testJSD();
   } else {
     jsd.asyncOn(
       {
         onDebuggerActivated: function() {
             testJSD();
@@ -95,18 +92,16 @@ function setupJSD() {
   }
 }
 
 addLoadEvent(setupJSD);
 
 </script>
 <script>
 function testJSD() {
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-
   ok(jsd.isOn, "JSD needs to be running for this test.");
 
   var deferred = loadScript("bug507448.js");
 }
 </script>
 </pre>
 </body>
 </html>
--- a/js/jsd/test/test_bug617870-callhooks.html
+++ b/js/jsd/test/test_bug617870-callhooks.html
@@ -6,30 +6,26 @@
   <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
   <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
   <script type="application/javascript" src="jsd-test.js"></script>
   <script type="application/javascript">
 var BUG = 617870;
 var TEST_SCRIPT = "test-bug617870-callhooks.js";
 document.getElementsByTagName("title")[0].innerHTML = "JSD Test for Bug " + BUG;
 
-netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-
 SimpleTest.waitForExplicitFinish();
 
 var hits = { gn: [], ge: [], fn: [], fe: [] };
 var numGlobalNonevals = 0;
 var numFunctionNonevals = 0;
 var numGlobalEvals = 0;
 var numFunctionEvals = 0;
 function runTest() {
-    netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
     jsd.topLevelHook = {
         onCall: function(frame,type) {
-            netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
             if (frame.script.fileName.indexOf(TEST_SCRIPT) != -1) {
                 var desc = frame.script.fileName + ":" + frame.line + " (" + frame.functionName + ")";
                 if (type == Ci.jsdICallHook.TYPE_TOPLEVEL_START) {
                     if (frame.callingFrame === null) {
                         numGlobalNonevals++;
                         hits.gn.push(desc);
                     } else if (frame.callee === null) {
                         numGlobalEvals++;
@@ -40,17 +36,16 @@ function runTest() {
                     }
                 }
                 dumpStack(frame, "TOPLEVEL(" + type + ")");
            }
         }
     };
     jsd.functionHook = {
         onCall: function(frame,type) {
-            netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
             if (frame.script.fileName.indexOf(TEST_SCRIPT) != -1) {
                 if (type == Ci.jsdICallHook.TYPE_FUNCTION_CALL) {
                     var desc = frame.script.fileName + ":" + frame.line + " (" + frame.functionName + ")";
                     numFunctionNonevals++;
                     hits.fn.push(desc);
                 }
                 dumpStack(frame, "FUNCTION(" + type + ")");
             }
--- a/js/jsd/test/test_bug638178-execlines.html
+++ b/js/jsd/test/test_bug638178-execlines.html
@@ -6,22 +6,19 @@
   <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
   <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
   <script type="application/javascript" src="jsd-test.js"></script>
   <script type="application/javascript">
 var BUG = 638178;
 var TEST_SCRIPT = "test-bug638178-execlines.js";
 document.getElementsByTagName("title")[0].innerHTML = "JSD Test for Bug " + BUG;
 
-netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-
 SimpleTest.waitForExplicitFinish();
 
 function runTest() {
-    netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
     console.log("start of runTest, loading script");
     loadScript(TEST_SCRIPT, document.getElementById("test"));
     console.log("end of runTest");
 }
 
 function setupTest() {
     var buglink = document.getElementById("buglink");
     buglink.href = "https://bugzilla.mozilla.org/show_bug.cgi?id=" + BUG;
--- a/layout/base/tests/test_bug394057.html
+++ b/layout/base/tests/test_bug394057.html
@@ -20,22 +20,21 @@ https://bugzilla.mozilla.org/show_bug.cg
   
 </div>
 <pre id="test">
 <script class="testbody" type="text/javascript">
 
 /** Test for Bug 394057 **/
 
 SimpleTest.waitForExplicitFinish();
-netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
 
 var tableElement = document.getElementById("display");
 
-var CC = Components.classes;
-var CI = Components.interfaces;
+var CC = SpecialPowers.Cc;
+var CI = SpecialPowers.Ci;
 
 var fe =
   CC["@mozilla.org/gfx/fontenumerator;1"].createInstance(CI.nsIFontEnumerator);
 var serifFonts = fe.EnumerateFonts("x-western", "serif", {});
 var monospaceFonts = fe.EnumerateFonts("x-western", "monospace", {});
 
 function table_width_for_font(font) {
   tableElement.style.fontFamily = '"' + font + '"';
@@ -66,25 +65,23 @@ isnot(serifWidth, monospaceWidth,
 
 var prefs =
   CC["@mozilla.org/preferences-service;1"].getService(CI.nsIPrefBranch);
 prefs.setCharPref('font.name.serif.x-western', serifFonts[serifIdx]);
 
 var serifWidthFromPref;
 setTimeout(setTimeout, 0, step2, 0);
 function step2() {
-    netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
     serifWidthFromPref = tableElement.offsetWidth;
     prefs.setCharPref('font.name.serif.x-western',
                         monospaceFonts[monospaceIdx]);
     setTimeout(setTimeout, 0, step3, 0);
 }
 var monospaceWidthFromPref;
 function step3() {
-    netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
     monospaceWidthFromPref = tableElement.offsetWidth;
     prefs.clearUserPref('font.name.serif.x-western');
 
     is(serifWidthFromPref, serifWidth,
        "changing font pref should change width of table (serif)");
     is(monospaceWidthFromPref, monospaceWidth,
        "changing font pref should change width of table (monospace)");
     SimpleTest.finish();
--- a/layout/base/tests/test_bug399284.html
+++ b/layout/base/tests/test_bug399284.html
@@ -13,19 +13,18 @@ https://bugzilla.mozilla.org/show_bug.cg
 <p id="display"></p>
 <div id="content" style="display: none">
 </div>
 <pre id="test">
 <script class="testbody" type="text/javascript">
 /** Test for Bug 399284 **/
 const testContent = "<p id='testPara'>The quick brown fox jumps over the lazy dog";
 
-netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-const Ci = Components.interfaces;
-const Cc = Components.classes;
+const Ci = SpecialPowers.Ci;
+const Cc = SpecialPowers.Cc;
 var ccManager = Cc["@mozilla.org/charset-converter-manager;1"].getService(Ci.nsICharsetConverterManager);
 
 var decoderList = ccManager.getDecoderList();
 SimpleTest.waitForExplicitFinish();
 while (decoderList.hasMore()) {
     var decoder =  decoderList.getNext();
 
     // encode the content for non-ASCII compatible encodings
--- a/layout/base/tests/test_bug416896.html
+++ b/layout/base/tests/test_bug416896.html
@@ -23,29 +23,28 @@ https://bugzilla.mozilla.org/show_bug.cg
 
 /** Test for Bug 416896 **/
  var inlineSheet = $("i").sheet;
  isnot(inlineSheet, null, "Should have sheet here");
 
  var linkedSheet = $("l").sheet;
  isnot(linkedSheet, null, "Should have sheet here");
 
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
- var domUtils = Components.classes["@mozilla.org/inspector/dom-utils;1"]
-                          .getService(Components.interfaces.inIDOMUtils);
- const nsIDOMCSSStyleRule = Components.interfaces["nsIDOMCSSStyleRule"];
+ var domUtils = SpecialPowers.Cc["@mozilla.org/inspector/dom-utils;1"]
+                             .getService(SpecialPowers.Ci.inIDOMUtils);
+ const nsIDOMCSSStyleRule = SpecialPowers.Ci["nsIDOMCSSStyleRule"];
  var inspectedRules = domUtils.getCSSStyleRules(document.links[0]);
 
  var seenInline = false;
  var seenLinked = false;
  
  for (var i = 0; i < inspectedRules.Count(); ++i)
  {
    var rule =
-     inspectedRules.GetElementAt(i).QueryInterface(nsIDOMCSSStyleRule);
+     SpecialPowers.unwrap(inspectedRules.GetElementAt(i).QueryInterface(nsIDOMCSSStyleRule));
    var sheet = rule.parentStyleSheet;
    if (sheet == inlineSheet) {
      is(sheet.href, null, "It's an inline sheet");
      is(seenInline, false, "Only one inline rule matches");
      seenInline = true;
    } else {
      isnot(sheet.href, null, "Shouldn't have null href here");
      if (sheet == linkedSheet) {
--- a/layout/base/tests/test_bug548545.xhtml
+++ b/layout/base/tests/test_bug548545.xhtml
@@ -16,22 +16,20 @@ https://bugzilla.mozilla.org/show_bug.cg
 </div>
 <pre id="test">
 <script class="testbody" type="text/javascript">
 <![CDATA[
 /** Test for Bug 548545 **/
 
 SimpleTest.waitForExplicitFinish();
 
-netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
-
 var content = document.getElementById("content");
 
-var CC = Components.classes;
-var CI = Components.interfaces;
+var CC = SpecialPowers.Cc;
+var CI = SpecialPowers.Ci;
 
 var fe =
   CC["@mozilla.org/gfx/fontenumerator;1"].createInstance(CI.nsIFontEnumerator);
 var allFonts = fe.EnumerateFonts(null, null, {});
 
 var idx = 0;
 var list = "";
 for (idx in allFonts) {
--- a/layout/base/tests/test_bug603550.html
+++ b/layout/base/tests/test_bug603550.html
@@ -48,19 +48,18 @@ function sendMouseUp(el) {
 }
 
 function fireEvent(target, event) {
   var utils = SpecialPowers.getDOMWindowUtils(window);
   utils.dispatchDOMEventViaPresShell(target, event, true);
 }
 
 function fireDrop(element) {
-  netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
-  var ds = Components.classes["@mozilla.org/widget/dragservice;1"].
-    getService(Components.interfaces.nsIDragService);
+  var ds = SpecialPowers.Cc["@mozilla.org/widget/dragservice;1"].
+    getService(SpecialPowers.Ci.nsIDragService);
 
   ds.startDragSession();
 
   var event = document.createEvent("DragEvents");
   event.initDragEvent("dragover", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null, null);
   fireEvent(element, event);
 
   event = document.createEvent("DragEvents");
--- a/layout/generic/test/test_bug263683.html
+++ b/layout/generic/test/test_bug263683.html
@@ -36,22 +36,19 @@ https://bugzilla.mozilla.org/show_bug.cg
       var userSetBG = false;
       var userValueBG = null;
       var prefNameBG = "ui.textHighlightBackground";
       var userSetFG = false;
       var userValueFG = null;
       var prefNameFG = "ui.textHighlightForeground";
 
       function onLoad() {
-        // Request security privileges
-        netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-
         // Get pref branch.
-        var prefs = Components.classes["@mozilla.org/preferences-service;1"]
-                              .getService(Components.interfaces.nsIPrefBranch);
+        var prefs = SpecialPowers.Cc["@mozilla.org/preferences-service;1"]
+                              .getService(SpecialPowers.Ci.nsIPrefBranch);
 
         // Check to see if this pref has a user-set value. If so, store it
         userSetFG = prefs.prefHasUserValue(prefNameFG);
         userSetBG = prefs.prefHasUserValue(prefNameBG);
 
         if (userSetFG)
           userValueFG = prefs.getCharPref(prefNameFG);
         if (userSetBG)
@@ -64,25 +61,26 @@ https://bugzilla.mozilla.org/show_bug.cg
         var textToSelect = document.getElementById("selecttext");
 
         // Take a snapshot now. This will be used to check that removing the
         // ranges removes the highlighting correctly
         var noHighlight = snapshotWindow(window);
 
         // Get docshell
         var docShell =
-          window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
-                .getInterface(Components.interfaces.nsIWebNavigation)
-                .QueryInterface(Components.interfaces.nsIDocShell);
+          SpecialPowers.wrap(window)
+                .QueryInterface(SpecialPowers.Ci.nsIInterfaceRequestor)
+                .getInterface(SpecialPowers.Ci.nsIWebNavigation)
+                .QueryInterface(SpecialPowers.Ci.nsIDocShell);
 
         // Get selection controller from docshell
         var controller =
-          docShell.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
-                  .getInterface(Components.interfaces.nsISelectionDisplay)
-                  .QueryInterface(Components.interfaces.nsISelectionController);
+          docShell.QueryInterface(SpecialPowers.Ci.nsIInterfaceRequestor)
+                  .getInterface(SpecialPowers.Ci.nsISelectionDisplay)
+                  .QueryInterface(SpecialPowers.Ci.nsISelectionController);
 
         // Get selection
         var findSelection = controller.getSelection(controller.SELECTION_FIND);
 
         // Lastly add range
         var range = document.createRange();
         range.selectNodeContents(textToSelect);
         findSelection.addRange(range);
@@ -108,21 +106,18 @@ https://bugzilla.mozilla.org/show_bug.cg
         res = compareSnapshots(removedHighlight, noHighlight, true);
         ok(res[0], "Removing ranges from FIND_SELECTION works correctly");
 
         SimpleTest.finish();
       }
 
       function onUnload() {
         // Restore any user values for ui.textHighlight* preferences
-        netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-
-        // Get the pref branch
-        var prefs = Components.classes["@mozilla.org/preferences-service;1"]
-                              .getService(Components.interfaces.nsIPrefBranch);
+        var prefs = SpecialPowers.Cc["@mozilla.org/preferences-service;1"]
+                              .getService(SpecialPowers.Ci.nsIPrefBranch);
  
         if (prefs.prefHasUserValue(prefNameFG))
           prefs.clearUserPref(prefNameFG);
         if (prefs.prefHasUserValue(prefNameBG))
           prefs.clearUserPref(prefNameBG);
 
         if (userSetFG)
           prefs.setCharPref(prefNameFG, userValueFG);
--- a/security/manager/ssl/tests/mochitest/bugs/test_bug483440.html
+++ b/security/manager/ssl/tests/mochitest/bugs/test_bug483440.html
@@ -3,26 +3,24 @@
   <title>Test bug 483437 and bug 480509</title>
   <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>        
   <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
 </head>
 <body>
 
 <script class="testbody" type="text/javascript">
 
-netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-
-var certdb = Components.classes["@mozilla.org/security/x509certdb;1"]
-  .getService(Components.interfaces.nsIX509CertDB);
+var certdb = SpecialPowers.Cc["@mozilla.org/security/x509certdb;1"]
+  .getService(SpecialPowers.Ci.nsIX509CertDB);
 
 function test(certNick, expected)
 {
   var cert1 = certdb.findCertByNickname(null, certNick);
-  var certDumpTree1 = Components.classes["@mozilla.org/security/nsASN1Tree;1"]
-                     .createInstance(Components.interfaces.nsIASN1Tree);
+  var certDumpTree1 = SpecialPowers.Cc["@mozilla.org/security/nsASN1Tree;1"]
+                     .createInstance(SpecialPowers.Ci.nsIASN1Tree);
   certDumpTree1.loadASN1Structure(cert1.ASN1Structure);
   var value1 = certDumpTree1.getDisplayData(9);
   
   is(value1, expected, "Incorrect OID recognized");
 }
 
 test("bug483440-attack2b", 
      "Object Identifier (2 5 4 Unknown) = www.bank.com\n"+
--- a/security/manager/ssl/tests/mochitest/mixedcontent/test_bug383369.html
+++ b/security/manager/ssl/tests/mochitest/mixedcontent/test_bug383369.html
@@ -10,118 +10,114 @@
 
   // We want to start this test from an insecure context
   loadAsInsecure = true;
   // We don't want to go through the navigation back/forward test
   bypassNavigationTest = true;
 
   function runTest()
   {
-    netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-  
     // Force download to be w/o user assistance for our testing mime type
-    const mimeSvc = Components.classes["@mozilla.org/mime;1"]
-      .getService(Components.interfaces.nsIMIMEService);
+    const mimeSvc = SpecialPowers.Cc["@mozilla.org/mime;1"]
+      .getService(SpecialPowers.Ci.nsIMIMEService);
     var handlerInfo = mimeSvc.getFromTypeAndExtension("application/x-auto-download", "auto");
-    handlerInfo.preferredAction = Components.interfaces.nsIHandlerInfo.saveToDisk;
+    handlerInfo.preferredAction = SpecialPowers.Ci.nsIHandlerInfo.saveToDisk;
     handlerInfo.alwaysAskBeforeHandling = false;
     handlerInfo.preferredApplicationHandler = null;
     
-    const handlerSvc = Components.classes["@mozilla.org/uriloader/handler-service;1"]
-      .getService(Components.interfaces.nsIHandlerService);
+    const handlerSvc = SpecialPowers.Cc["@mozilla.org/uriloader/handler-service;1"]
+      .getService(SpecialPowers.Ci.nsIHandlerService);
     handlerSvc.store(handlerInfo);
     
-    var dirProvider = Components.classes["@mozilla.org/file/directory_service;1"]
-      .getService(Components.interfaces.nsIProperties);
-    var profileDir = dirProvider.get("ProfDS", Components.interfaces.nsIFile);
+    var dirProvider = SpecialPowers.Cc["@mozilla.org/file/directory_service;1"]
+      .getService(SpecialPowers.Ci.nsIProperties);
+    var profileDir = dirProvider.get("ProfDS", SpecialPowers.Ci.nsIFile);
     profileDir.append("downloads");
     
-    var prefs = Components.classes["@mozilla.org/preferences-service;1"]
-      .getService(Components.interfaces.nsIPrefService);
+    var prefs = SpecialPowers.Cc["@mozilla.org/preferences-service;1"]
+      .getService(SpecialPowers.Ci.nsIPrefService);
     prefs = prefs.getBranch("browser.download.");
         
     prefs.setCharPref("dir", profileDir.path);
     prefs.setBoolPref("useDownloadDir", true);
     prefs.setIntPref("folderList", 2);
     prefs.setBoolPref("manager.closeWhenDone", true);
     prefs.setBoolPref("manager.showWhenStarting", false);
   
     var theWindow = window;
 
     var useJSTransfer = false;
     try {
       useJSTransfer = prefs.getBoolPref("useJSTransfer");
     } catch (ex) { }
 
     if (useJSTransfer) {
-      Components.utils.import("resource://gre/modules/Downloads.jsm");
+      var Downloads = SpecialPowers.Cu.import("resource://gre/modules/Downloads.jsm").Downloads;
       Downloads.getPublicDownloadList().then(list => {
+        list = SpecialPowers.wrap(list);
         list.addView({
           onDownloadAdded: function (aDownload) {
             list.removeView(this);
-            aDownload.whenSucceeded().then(() => {
+            SpecialPowers.wrap(aDownload).whenSucceeded().then(() => {
               list.removeFinished();
               theWindow.location = "bug383369step2.html";
             });
           },
         });
         window.location = "download.auto";
-      }).then(null, Components.utils.reportError);
+      }).then(null, SpecialPowers.Cu.reportError);
 
       return;
     }
 
-    var downloadManager = Components.classes["@mozilla.org/download-manager;1"]
-      .getService(Components.interfaces.nsIDownloadManager);
+    var downloadManager = SpecialPowers.Cc["@mozilla.org/download-manager;1"]
+      .getService(SpecialPowers.Ci.nsIDownloadManager);
     var observer = {
       observe: function(subject, topic, data) {
         switch (topic) {
         case "dl-done":
         case "dl-failed":
         case "dl-blocked":
         case "dl-dirty":
-          netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
           downloadManager.cleanUp();
           theWindow.location = "bug383369step2.html";
           observerService.removeObserver(this, "dl-done");
           observerService.removeObserver(this, "dl-failed");
           observerService.removeObserver(this, "dl-blocked");
           observerService.removeObserver(this, "dl-dirty");
           break;
         }
       }
     };
-    var observerService = Components.classes["@mozilla.org/observer-service;1"]
-      .getService(Components.interfaces.nsIObserverService);
+    var observerService = SpecialPowers.Cc["@mozilla.org/observer-service;1"]
+      .getService(SpecialPowers.Ci.nsIObserverService);
     observerService.addObserver(observer, "dl-done", false);
     observerService.addObserver(observer, "dl-failed", false);
     observerService.addObserver(observer, "dl-blocked", false);
     observerService.addObserver(observer, "dl-dirty", false);
 
     window.location = "download.auto";
   }
 
   function afterNavigationTest()
   {
   }
   
   testCleanUp = function cleanup()
   {
-    netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-
-    const mimeSvc = Components.classes["@mozilla.org/mime;1"]
-      .getService(Components.interfaces.nsIMIMEService);
+    const mimeSvc = SpecialPowers.Cc["@mozilla.org/mime;1"]
+      .getService(SpecialPowers.Ci.nsIMIMEService);
     var handlerInfo = mimeSvc.getFromTypeAndExtension("application/x-auto-download", "auto");
     
-    const handlerSvc = Components.classes["@mozilla.org/uriloader/handler-service;1"]
-      .getService(Components.interfaces.nsIHandlerService);
+    const handlerSvc = SpecialPowers.Cc["@mozilla.org/uriloader/handler-service;1"]
+      .getService(SpecialPowers.Ci.nsIHandlerService);
     handlerSvc.remove(handlerInfo);
     
-    var prefs = Components.classes["@mozilla.org/preferences-service;1"]
-      .getService(Components.interfaces.nsIPrefService);
+    var prefs = SpecialPowers.Cc["@mozilla.org/preferences-service;1"]
+      .getService(SpecialPowers.Ci.nsIPrefService);
     prefs = prefs.getBranch("browser.download.");
 
     var prefKeys = ["dir", "useDownloadDir", "folderList", 
                     "manager.closeWhenDone", "manager.showWhenStarting"];
     for (var i = 0; i < prefKeys.length; i++)
       if (prefs.prefHasUserValue(prefKeys[i]))
         prefs.clearUserPref(prefKeys[i]);
   }
--- a/security/manager/ssl/tests/mochitest/stricttransportsecurity/test_stricttransportsecurity.html
+++ b/security/manager/ssl/tests/mochitest/stricttransportsecurity/test_stricttransportsecurity.html
@@ -42,19 +42,18 @@
 
   function endRound(round) {
     // remove all the iframes in the document
     document.body.removeChild(document.getElementById('ifr_bootstrap'));
     for (var test in testframes)
       document.body.removeChild(document.getElementById('ifr_' + test));
 
     // clean up the STS state
-    netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
-    const Cc = Components.classes;
-    const Ci = Components.interfaces;
+    const Cc = SpecialPowers.Cc;
+    const Ci = SpecialPowers.Ci;
     var ios = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);
     var thehost = ios.newURI("http://example.com", null, null);
 
     var sss = Cc["@mozilla.org/ssservice;1"].getService(Ci.nsISiteSecurityService);
     sss.removeState(Ci.nsISiteSecurityService.HEADER_HSTS, thehost, 0);
   }
 
   function loadVerifyFrames(round) {
--- a/toolkit/components/alerts/test/test_alerts.html
+++ b/toolkit/components/alerts/test/test_alerts.html
@@ -13,17 +13,16 @@
 
 <br>Alerts service, with observer "synchronous" case.
 <br>
 <br>Did a notification appear anywhere?
 <br>If so, the test will finish once the notification disappears.
 
 <pre id="test">
 <script class="testbody" type="text/javascript">
-netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
 
 var observer = {
   alertShow: false,
   observe: function (aSubject, aTopic, aData) {
     if (aTopic == "alertclickcallback") { 
       todo(false, "Did someone click the notification while running mochitests? (Please don't.)");
     } else if (aTopic == "alertshow") {
       ok(!this.alertShow, "Alert should not be shown more than once");
@@ -32,18 +31,18 @@ var observer = {
       is(aTopic, "alertfinished", "Checking the topic for a finished notification");
       SimpleTest.finish();
     }
     is(aData, "foobarcookie", "Checking whether the alert cookie was passed correctly");
   }
 };
 
 function runTest() {
-  const Cc = Components.classes;
-  const Ci = Components.interfaces;
+  const Cc = SpecialPowers.Cc;
+  const Ci = SpecialPowers.Ci;
 
   if (!("@mozilla.org/alerts-service;1" in Cc)) {
     todo(false, "Alerts service does not exist in this application");
     return;
   }
 
   ok(true, "Alerts service exists in this application");
 
--- a/toolkit/components/alerts/test/test_alerts_noobserve.html
+++ b/toolkit/components/alerts/test/test_alerts_noobserve.html
@@ -13,20 +13,19 @@
 
 <br>Alerts service, without observer "asynchronous" case.
 <br>
 <br>A notification should soon appear somewhere.
 <br>If there has been no crash when the notification (later) disappears, assume all is good.
 
 <pre id="test">
 <script class="testbody" type="text/javascript">
-netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
 
-const Cc = Components.classes;
-const Ci = Components.interfaces;
+const Cc = SpecialPowers.Cc;
+const Ci = SpecialPowers.Ci;
 
 var gNotificationIsAvailable;
 
 if (!("@mozilla.org/alerts-service;1" in Cc)) {
   todo(false, "Alerts service does not exist in this application");
 } else {
   ok(true, "Alerts service exists in this application");
 
--- a/toolkit/components/microformats/tests/test_Microformats.html
+++ b/toolkit/components/microformats/tests/test_Microformats.html
@@ -183,33 +183,31 @@
     <div class="fn">John Doe</div>
   </div>
   <div class="vcard" id="two">
     <div class="fn">John Smith</div>
   </div>
 </div>
 
 <pre id="test">
-<script class="testbody" type="text/javascript">
+<script class="testbody" type="application/javascript;version=1.8">
 
 test_Microformats();
 test_hCard();
 
 function test_Microformats() {
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-
-  Components.utils.import("resource://gre/modules/Microformats.js");
+  let { Microformats, hCard, hCalendar } = SpecialPowers.Cu.import("resource://gre/modules/Microformats.js");
 
   ok(Microformats, "Check global access to Microformats");
   var hCards = Microformats.get("hCard", document.getElementById("test_1"), {showHidden: true});
   is(hCards.length, 1, "Check Microformats.get");
   is(Microformats.count("hCard", document.getElementById("test_1"),  {showHidden: true}), 1, "Check Microformats.count");
   is(Microformats.count("hCard", document.getElementById("test_1"),  {showHidden: true, debug: true}), 2, "Check Microformats.count (debug)");
   ok(Microformats.isMicroformat(document.getElementById("vcard1_node")), "Check isMicroformat");
-  is(Microformats.getParent(document.getElementById("vcard1_org")), document.getElementById("vcard1_node"), "Check getParent");
+  is(SpecialPowers.unwrap(Microformats.getParent(document.getElementById("vcard1_org"))), document.getElementById("vcard1_node"), "Check getParent");
   is(Microformats.getNamesFromNode(document.getElementById("vcard1_node")), "hCard", "Check getNamesFromNode");
   
   var hCardArray1 = Microformats.get("hCard", document.getElementById("test_1"), {showHidden: true});
   is(hCardArray1.length, 1, "Check showHidden=true");
   var hCardArray2 = Microformats.get("hCard", document.getElementById("test_1"), {showHidden: false});
   is(hCardArray2.length, 0, "Check showHidden=false");
   
   var inner_parent = Microformats.getParent(document.getElementById("inner_vcard"));
@@ -284,19 +282,17 @@ function test_Microformats() {
   var valueCard = new hCard(document.getElementById("valuespace_6"));
   is(valueCard.fn, "John Doe", "valuespace_6");
   var valueCard = new hCard(document.getElementById("valuespace_7"));
   is(valueCard.fn, "JohnDoe", "valuespace_7");
 
 }
 
 function test_hCard() {
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-
-  Components.utils.import("resource://gre/modules/Microformats.js");
+  var Microformats = SpecialPowers.Cu.import("resource://gre/modules/Microformats.js").Microformats;
   
   var hCards = Microformats.get("hCard", document.getElementById("test_1"),  {showHidden: true}); 
   
   is(hCards[0].fn, "Tantek Çelik", "Check for fn on test vcard");
   is(hCards[0].url, "http://tantek.com/", "Check for url on test vcard");
 }
 
 </script>
--- a/toolkit/components/microformats/tests/test_Microformats_add.html
+++ b/toolkit/components/microformats/tests/test_Microformats_add.html
@@ -75,17 +75,17 @@
     </span>
   </div>
 
   <!-- Ok, the test, here we go -->
   <pre id="test">
   <script class="testbody" type="text/javascript">
 
   function hTest(node, validate) {
-    netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
+    var Microformats = SpecialPowers.Cu.import("resource://gre/modules/Microformats.js").Microformats;
     if (node)
       Microformats.parser.newMicroformat(this, node, "hTest", validate);
   }
 
   hTest.prototype.toString = function () {
     return("This is a test");
   }
 
@@ -144,17 +144,17 @@
       "date" : {
         datatype: "dateTime",
       }
     }
   };
   test_MicroformatsAPI();
 
   function doTest3_4_and5() {
-    netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
+    var Microformats = SpecialPowers.Cu.import("resource://gre/modules/Microformats.js").Microformats;
     ok(Microformats, "Make sure we still have a microformats object");
 
     var mfs = Microformats.get("hTest",
                                document.getElementById("test3"),
                                {recurseExternalFrames: true});
 
     is(mfs.length, 0, "Check hTest 3 is invalid");
 
@@ -176,18 +176,17 @@
       var jsDate = new Date(Microformats.parser.dateFromISO8601(mfs[0].date));
       ok(false, "Invalid JS Date should throw");
     } catch (ex) {
       ok(true, "Check that getting invalid jsdate throws");
     }
   }
 
   function test_MicroformatsAPI() {
-    netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-    Components.utils.import("resource://gre/modules/Microformats.js");
+    var Microformats = SpecialPowers.Cu.import("resource://gre/modules/Microformats.js").Microformats;
 
     // Make sure they aren't microformats yet
     is(Microformats.isMicroformat(document.getElementById("mftest-version1")),
        false, "Check that the mfTest microformat does not exist yet");
 
     try {
       Microformats.add("hTest", hTest_definition);
     } catch (ex) {
--- a/toolkit/components/microformats/tests/test_Microformats_adr.html
+++ b/toolkit/components/microformats/tests/test_Microformats_adr.html
@@ -14,27 +14,23 @@
 </div>
 <pre id="test">
 <script class="testbody" type="text/javascript">
 
 test_Microformats();
 test_adr();
 
 function test_Microformats() {
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-
-  Components.utils.import("resource://gre/modules/Microformats.js");
+  var Microformats = SpecialPowers.Cu.import("resource://gre/modules/Microformats.js").Microformats;
 
   ok(Microformats, "Check global access to Microformats");
 };
 
 function test_adr() {
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-
-  Components.utils.import("resource://gre/modules/Microformats.js");
+  var adr = SpecialPowers.Cu.import("resource://gre/modules/Microformats.js").adr;
 
   var address;
 
   address = new adr(document.getElementById("01-extended-address"));
 
   is(address.toString(), "Park Bench", "01-extended-address");
 }
 
--- a/toolkit/components/microformats/tests/test_Microformats_count.html
+++ b/toolkit/components/microformats/tests/test_Microformats_count.html
@@ -92,18 +92,17 @@
     try {
       Components.utils.import("resource://gre/modules/Microformats.js");
       ok(false, "Should not execute this code");
     } catch(ex) {
       ok(true, "Expected exception");
     }
 
     // Gonna do things the right way
-    netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-    Components.utils.import("resource://gre/modules/Microformats.js");
+    var Microformats = SpecialPowers.Cu.import("resource://gre/modules/Microformats.js").Microformats;
 
     // Test Microformat frame recursion - start with counting
     var count = Microformats.count("adr",
                                    document.getElementById("contentbody"),
                                    {recurseExternalFrames: false}, // do not recurse frames
                                    0);    // current count
     is(count, 2, "No frame recursion, finds 2 adr's (none in frames)");
 
--- a/toolkit/components/microformats/tests/test_Microformats_geo.html
+++ b/toolkit/components/microformats/tests/test_Microformats_geo.html
@@ -78,27 +78,23 @@
 </div>
 <pre id="test">
 <script class="testbody" type="text/javascript">
 
 test_Microformats();
 test_geo();
 
 function test_Microformats() {
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-
-  Components.utils.import("resource://gre/modules/Microformats.js");
+  var Microformats = SpecialPowers.Cu.import("resource://gre/modules/Microformats.js").Microformats;
 
   ok(Microformats, "Check global access to Microformats");
 };
 
 function test_geo() {
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-
-  Components.utils.import("resource://gre/modules/Microformats.js");
+  var geo = SpecialPowers.Cu.import("resource://gre/modules/Microformats.js").geo;
 
   var Geo;
 
   Geo = new geo(document.getElementById("01-geo-basic"));
 
   is(Geo.latitude, "37.77", "01-geo-basic - latitude");
   is(Geo.longitude, "-122.411", "01-geo-basic - longitude");
 
--- a/toolkit/components/microformats/tests/test_Microformats_getters.html
+++ b/toolkit/components/microformats/tests/test_Microformats_getters.html
@@ -6,18 +6,17 @@
   <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"></link>
 </head>
 <body id="contentbody">
   <pre id="test">
   <script class="testbody" type="text/javascript">
 
   // Called from onload in iframe
   function test_MicroformatsAPI() {
-    netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-    Components.utils.import("resource://gre/modules/Microformats.js");
+    var Microformats = SpecialPowers.Cu.import("resource://gre/modules/Microformats.js").Microformats;
 
     // Test that we can get them all
     var mfs = [];
     mfs = Microformats.get("adr",
                            document.getElementById("content"),
                            {showHidden: true});
 
     is(mfs.length, 2, "Two adr's in our array");
--- a/toolkit/components/microformats/tests/test_Microformats_hCalendar.html
+++ b/toolkit/components/microformats/tests/test_Microformats_hCalendar.html
@@ -182,27 +182,23 @@
 
 <pre id="test">
 <script class="testbody" type="text/javascript">
 
 test_Microformats();
 test_hCard();
 
 function test_Microformats() {
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-
-  Components.utils.import("resource://gre/modules/Microformats.js");
+  var Microformats = SpecialPowers.Cu.import("resource://gre/modules/Microformats.js").Microformats;
 
   ok(Microformats, "Check global access to Microformats");
 };
 
 function test_hCard() {
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-
-  Components.utils.import("resource://gre/modules/Microformats.js");
+  var hCalendar = SpecialPowers.Cu.import("resource://gre/modules/Microformats.js").hCalendar;
 
   var hcalendar;
 
   hcalendar = new hCalendar(document.getElementById("01-component-vevent-dtstart-date"));
 
   is(hcalendar.dtstart, "1997-09-03", "01-component-vevent-dtstart-date - dtstart");
 
   hcalendar = new hCalendar(document.getElementById("02-component-vevent-dtstart-datetime"));
--- a/toolkit/components/microformats/tests/test_Microformats_hCard.html
+++ b/toolkit/components/microformats/tests/test_Microformats_hCard.html
@@ -558,27 +558,23 @@
 </div>
 <pre id="test">
 <script class="testbody" type="text/javascript">
 
 test_Microformats();
 test_hCard();
 
 function test_Microformats() {
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-
-  Components.utils.import("resource://gre/modules/Microformats.js");
+  var Microformats = SpecialPowers.Cu.import("resource://gre/modules/Microformats.js").Microformats;
 
   ok(Microformats, "Check global access to Microformats");
 };
 
 function test_hCard() {
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-
-  Components.utils.import("resource://gre/modules/Microformats.js");
+  var hCard = SpecialPowers.Cu.import("resource://gre/modules/Microformats.js").hCard;
 
   var hcard;
 
   hcard = new hCard(document.getElementById("01-tantek-basic"));
 
   is(hcard.fn, "Tantek Çelik", "01-tantek-basic - fn");
   is(hcard.url, "http://tantek.com/", "01-tantek-basic - url");
   is(hcard.n["given-name"][0], "Tantek", "01-tantek-basic - given-name");
--- a/toolkit/components/microformats/tests/test_Microformats_negative.html
+++ b/toolkit/components/microformats/tests/test_Microformats_negative.html
@@ -63,18 +63,17 @@
 
   <!-- Ok, the test, here we go -->
   <pre id="test">
   <script class="testbody" type="text/javascript">
 
   test_MicroformatsAPI();
 
   function test_MicroformatsAPI() {
-    netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-    Components.utils.import("resource://gre/modules/Microformats.js");
+    var Microformats = SpecialPowers.Cu.import("resource://gre/modules/Microformats.js").Microformats;
 
     // Test to see if we can get the invalid vcard
     var mfs = Microformats.get("hCard",
                                document.getElementById("content"),
                                { });
 
     is(mfs.length, 0, "Check that we can't get invalid vcard");
 
--- a/toolkit/components/microformats/tests/test_framerecursion.html
+++ b/toolkit/components/microformats/tests/test_framerecursion.html
@@ -13,18 +13,17 @@
   <script class="testbody" type="text/javascript">
 
   // Start the test once the iFrame loads
   function onLoad() {
     test_MicroformatsAPI();
   }
 
   function test_MicroformatsAPI() {
-    netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-    Components.utils.import("resource://gre/modules/Microformats.js");
+    var Microformats = SpecialPowers.Cu.import("resource://gre/modules/Microformats.js").Microformats;
 
     count = Microformats.count("geo",
                               document.getElementById("contentbody"),
                               {recurseExternalFrames: false},
                               0);
     is(count, 1, "Only one geo - we don't count external frames");
 
     count = Microformats.count("geo",
--- a/toolkit/components/places/tests/Makefile.in
+++ b/toolkit/components/places/tests/Makefile.in
@@ -12,21 +12,21 @@ include $(DEPTH)/config/autoconf.mk
 
 # Files in the main "tests" folder.
 XPCSHELL_TESTS_COMMON = \
   head_common.js \
   $(NULL)
 
 # Simple MochiTests
 MOCHITEST_FILES = \
-	mochitest/test_bug_411966.html \
-	mochitest/test_bug_94514.html \
 	mochitest/bug94514-postpage.html \
 	$(NULL)
 
 MOCHITEST_CHROME_FILES = \
+	mochitest/test_bug_94514.html \
+	mochitest/test_bug_411966.html \
 	mochitest/test_bug_461710_perwindowpb.html \
 	$(NULL)
 
 include $(topsrcdir)/config/rules.mk
 
 libs:: $(XPCSHELL_TESTS_COMMON)
 	$(INSTALL) $(foreach f,$^,"$f") $(DEPTH)/_tests/xpcshell/$(relativesrcdir)
--- a/toolkit/components/places/tests/mochitest/bug_411966/redirect.js
+++ b/toolkit/components/places/tests/mochitest/bug_411966/redirect.js
@@ -1,21 +1,19 @@
 /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim:set ts=2 sw=2 sts=2 et: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
-netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
-
 const Ci = Components.interfaces;
 const Cc = Components.classes;
-const Cu = Components.utils
+const Cu = Components.utils;
 
-Cu.import("resource://gre/modules/PlacesUtils.jsm");
+var PlacesUtils = Cu.import("resource://gre/modules/PlacesUtils.jsm").PlacesUtils;
 
 // Get Services.
 var histsvc = Cc["@mozilla.org/browser/nav-history-service;1"].
               getService(Ci.nsINavHistoryService);
 ok(histsvc != null, "Could not get History Service");
 var bhist = histsvc.QueryInterface(Ci.nsIBrowserHistory);
 ok(bhist != null, "Could not get Browser History Service");
 var ios = Cc["@mozilla.org/network/io-service;1"].
@@ -49,17 +47,16 @@ StreamListener.prototype = {
   mChannel: null,
 
   // nsIStreamListener
   onStartRequest: function (aRequest, aContext) {
     this.mData = "";
   },
 
   onDataAvailable: function (aRequest, aContext, aStream, aSourceOffset, aLength) {
-    netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
     // We actually don't need received data
     var scriptableInputStream =
       Components.classes["@mozilla.org/scriptableinputstream;1"]
                 .createInstance(Components.interfaces.nsIScriptableInputStream);
     scriptableInputStream.init(aStream);
 
     this.mData += scriptableInputStream.read(aLength);
   },
@@ -70,57 +67,53 @@ StreamListener.prototype = {
     else
       throw("Could not get page.");
 
     this.mChannel = null;
   },
 
   // nsIChannelEventSink
   asyncOnChannelRedirect: function (aOldChannel, aNewChannel, aFlags, callback) {
-    netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
     // If redirecting, store the new channel
     this.mChannel = aNewChannel;
     callback.onRedirectVerifyCallback(Components.results.NS_OK);
   },
 
   // nsIInterfaceRequestor
   getInterface: function (aIID) {
-    netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
     try {
       return this.QueryInterface(aIID);
     } catch (e) {
       throw Components.results.NS_NOINTERFACE;
     }
   },
 
   // nsIProgressEventSink (not implementing will cause annoying exceptions)
   onProgress : function (aRequest, aContext, aProgress, aProgressMax) { },
   onStatus : function (aRequest, aContext, aStatus, aStatusArg) { },
 
   // nsIHttpEventSink (not implementing will cause annoying exceptions)
   onRedirect : function (aOldChannel, aNewChannel) { },
 
   // we are faking an XPCOM interface, so we need to implement QI
   QueryInterface : function(aIID) {
-    netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
     if (aIID.equals(Components.interfaces.nsISupports) ||
         aIID.equals(Components.interfaces.nsIInterfaceRequestor) ||
         aIID.equals(Components.interfaces.nsIChannelEventSink) ||
         aIID.equals(Components.interfaces.nsIProgressEventSink) ||
         aIID.equals(Components.interfaces.nsIHttpEventSink) ||
         aIID.equals(Components.interfaces.nsIStreamListener))
       return this;
 
     throw Components.results.NS_NOINTERFACE;
   }
 };
 
 // Check Callback.
 function checkDB(data){
-  netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
   var referrer = this.mChannel.QueryInterface(Ci.nsIHttpChannel).referrer;
 
   addVisits(
     {uri: this.mChannel.URI,
       transition: Ci.nsINavHistoryService.TRANSITION_REDIRECT_PERMANENT,
       referrer: referrer},
     function() {
       // Get all pages visited from the original typed one
--- a/toolkit/components/places/tests/mochitest/test_bug_411966.html
+++ b/toolkit/components/places/tests/mochitest/test_bug_411966.html
@@ -1,32 +1,30 @@
 <!DOCTYPE HTML>
 <html>
   <!--
     https://bugzilla.mozilla.org/show_bug.cgi?id=411966
   -->
   <head>
     <title>Test for Bug 411966</title>
-    <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
-    <script type="text/javascript" src="mochitest/bug_411966/redirect.js"></script>
-    <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
+    <script type="text/javascript" src="http://mochi.test:8888/tests/SimpleTest/SimpleTest.js"></script>
+    <script type="text/javascript" src="http://mochi.test:8888/tests/toolkit/components/places/tests/mochitest/bug_411966/redirect.js"></script>
+    <link rel="stylesheet" type="text/css" href="http://mochi.test:8888/tests/SimpleTest/test.css" />
   </head>
   <body>
     <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=411966">
       Mozilla Bug 411966</a>
     <p id="display"></p>
     <div id="content" style="display: none">
       <iframe id="iframe"></iframe>
     </div>
     <pre id="test">
       <script class="testbody" type="text/javascript">
 
       /** Test for Bug 411966 **/
-      netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
-
       addVisits(typedURI, function() {
         histsvc.markPageAsTyped(typedURI);
 
         var clickedLinkChannel = ios.newChannelFromURI(clickedLinkURI);
         clickedLinkChannel.QueryInterface(Ci.nsIHttpChannel).referrer = typedURI;
         var listener = new StreamListener(clickedLinkChannel, checkDB);
         clickedLinkChannel.notificationCallbacks = listener;
         clickedLinkChannel.asyncOpen(listener, null);
--- a/toolkit/components/places/tests/mochitest/test_bug_94514.html
+++ b/toolkit/components/places/tests/mochitest/test_bug_94514.html
@@ -2,36 +2,34 @@
 <html>
 <!--
 https://bugzilla.mozilla.org/show_bug.cgi?id=94514
 Specifically, this tests that a page that is obtained via a post request does
 not get added to global history.
 -->
 <head>
   <title>Test for Bug 94515</title>
-  <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <script type="text/javascript" src="http://mochi.test:8888/tests/SimpleTest/SimpleTest.js"></script>
 
-  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
+  <link rel="stylesheet" type="text/css" href="http://mochi.test:8888/tests/SimpleTest/test.css" />
 </head>
 <body>
 <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=94514">Mozilla Bug 94514</a>
 
 <div id="content" style="display: none">
   
 </div>
 <pre id="test">
 <script class="testbody" type="text/javascript">
 
 SimpleTest.waitForExplicitFinish();
 
 var startURI = "http://mochi.test:8888/tests/toolkit/components/places/tests/bug94514-postpage.html";
 var postedURI = startURI + "?posted=1";
 
-netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-
 const Cc = Components.classes;
 const Ci = Components.interfaces;
 
 Components.utils.import("resource://gre/modules/PlacesUtils.jsm");
 
 var ios = Cc["@mozilla.org/network/io-service;1"].
           getService(Ci.nsIIOService);
 var startPage = ios.newURI(startURI, null, null);
@@ -39,17 +37,16 @@ var postedPage = ios.newURI(postedURI, n
 var w = null;
 
 // Because adding visits is async, we will not be notified imemdiately.
 var os = Cc["@mozilla.org/observer-service;1"].
          getService(Ci.nsIObserverService);
 var visitObserver = {
   _visitCount: 0,
   observe: function(aSubject, aTopic, aData) {
-    netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
     if (!startPage.equals(aSubject.QueryInterface(Ci.nsIURI)) ||
         ++this._visitCount < 2) {
       return;
     }
     os.removeObserver(this, aTopic);
     finishTest();
   },
 };
--- a/toolkit/components/url-classifier/tests/mochitest/test_classifier.html
+++ b/toolkit/components/url-classifier/tests/mochitest/test_classifier.html
@@ -9,19 +9,18 @@
 <body onload="doUpdate(testUpdate);">
 <p id="display"></p>
 <div id="content" style="display: none">
 </div>
 <pre id="test">
 
 <script class="testbody" type="text/javascript">
 
-netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-var Cc = Components.classes;
-var Ci = Components.interfaces;
+var Cc = SpecialPowers.Cc;
+var Ci = SpecialPowers.Ci;
 
 // Add some URLs to the malware database.
 var testData = "malware.example.com/";
 var testUpdate =
   "n:1000\ni:test-malware-simple\nad:1\n" +
   "a:524:32:" + testData.length + "\n" +
   testData;
 
@@ -50,18 +49,16 @@ function doUpdate(update) {
         {"set" : [["browser.safebrowsing.malware.enabled", true]]},
         function loadTestFrame() {
           document.getElementById("testFrame").src = "classifierFrame.html";
         }
       );
     }
   };
 
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-
   dbService.beginUpdate(listener, "test-malware-simple", "");
   dbService.beginStream("", "");
   dbService.updateStream(update);
   dbService.finishStream();
   dbService.finishUpdate();
 }
 
 // Expected finish() call is in "classifierFrame.html".
--- a/toolkit/components/url-classifier/tests/mochitest/test_classifier_worker.html
+++ b/toolkit/components/url-classifier/tests/mochitest/test_classifier_worker.html
@@ -9,19 +9,18 @@
 <body onload="doUpdate(testUpdate);">
 <p id="display"></p>
 <div id="content" style="display: none">
 </div>
 <pre id="test">
 
 <script class="testbody" type="text/javascript">
 
-netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-var Cc = Components.classes;
-var Ci = Components.interfaces;
+var Cc = SpecialPowers.Cc;
+var Ci = SpecialPowers.Ci;
 
 // Add some URLs to the malware database.
 var testData = "example.com/tests/toolkit/components/url-classifier/tests/mochitest/evilWorker.js";
 var testUpdate =
   "n:1000\ni:test-malware-simple\nad:550\n" +
   "a:550:32:" + testData.length + "\n" +
   testData;
 
@@ -51,18 +50,16 @@ function doUpdate(update) {
         function loadTestFrame() {
           document.getElementById("testFrame").src =
             "http://example.com/tests/toolkit/components/url-classifier/tests/mochitest/workerFrame.html";
         }
       );
     }
   };
 
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-
   dbService.beginUpdate(listener, "test-malware-simple", "");
   dbService.beginStream("", "");
   dbService.updateStream(update);
   dbService.finishStream();
   dbService.finishUpdate();
 }
 
 function onmessage(event)
--- a/uriloader/exthandler/tests/mochitest/test_unsafeBidiChars.xhtml
+++ b/uriloader/exthandler/tests/mochitest/test_unsafeBidiChars.xhtml
@@ -60,20 +60,20 @@ function run_next_test() {
     run_test(gTests[gCounter], run_next_test);
 }
 
 SimpleTest.waitForExplicitFinish();
 
 netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
 
 const HELPERAPP_DIALOG_CONTRACT = "@mozilla.org/helperapplauncherdialog;1";
-const HELPERAPP_DIALOG_CID = Components.ID(Components.classes[HELPERAPP_DIALOG_CONTRACT].number);
+const HELPERAPP_DIALOG_CID = SpecialPowers.wrap(SpecialPowers.Components).ID(SpecialPowers.Cc[HELPERAPP_DIALOG_CONTRACT].number);
 
-const FAKE_CID = Components.classes["@mozilla.org/uuid-generator;1"].
-  getService(Components.interfaces.nsIUUIDGenerator).generateUUID();
+const FAKE_CID = SpecialPowers.Cc["@mozilla.org/uuid-generator;1"].
+  getService(SpecialPowers.Ci.nsIUUIDGenerator).generateUUID();
 
 function HelperAppLauncherDialog() {}
 HelperAppLauncherDialog.prototype = {
   REASON_CANTHANDLE: 0,
   REASON_SERVERREQUEST: 1,
   REASON_TYPESNIFFED: 2,
   show: function(aLauncher, aWindowContext, aReason) {
     netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
@@ -82,43 +82,43 @@ HelperAppLauncherDialog.prototype = {
        "The filename should be correctly sanitized");
     gCallback();
   },
   promptForSaveToFile: function(aLauncher, aWindowContext, aDefaultFileName, aSuggestedFileExtension, aForcePrompt) {
     return null;
   },
   QueryInterface: function(aIID) {
     netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
-    if (aIID.equals(Components.interfaces.nsISupports) ||
-        aIID.equals(Components.interfaces.nsIHelperAppLauncherDialog))
+    if (aIID.equals(SpecialPowers.Ci.nsISupports) ||
+        aIID.equals(SpecialPowers.Ci.nsIHelperAppLauncherDialog))
       return this;
-    throw Components.results.NS_ERROR_NO_INTERFACE;
+    throw SpecialPowers.Cr.NS_ERROR_NO_INTERFACE;
   }
 };
 
 var factory = {
   createInstance: function(aOuter, aIID) {
     netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
     if (aOuter != null)
-      throw Components.results.NS_ERROR_NO_AGGREGATION;
+      throw SpecialPowers.Cr.NS_ERROR_NO_AGGREGATION;
     return new HelperAppLauncherDialog().QueryInterface(aIID);
   }
 };
 
 dump("RegisterFactory...\n");
-Components.manager
-          .QueryInterface(Components.interfaces.nsIComponentRegistrar)
+SpecialPowers.wrap(SpecialPowers.Components).manager
+          .QueryInterface(SpecialPowers.Ci.nsIComponentRegistrar)
           .registerFactory(FAKE_CID, "",
                            HELPERAPP_DIALOG_CONTRACT,
                            factory);
 
 function finish_test() {
   dump("UnregisterFactory...\n");
-  Components.manager
-            .QueryInterface(Components.interfaces.nsIComponentRegistrar)
+  SpecialPowers.wrap(SpecialPowers.Components).manager
+            .QueryInterface(SpecialPowers.Ci.nsIComponentRegistrar)
             .registerFactory(HELPERAPP_DIALOG_CID, "",
                              HELPERAPP_DIALOG_CONTRACT,
                              null);
   SimpleTest.finish();
 }
 
 var i,j;
 
--- a/widget/tests/test_bug565392.html
+++ b/widget/tests/test_bug565392.html
@@ -15,26 +15,26 @@ https://bugzilla.mozilla.org/show_bug.cg
   
 </div>
 <pre id="test">
 <script type="application/javascript">
 
 /** Test for Bug 565392 **/
 
   netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-  const Cc = Components.classes;
-  const Ci = Components.interfaces;
+  const Cc = SpecialPowers.Cc;
+  const Ci = SpecialPowers.Ci;
   var ds = Cc["@mozilla.org/file/directory_service;1"]
              .getService(Ci.nsIProperties);
   var dir1 = ds.get("ProfD", Ci.nsIFile);
   var clipboard = Cc["@mozilla.org/widget/clipboard;1"]
                     .getService(Ci.nsIClipboard);
   
   function getLoadContext() {
-    return window.QueryInterface(Ci.nsIInterfaceRequestor)
+    return SpecialPowers.wrap(window).QueryInterface(Ci.nsIInterfaceRequestor)
                  .getInterface(Ci.nsIWebNavigation)
                  .QueryInterface(Ci.nsILoadContext);
   }
 
   function getTransferableFile(file) {
     var transferable = Cc['@mozilla.org/widget/transferable;1']
                          .createInstance(Ci.nsITransferable);
     transferable.init(getLoadContext());