Toggle A Boolean Pref

Talk about add-ons and extension development.
Post Reply
AlbertG
Posts: 57
Joined: April 12th, 2006, 2:44 pm

Toggle A Boolean Pref

Post by AlbertG »

Greetings!

I have been bumping about in the codeblocks of a small "JS Button" extension created by "ivangurkin" called "NJS" ( https://addons.mozilla.org/en-US/firefo ... src=search ).

While an interesting piece of work, I seem to be needing something even more basic; and have therefore undertaken a short "learning exercise" to tweak his code :wink:

Basically, all I want to do is toggle the boolean pref "javascript.enabled" by clicking on the NJS address bar icon on-the-fly. Don't need (or want) any other functionality; as I'm a simple creature at heart :)

For quick reference, here's ivangurkin's core NJS code in a nutshell --

"background.js":

Code: Select all

let useSync;

function restoreOptions() {
	function setCurrentChoice(result) {
		useSync = result.useSync;
	}

	function onError(error) {
		console.log('Error: ${error}');
	}

	browser.storage.local.get("useSync").then(setCurrentChoice, onError);
}

document.addEventListener("DOMContentLoaded", restoreOptions);

function isBlock(dict, host) {
	if (dict[host] !== undefined) {
		return dict[host];
	}
	return false;
}

function getHost(url) {
	return new URL(url).hostname;
}

function getStorage() {
	//return useSync ? browser.storage.sync : browser.storage.local;
	return browser.storage.local;
}

function pushNoJsHeader(response) {
	let host = getHost(response.url);
	let headers = response.responseHeaders;
	return new Promise((resolve) => {
		getStorage().get(host).then(item => {
			if (isBlock(item, host)) {
				headers.push({name: "Content-Security-Policy", value: "script-src 'none';"});
			}
			resolve({responseHeaders: headers});
		});
	});
}

browser.webRequest.onHeadersReceived.addListener(pushNoJsHeader,
	{
		urls: ["<all_urls>"],
		types: ["main_frame", "sub_frame"]
	},
	["blocking", "responseHeaders"]
);

browser.tabs.onUpdated.addListener((id, inf) => {
	if (inf.url && !inf.url.startsWith('moz-extension') && !inf.url.startsWith('about')) {
		let host = getHost(inf.url);
		getStorage().get(host).then(item => {
			let blocked = isBlock(item, host);
			browser.pageAction.setIcon({tabId: id, path: blocked ? "js_off.svg" : "js_on.svg"});
			browser.pageAction.setTitle({tabId: id, title: 'Javascript ' + (blocked ? 'Disabled' : 'Enabled')});
		});
		browser.pageAction.show(id);
	}
});

browser.pageAction.onClicked.addListener(function (tab) {
	let host = getHost(tab.url);
	getStorage().get(host).then(item => {
		if (!isBlock(item, host)) {
			let to_store = {};
			to_store[host] = true;
			getStorage().set(to_store).then(function () {
				browser.tabs.reload();
			});
		} else {
			getStorage().remove(host).then(function () {
				browser.tabs.reload();
			});
		}
	});
});
...and "options.js":

Code: Select all

function saveOptions(e) {
	e.preventDefault();
	browser.storage.local.set({
		useSync: document.querySelector("#useSyncId").checked
	});
}

function restoreOptions() {
	function setCurrentChoice(result) {
		document.querySelector("#useSyncId").checked = result.useSync;
	}

	function onError(error) {
		console.log('Error: ${error}');
	}

	browser.storage.local.get("useSync").then(setCurrentChoice, onError);
}

document.addEventListener("DOMContentLoaded", restoreOptions);
document.querySelector("form").addEventListener("submit", saveOptions);
From what I've been able to glean, the trick in doing something like this entails working "browser.storage.local.get()" and "browser.storage.local.set()"; but I'm hard pressed to figure out just how this comes together...

Working with the 68.10.0 ESR release, just for the record :wink:

Cheers and thanks!
morat
Posts: 6394
Joined: February 3rd, 2009, 6:29 pm

Re: Toggle A Boolean Pref

Post by morat »

You can't access preferences.

Does the WebExtensions API provide access to preferences?
http://wiki.mozilla.org/WebExtensions/F ... erences.3F
AlbertG
Posts: 57
Joined: April 12th, 2006, 2:44 pm

Re: Toggle A Boolean Pref

Post by AlbertG »

@morat:

Thanks for the insight.

Is this the reason why calling

Code: Select all

function setJavascriptPref(bool) {
   prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
   prefs.setBoolPref("javascript.enabled", bool);
}
in an Add-on's background.js script results in
TypeError: Components.classes is undefined
being sent to the Browser Console?
morat
Posts: 6394
Joined: February 3rd, 2009, 6:29 pm

Re: Toggle A Boolean Pref

Post by morat »

Yep.

You can access preferences with userChrome.js hacks.

userChrome.js hacks
http://forums.mozillazine.org/viewtopic ... &t=3056596

Here is an obsolete toggle javascript custom button.

Code: Select all

/*Initialization code*/
var prefBranch = Components.classes["@mozilla.org/preferences-service;1"].
  getService(Components.interfaces.nsIPrefBranch);
var pref = "javascript.enabled";
var strEnable = "[enable] JavaScript";
var strDisable = "[disable] JavaScript";
var imgEnable = "data:image/png;base64," +
  "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAjpJRE" +
  "FUOMttkztoVFEQhr95nHPuRsFVg69CAiJBIoJgo2JjGbUL2NmJFmphIQElnWBhY2wUOxsL" +
  "wSa6SNpAChETewWxUAgWKSKbzXLvWKwboskPpzrzP2aGEbZg38TUAeAGcB8oACICgEBP1B" +
  "6KyPOVz69WhhzZQj4HvAPaIIgKqKIoqCBAENDEqqd06efHl4sAsm9iyoHTQAcYRRVTw1TB" +
  "FBWLgYBICETdAPFLzSeBJQcOAvNAW90RNUwdy4574t71y3L08H4WPn3h9fsPNNEQ/f5o0z" +
  "TzwEkFrgBt/romT6RSUUqLUo1wfOwwe9t7uHh2gtIaGbxdu0ilansqVxyYFRHUDPWM50Iq" +
  "FZ4z5okmNseE50wTEE2NWKLu9WYdNIkqZo6lRCoFrwqWCq62ZcxgnpEIIgxVQyKSi4C6Ye" +
  "54TngquGfMHFXdXONwpSYQYTQheM44Kqgq6o55Rt0H7aj+dRf+hSASqAqE4yoCogMRNW5d" +
  "Pc+pE2P87m4w/bRDRMN2CKIgoSjQVxFEFVGLY2NHEJTdrYpHtyfZs7sFwNdvP3ZIIn0V0T" +
  "uDmIO8dx+/Ya27Tr+uaVWZug7Wuuu8mFveIYjcUTWba4jViIagBuDek7f0Nvp01zdY664z" +
  "/bSzQxusisicHDpzzRE5nauRTm61RlNp4Sljpv+fy1b8AiaBpc3foxdunkulepdyaXsumP" +
  "ngoLYLrAKXll8/WAQY2vB94dkiwXhEzDR13avrmmgCiGFJD5gBxodkgD8dCqDsePGH4QAA" +
  "AABJRU5ErkJggg==";
var imgDisable = "data:image/png;base64," +
  "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAdJJRE" +
  "FUOMt1kzFv2lAUhb/73n2yJRgYUJEYWbKUoWt+QJESRYKRhbVb/kClbN1Rto4wgBiYomTI" +
  "xsLajZ+AlCoDo0Ns3wzNs9yUHsmS9Z7P987xtYWahsPhJ+Ab8B1IAJxzcftFRH4AP9fr9e" +
  "+4KDXzOXAPtAC89xW4fl8UxUFVL1er1RZAhsOhAl+AB6DtnENE8N4jIgD2DhARIc9zgGdV" +
  "vQB+KdABHoGW974yqiree0ajkXQ6HXa7HdvtFlXFzNpFUTwCnx1wBbScc5U5hEAIgTRN6X" +
  "a7NBoN+v1+tZamKSGElqpeKXDrnCNGT5KEEEKVoK4kSSiKAjPjvc6tAiF2VtW/ro+AWM3M" +
  "4nSCxugfAd77KlUdEOWc+/OsiFRkVSUC4/xr38E/IO89Wt/w3jMYDOj1emRZxnK5pCgKQg" +
  "gnIWaGA15jChGxbrcLQJqmjMdjms0mAPv9/hTk1YnIdS2mzGYzsiyjLEvSNCXPc7IsY7PZ" +
  "cELXznt/V5blAcDMAFgsFhyPR7Isq6qc0EFE7hR4MrOvZvYAtCPoP6aoZ+ACeKrmMplMzk" +
  "MI96raSpIkvpOTJwOX0+l0C1CVn8/nW+AMuMnz/MXMqkrxdwZugLNoBngDCfaXqH4PqZEA" +
  "AAAASUVORK5CYII=";
prefBranch.setBoolPref(pref, true);
this.tooltipText = strEnable;
this.image = imgEnable;
this.leftclick = function (event) {
  if (prefBranch.getBoolPref(pref) == false) {
    prefBranch.setBoolPref(pref, true);
    this.tooltipText = strEnable;
    this.image = imgEnable;
  } else {
    prefBranch.setBoolPref(pref, false);
    this.tooltipText = strDisable;
    this.image = imgDisable;
  }
};
this.setAttribute("onclick", "custombuttons.gQuot.mHandler(event, this)");
Maybe you could convert it to a userChrome.js hack.
AlbertG
Posts: 57
Joined: April 12th, 2006, 2:44 pm

Re: Toggle A Boolean Pref

Post by AlbertG »

Thanks for the tip!

So, based upon all this, and, drawing on a couple of your key posts at http://forums.mozillazine.org/viewtopic ... &t=3056596 , what might be done is:

Create file <install directory>\defaults\pref\autoconfig.js:

Code: Select all

pref("general.config.sandbox_enabled", false);
pref("general.config.filename", "mozilla.cfg");
pref("general.config.obscure_value", 0);
Create file <install directory>\mozilla.cfg:

Code: Select all

// mozilla.cfg file needs to start with a comment line

// mozilla.cfg file is sandboxed by default i.e. can't use the Components object
// disable the sandbox by setting the general.config.sandbox_enabled pref to false

// run userChrome.js example.uc.js example.as.css example.css files in chrome folder
// do not run userChrome.css userContent.css example.js files in chrome folder

Components.utils.import("resource://gre/modules/Services.jsm");
Services.obs.addObserver(function (aSubject, aTopic, aData) {
  var chromeWindow = aSubject;
  chromeWindow.setTimeout(function () {
    try {
      if (chromeWindow.userChromeJsMod) return;
      chromeWindow.userChromeJsMod = true;
      var chromeFiles = chromeWindow.FileUtils.getDir("UChrm", []).directoryEntries;
      var sss = Components.classes["@mozilla.org/content/style-sheet-service;1"].
        getService(Components.interfaces.nsIStyleSheetService);
      while (chromeFiles.hasMoreElements()) {
        var file = chromeFiles.getNext().QueryInterface(Components.interfaces.nsIFile);
        var fileURI = Services.io.newFileURI(file);
        if (file.isFile()) {
          if (/(^userChrome|\.uc)\.js$/i.test(file.leafName)) {
            Services.scriptloader.loadSubScriptWithOptions(fileURI.spec, {target: chromeWindow, ignoreCache: true});
          } else if (/\.as\.css$/i.test(file.leafName)) {
            if (!sss.sheetRegistered(fileURI, sss.AGENT_SHEET)) {
              sss.loadAndRegisterSheet(fileURI, sss.AGENT_SHEET);
            }
          } else if (/^(?!(userChrome|userContent)\.css$).+\.css$/i.test(file.leafName)) {
            if (!sss.sheetRegistered(fileURI, sss.USER_SHEET)) {
              sss.loadAndRegisterSheet(fileURI, sss.USER_SHEET);
            }
          }
        }
      }
    } catch (e) {
      Components.utils.reportError(e); // [check] Show Content Messages
    }
  }, 10);
}, "browser-delayed-startup-finished", false);
Create file <profile directory>\chrome\JS_Toggler.uc.js:

Code: Select all

/*Initialization code*/
var prefBranch = Components.classes["@mozilla.org/preferences-service;1"].
  getService(Components.interfaces.nsIPrefBranch);
var pref = "javascript.enabled";
var strEnable = "[enable] JavaScript";
var strDisable = "[disable] JavaScript";
var imgEnable = "data:image/png;base64," +
  "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAjpJRE" +
  "FUOMttkztoVFEQhr95nHPuRsFVg69CAiJBIoJgo2JjGbUL2NmJFmphIQElnWBhY2wUOxsL" +
  "wSa6SNpAChETewWxUAgWKSKbzXLvWKwboskPpzrzP2aGEbZg38TUAeAGcB8oACICgEBP1B" +
  "6KyPOVz69WhhzZQj4HvAPaIIgKqKIoqCBAENDEqqd06efHl4sAsm9iyoHTQAcYRRVTw1TB" +
  "FBWLgYBICETdAPFLzSeBJQcOAvNAW90RNUwdy4574t71y3L08H4WPn3h9fsPNNEQ/f5o0z" +
  "TzwEkFrgBt/romT6RSUUqLUo1wfOwwe9t7uHh2gtIaGbxdu0ilansqVxyYFRHUDPWM50Iq" +
  "FZ4z5okmNseE50wTEE2NWKLu9WYdNIkqZo6lRCoFrwqWCq62ZcxgnpEIIgxVQyKSi4C6Ye" +
  "54TngquGfMHFXdXONwpSYQYTQheM44Kqgq6o55Rt0H7aj+dRf+hSASqAqE4yoCogMRNW5d" +
  "Pc+pE2P87m4w/bRDRMN2CKIgoSjQVxFEFVGLY2NHEJTdrYpHtyfZs7sFwNdvP3ZIIn0V0T" +
  "uDmIO8dx+/Ya27Tr+uaVWZug7Wuuu8mFveIYjcUTWba4jViIagBuDek7f0Nvp01zdY664z" +
  "/bSzQxusisicHDpzzRE5nauRTm61RlNp4Sljpv+fy1b8AiaBpc3foxdunkulepdyaXsumP" +
  "ngoLYLrAKXll8/WAQY2vB94dkiwXhEzDR13avrmmgCiGFJD5gBxodkgD8dCqDsePGH4QAA" +
  "AABJRU5ErkJggg==";
var imgDisable = "data:image/png;base64," +
  "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAdJJRE" +
  "FUOMt1kzFv2lAUhb/73n2yJRgYUJEYWbKUoWt+QJESRYKRhbVb/kClbN1Rto4wgBiYomTI" +
  "xsLajZ+AlCoDo0Ns3wzNs9yUHsmS9Z7P987xtYWahsPhJ+Ab8B1IAJxzcftFRH4AP9fr9e" +
  "+4KDXzOXAPtAC89xW4fl8UxUFVL1er1RZAhsOhAl+AB6DtnENE8N4jIgD2DhARIc9zgGdV" +
  "vQB+KdABHoGW974yqiree0ajkXQ6HXa7HdvtFlXFzNpFUTwCnx1wBbScc5U5hEAIgTRN6X" +
  "a7NBoN+v1+tZamKSGElqpeKXDrnCNGT5KEEEKVoK4kSSiKAjPjvc6tAiF2VtW/ro+AWM3M" +
  "4nSCxugfAd77KlUdEOWc+/OsiFRkVSUC4/xr38E/IO89Wt/w3jMYDOj1emRZxnK5pCgKQg" +
  "gnIWaGA15jChGxbrcLQJqmjMdjms0mAPv9/hTk1YnIdS2mzGYzsiyjLEvSNCXPc7IsY7PZ" +
  "cELXznt/V5blAcDMAFgsFhyPR7Isq6qc0EFE7hR4MrOvZvYAtCPoP6aoZ+ACeKrmMplMzk" +
  "MI96raSpIkvpOTJwOX0+l0C1CVn8/nW+AMuMnz/MXMqkrxdwZugLNoBngDCfaXqH4PqZEA" +
  "AAAASUVORK5CYII=";
prefBranch.setBoolPref(pref, true);
this.tooltipText = strEnable;
this.image = imgEnable;
this.leftclick = function (event) {
  if (prefBranch.getBoolPref(pref) == false) {
    prefBranch.setBoolPref(pref, true);
    this.tooltipText = strEnable;
    this.image = imgEnable;
  } else {
    prefBranch.setBoolPref(pref, false);
    this.tooltipText = strDisable;
    this.image = imgDisable;
  }
};
this.setAttribute("onclick", "custombuttons.gQuot.mHandler(event, this)");
Restart FF, and click the new button/icon to toggle.
(?)
:roll:
morat
Posts: 6394
Joined: February 3rd, 2009, 6:29 pm

Re: Toggle A Boolean Pref

Post by morat »

You would need to convert the obsolete custom button using the RestartFirefoxButton_Movable.uc.js file as an example.

I don't have time to convert it right now.
AlbertG
Posts: 57
Joined: April 12th, 2006, 2:44 pm

Re: Toggle A Boolean Pref

Post by AlbertG »

Thanks again.

One more question, when you might have just a moment:

Since I'm running ESR and don't need to worry about sandboxing, would simply dropping viable javascript directly into \defaults\pref\autoconfig.js execute without issue?

( https://mike.kaply.com/2012/03/22/custo ... fig-files/ )

???
morat
Posts: 6394
Joined: February 3rd, 2009, 6:29 pm

Re: Toggle A Boolean Pref

Post by morat »

The <install directory>\defaults\pref\*.js files are preference files, like prefs.js and user.js files.

More info
http://kb.mozillazine.org/Prefs.js_file
http://kb.mozillazine.org/User.js_file

I don't think you can use the Components object in these files.
AlbertG
Posts: 57
Joined: April 12th, 2006, 2:44 pm

Re: Toggle A Boolean Pref

Post by AlbertG »

Thanks and Cheers --
:)
AlbertG
Posts: 57
Joined: April 12th, 2006, 2:44 pm

Re: Toggle A Boolean Pref

Post by AlbertG »

An update, for the record :)

I put together a quick, annoying, and edifying sample code context in accord with this:

File firefox/defaults/pref/autoconfig.js --

Code: Select all

pref("general.config.obscure_value", 0);
pref("general.config.filename", "execute.cfg");
File firefox/execute.cfg --

Code: Select all

//
(function () {
   prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
   prefs.setBoolPref("javascript.enabled", false);
})();
Restart.
Success -- pref "javascript.enabled" annoyingly toggled to "false" at each restart :wink:

Notes:
1) All *.js files in firefox/defaults/pref/ are executed at startup.
2) All *.js files in firefox/defaults/pref/ seem to be purpose-built to call "pref()" only, and don't seem to be able to execute .js code by themselves.
3) Ad-hoc named firefox/*.cfg files can be called from within firefox/defaults/pref/*.js via "pref("general.config.filename", "somename.cfg");".
4) All firefox/*.cfg files are, functionally, just pure .js files.
5) Any number of firefox/defaults/pref/*.js and their corresponding firefox/*.cfg files can be run at startup via this method.

>>The ESR releases don't seem to have an issue relating to sandboxing. morat addresses this situation with regard to standard releases in his code/postings here: http://forums.mozillazine.org/viewtopic ... &t=3056596

Nearly anything goes in these *.cfg files: You literally seem to have the helm. From https://mike.kaply.com/2012/03/22/custo ... fig-files/ :
Autoconfig files are Javascript files that have full access to all components of Firefox.
...
The best thing about autoconfig files is how easy they are to get into Firefox. No need for an add-on or anything like that. You just drop in two files and you’re done.
Awesome!
morat
Posts: 6394
Joined: February 3rd, 2009, 6:29 pm

Re: Toggle A Boolean Pref

Post by morat »

Here is a toggle javascript button.

* <profile directory>\chrome\ToggleJavaScriptFirefoxButton_Movable.uc.js

Code: Select all

(function () {
  if (location != "chrome://browser/content/browser.xul" &&
      location != "chrome://browser/content/browser.xhtml") return;

  /* CustomizableUI
     http://developer.mozilla.org/docs/Mozilla/JavaScript_code_modules/CustomizableUI.jsm
     http://developer.mozilla.org/docs/Mozilla/JavaScript_code_modules/CustomizableUI.jsm/API-provided_widgets
  */

  try {
    CustomizableUI.createWidget({
      id: "__unique_identifier_toggle_javascript_button", // should match id below
      type: "custom",
      defaultArea: CustomizableUI.AREA_MENUBAR,
   // defaultArea: CustomizableUI.AREA_NAVBAR,
      onBuild: function (aDocument) {
        var XUL_NS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
        var toolbaritem = aDocument.createElementNS(XUL_NS, "toolbarbutton");
        var prefBranch = Components.classes["@mozilla.org/preferences-service;1"].
          getService(Components.interfaces.nsIPrefBranch);
        var pref = "javascript.enabled";
        var strEnable = "[enable] JavaScript";
        var strDisable = "[disable] JavaScript";
        var imgEnable = "data:image/png;base64," +
          "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAjpJRE" +
          "FUOMttkztoVFEQhr95nHPuRsFVg69CAiJBIoJgo2JjGbUL2NmJFmphIQElnWBhY2wUOxsL" +
          "wSa6SNpAChETewWxUAgWKSKbzXLvWKwboskPpzrzP2aGEbZg38TUAeAGcB8oACICgEBP1B" +
          "6KyPOVz69WhhzZQj4HvAPaIIgKqKIoqCBAENDEqqd06efHl4sAsm9iyoHTQAcYRRVTw1TB" +
          "FBWLgYBICETdAPFLzSeBJQcOAvNAW90RNUwdy4574t71y3L08H4WPn3h9fsPNNEQ/f5o0z" +
          "TzwEkFrgBt/romT6RSUUqLUo1wfOwwe9t7uHh2gtIaGbxdu0ilansqVxyYFRHUDPWM50Iq" +
          "FZ4z5okmNseE50wTEE2NWKLu9WYdNIkqZo6lRCoFrwqWCq62ZcxgnpEIIgxVQyKSi4C6Ye" +
          "54TngquGfMHFXdXONwpSYQYTQheM44Kqgq6o55Rt0H7aj+dRf+hSASqAqE4yoCogMRNW5d" +
          "Pc+pE2P87m4w/bRDRMN2CKIgoSjQVxFEFVGLY2NHEJTdrYpHtyfZs7sFwNdvP3ZIIn0V0T" +
          "uDmIO8dx+/Ya27Tr+uaVWZug7Wuuu8mFveIYjcUTWba4jViIagBuDek7f0Nvp01zdY664z" +
          "/bSzQxusisicHDpzzRE5nauRTm61RlNp4Sljpv+fy1b8AiaBpc3foxdunkulepdyaXsumP" +
          "ngoLYLrAKXll8/WAQY2vB94dkiwXhEzDR13avrmmgCiGFJD5gBxodkgD8dCqDsePGH4QAA" +
          "AABJRU5ErkJggg==";
        var imgDisable = "data:image/png;base64," +
          "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAdJJRE" +
          "FUOMt1kzFv2lAUhb/73n2yJRgYUJEYWbKUoWt+QJESRYKRhbVb/kClbN1Rto4wgBiYomTI" +
          "xsLajZ+AlCoDo0Ns3wzNs9yUHsmS9Z7P987xtYWahsPhJ+Ab8B1IAJxzcftFRH4AP9fr9e" +
          "+4KDXzOXAPtAC89xW4fl8UxUFVL1er1RZAhsOhAl+AB6DtnENE8N4jIgD2DhARIc9zgGdV" +
          "vQB+KdABHoGW974yqiree0ajkXQ6HXa7HdvtFlXFzNpFUTwCnx1wBbScc5U5hEAIgTRN6X" +
          "a7NBoN+v1+tZamKSGElqpeKXDrnCNGT5KEEEKVoK4kSSiKAjPjvc6tAiF2VtW/ro+AWM3M" +
          "4nSCxugfAd77KlUdEOWc+/OsiFRkVSUC4/xr38E/IO89Wt/w3jMYDOj1emRZxnK5pCgKQg" +
          "gnIWaGA15jChGxbrcLQJqmjMdjms0mAPv9/hTk1YnIdS2mzGYzsiyjLEvSNCXPc7IsY7PZ" +
          "cELXznt/V5blAcDMAFgsFhyPR7Isq6qc0EFE7hR4MrOvZvYAtCPoP6aoZ+ACeKrmMplMzk" +
          "MI96raSpIkvpOTJwOX0+l0C1CVn8/nW+AMuMnz/MXMqkrxdwZugLNoBngDCfaXqH4PqZEA" +
          "AAAASUVORK5CYII=";
        prefBranch.setBoolPref(pref, true);
        toolbaritem.tooltipText = strEnable;
        toolbaritem.image = imgEnable;
        toolbaritem.onclick = function (aEvent) {
          if (aEvent.button == 0) {
            if (prefBranch.getBoolPref(pref) == false) {
              prefBranch.setBoolPref(pref, true);
              this.tooltipText = strEnable;
              this.image = imgEnable;
            } else {
              prefBranch.setBoolPref(pref, false);
              this.tooltipText = strDisable;
              this.image = imgDisable;
            }
          }
        };
        var props = {
          id: "__unique_identifier_toggle_javascript_button",
          class: "toolbarbutton-1 chromeclass-toolbar-additional",
          label: "Toggle JavaScript",
        };
        for (var p in props) toolbaritem.setAttribute(p, props[p]);
        return toolbaritem;
      },
    });
  } catch (e) {
    Components.utils.reportError(e); // [check] Show Content Messages
  };
})();
AlbertG
Posts: 57
Joined: April 12th, 2006, 2:44 pm

Re: Toggle A Boolean Pref

Post by AlbertG »

Thanks again, morat! That is a considerable help...

Hoping not to be a pest, but can we call on any additional basic functions in these scripts beyond what is listed here:

https://support.mozilla.org/en-US/kb/cu ... autoconfig

For example, if we'd like to use another function/feature which falls outside the scope of that list, could one import those resources to prevent reference errors? If so, what would the general syntax look like???

Thanks again; and have a great day :)
morat
Posts: 6394
Joined: February 3rd, 2009, 6:29 pm

Re: Toggle A Boolean Pref

Post by morat »

I got a "ChromeUtils is not defined" error when trying to create a command line handler using the mozilla.cfg file.

I had to import the ChromeUtils object.

Access addons via cmdline
http://forums.mozillazine.org/viewtopic ... &t=3060782

Import various objects
http://developer.mozilla.org/docs/Mozil ... ils.import
http://developer.mozilla.org/docs/Mozil ... Properties
AlbertG
Posts: 57
Joined: April 12th, 2006, 2:44 pm

Re: Toggle A Boolean Pref

Post by AlbertG »

Thanks again, morat! You've been a real help :)

For anyone who might tread this path at some point henceforth, here are a couple more refs which also seem to be of value in these general endeavors:

https://developer.mozilla.org/en-US/doc ... de_modules
https://developer.mozilla.org/en-US/doc ... ules/Using

And, perhaps for something else in this present code context:

https://developer.mozilla.org/en-US/doc ... ableUI.jsm

8-)

Cheers!
Post Reply