Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[JavaScript] General JavaScript talk and custom userChrome.js scripts - unrelated to CustomCSSforFx #135

Closed
Aris-t2 opened this issue Jul 19, 2018 · 77 comments

Comments

@Aris-t2
Copy link
Owner

Aris-t2 commented Jul 19, 2018

Lets discuss everything related to JavaScript here instead of opening new threads for questions or requests regarding custom js scripts.

Ways to implement custom JavaScripts through userChrome.js
see method 1 and 2 from Scrollbars repository

Custom Scrollbars
Restart button
Restart menuitems
Custom Downloads button
Bookmarks backup/restore buttons
Password Manager button
'Bookmarks' and 'History' sidebar buttons

Custom script collections
- by ardiman
- by Endor8

Note
Scripts will not be integrated into CustomCSSforFx!

@garywill
Copy link

garywill commented Aug 4, 2018

Hi Aris
Could you please tell me how to prevent tab context menu?
I have this code to close tab by right clicking. It works but context menu appears, which I want to prevent

gBrowser.tabContainer.addEventListener('click', function(event) {
    if (event.button != 2) return;
    if (event.target.localName == 'tab' && event.button == 2) {
        event.preventDefault();
        event.stopPropagation();
        gBrowser.removeTab(event.target, {animate: true});
    }
}); 

Much thanks

@garywill
Copy link

garywill commented Aug 4, 2018

I figured it out

gBrowser.tabContainer.addEventListener('contextmenu', function(event) {
    event.preventDefault();
    event.stopPropagation();
    
}); 

@Aris-t2
Copy link
Owner Author

Aris-t2 commented Aug 4, 2018

There also exists a "removeEventListener" script to remove listeners, but your code work too.
It is possible to hide tab context menu entirely, if needed:

#tabContextMenu {
  display: none !important;
} 

@Acid-Crash
Copy link

Hi @Aris-t2,
I am really new to a userChrome.js
Before FF57 I've used an extension to open Password manager in a pop-up.
As far as I know, Web-Extensions don't have access to chrome:// pages
So I wonder is it possible to create a new toolbar button for navbar that opens
chrome://passwordmgr/content/passwordManager.xul ?
Preferably in a pop-up window that has minimum control buttons (the one that only has app button and location bar)
popup
If it isn't possible, a regular tab will do...

@Aris-t2
Copy link
Owner Author

Aris-t2 commented Aug 10, 2018

pw_manager_button

It is possible. I just wrote this script:

// 'Open Password Manager' button for Firefox 60+ by Aris

(function() {

try {
  Components.utils.import("resource:///modules/CustomizableUI.jsm");
  var {Services} = Components.utils.import("resource://gre/modules/Services.jsm", {});
  var sss = Components.classes["@mozilla.org/content/style-sheet-service;1"].getService(Components.interfaces.nsIStyleSheetService);
  
  CustomizableUI.createWidget({
	id: "pw_manager_button", // button id
	defaultArea: CustomizableUI.AREA_NAVBAR,
	removable: true,
	label: "Open Password Manager", // button title
	tooltiptext: "Open Password Manager", // tooltip title
	onClick: function(event) {
			
	  if(event.button=='0') {
		window.open('chrome://passwordmgr/content/passwordManager.xul','', 'chrome');
	  }
	  
	},
	onCreated: function(button) {
	  return button;
	}
		
  });
  
  // style button icon
  var uri = Services.io.newURI("data:text/css;charset=utf-8," + encodeURIComponent('\
	\
	  #pw_manager_button .toolbarbutton-icon {\
		list-style-image: url("chrome://browser/skin/connection-secure.svg"); /* icon / path to icon */ \
		fill: red; /* icon color name/code */\
	  }\
	\
  '), null, null);
  
  sss.loadAndRegisterSheet(uri, sss.AGENT_SHEET);
  
} catch (e) {
	Components.utils.reportError(e);
};

})();

v2 - middle click on button will fill current (non-chrome) domain/host into input field

// 'Open Password Manager' button for Firefox 60+ by Aris

(function() {

try {
  Components.utils.import("resource:///modules/CustomizableUI.jsm");
  Components.utils.import("resource://gre/modules/LoginHelper.jsm");
  var {Services} = Components.utils.import("resource://gre/modules/Services.jsm", {});
  var sss = Components.classes["@mozilla.org/content/style-sheet-service;1"].getService(Components.interfaces.nsIStyleSheetService);
  
  CustomizableUI.createWidget({
	id: "pw_manager_button", // button id
	defaultArea: CustomizableUI.AREA_NAVBAR,
	removable: true,
	label: "Open Password Manager", // button title
	tooltiptext: "Open Password Manager", // tooltip title
	onClick: function(event) {
			
	  if(event.button=='0') {
		try {
		  window.open('chrome://passwordmgr/content/passwordManager.xul','', 'chrome');
		} catch (e) {}
	  } else if(event.button=='1') {
		try {
		  LoginHelper.openPasswordManager(window, gBrowser.currentURI.host);
		} catch (e) {}
	  }
	  
	},
	onCreated: function(button) {
	  return button;
	}
		
  });
  
  // style button icon
  var uri = Services.io.newURI("data:text/css;charset=utf-8," + encodeURIComponent('\
	\
	  #pw_manager_button .toolbarbutton-icon {\
		list-style-image: url("chrome://browser/skin/connection-secure.svg"); /* icon / path to icon */ \
		fill: red; /* icon color name/code */\
	  }\
	\
  '), null, null);
  
  sss.loadAndRegisterSheet(uri, sss.AGENT_SHEET);
  
} catch (e) {
	Components.utils.reportError(e);
};

})();

@Acid-Crash
Copy link

Acid-Crash commented Aug 10, 2018

Hmm, struggling here.
Right now I use so called method2 (for RestartApp menu button).
https://github.com/Aris-t2/Scrollbars/tree/master/method 2/profile

To my understanding I need to create a new file in profile/userChrome/ (for example custom_PwMgr.uc.js)
Copy-paste your code in it and then add to userChrome.js
userChrome.import("/userChrome/custom_PwMgr.uc.js", "UChrm");

However It looks like I'm missing something, because the new button didn't show up.
Also the structure of actual code is a bit different...

UPD: managed to make it working with this inside custom_PwMgr.uc.js:
Is it the optimal way?

Code
// 'Open Password Manager' button for Firefox 60+ by Aris

var {Services} = Components.utils.import("resource://gre/modules/Services.jsm", {});

var PwdmgrItems = {
  init: function() {

try {
  Components.utils.import("resource:///modules/CustomizableUI.jsm");
  var {Services} = Components.utils.import("resource://gre/modules/Services.jsm", {});
  var sss = Components.classes["@mozilla.org/content/style-sheet-service;1"].getService(Components.interfaces.nsIStyleSheetService);
  
  CustomizableUI.createWidget({
  id: "pw_manager_button", // button id
  defaultArea: CustomizableUI.AREA_NAVBAR,
  removable: true,
  label: "Open Password Manager", // button title
  tooltiptext: "Open Password Manager", // tooltip title
  onClick: function(event) {
      
    if(event.button=='0') {
    window.open('chrome://passwordmgr/content/passwordManager.xul','', 'chrome');
    }
    
  },
  onCreated: function(button) {
    return button;
  }
    
  });
  
  // style button icon
  var uri = Services.io.newURI("data:text/css;charset=utf-8," + encodeURIComponent('\
  \
    #pw_manager_button .toolbarbutton-icon {\
    list-style-image: url("chrome://browser/skin/connection-secure.svg"); /* icon / path to icon */ \
    fill: red; /* icon color name/code */\
    }\
  \
  '), null, null);
  
  sss.loadAndRegisterSheet(uri, sss.AGENT_SHEET);
  
} catch (e) {
  Components.utils.reportError(e);
};

}
}

PwdmgrItems.init();

@Acid-Crash
Copy link

Acid-Crash commented Aug 10, 2018

UPD2. Just noticed that if I open context menu on a password/login field, and then open password manager it "remembers" URL of the page.
Maybe you can mimic this as well?

Screen

pwd

@Aris-t2
Copy link
Owner Author

Aris-t2 commented Aug 10, 2018

@Acid-Crash

UPD: managed to make it working with this inside custom_PwMgr.uc.js:
Is it the optimal way?

Yes, this was the correct way of adding custom users cripts to userChrome.js.

I have added a second script to the above post, where a middle-click on the button will "remember" current urls host/domain and add it to search field automatically similar to what context menu entry "View saved logins" does. You can adopt the script to only allow this for left-click too, if you want.

pw

@Acid-Crash
Copy link

@Aris-t2 Simply superb! Thank you so much. You are the CSS/JS hero! Yet again!

@Pizzapops
Copy link

@Aris-t2 This is working for me too. (java-script method 2) Thanks!

I have been trying to get your Bookmarks backup/restore buttons to work but the buttons do not appear. I have tried on both FxQ62 and Nightly. I even tried with a new profile containing Chrome folder with only JS files.
2018-08-11_160231

I also tried without vert_addonbar_left.uc.js in case there was a conflict. No luck.

@Aris-t2
Copy link
Owner Author

Aris-t2 commented Aug 12, 2018

@Pizzapops
Not sure what to say, Sounds like an issue with either missing or wrong files inside Firefox folder.

Here is a preconfigured Portable Firefox setup with "method 2" active and Fx62beta in use. Alternatively rename App/firefox to something and rename App/firefox60esr to App/firefox to test Fx60esr.
https://www.dropbox.com/s/l8ygfn9nqmfixmr/FirefoxPortable_JS_method2.7z?dl=1

@Acid-Crash
Copy link

Hi @Aris-t2,
Quick question regarding new buttons via JS. Maybe you know how to define separate locale variants for label and tooltiptext?

@Aris-t2
Copy link
Owner Author

Aris-t2 commented Aug 12, 2018

You can achieve this by finding localized nodes inside the ui. Use developer tools to find navigation toolbars localized "aria-label" node and replace the variable for that case. Its a shame Mozilla removed the preference "general.useragent.locale". It would be easier to handle location variable that way.

Example based on 'restart item' script
// Restart item script for Firefox 60+ by Aris
//
// left-click on restart item: normal restart
// middle-click on restart item: restart + clear caches
// right-click on restart item: no special function
//
// based on 'addRestartButton.uc.js' script by Alice0775
// restart code from Classic Theme Restorer add-on
// invalidate caches from Session Saver add-on

var {Services} = Components.utils.import("resource://gre/modules/Services.jsm", {});

var RestartMenuFileAppItems = {
  init: function() {

	var button_label = "Restart";
	
	try {
	  switch (document.getElementById("nav-bar").getAttribute("aria-label")) {
		case "Navigations-Symbolleiste": button_label = "Neustarten"; break;
		case "Панель навигации": button_label = "Перезапустить"; break;
	  }
	} catch(e) {}

	try {
	  restartitem_filemenu = document.createElement("menuitem");
	  restartitem_filemenu.setAttribute("label", button_label);
	  restartitem_filemenu.setAttribute("id","fileMenu-restart-item");
	  restartitem_filemenu.setAttribute("key", "R");
	  restartitem_filemenu.setAttribute("insertbefore", "menu_FileQuitItem");
	  restartitem_filemenu.setAttribute("onclick", "if (event.button == 0) {RestartMenuFileAppItems.restartApp(false);} else if (event.button == 1) {RestartMenuFileAppItems.restartApp(true)};");
	  restartitem_filemenu.setAttribute("oncommand", "RestartMenuFileAppItems.restartApp(false);");

	  if(document.getElementById("menu_FileQuitItem").previousSibling.id != "fileMenu-restart-item" )
		document.getElementById("menu_FileQuitItem").parentNode.insertBefore(restartitem_filemenu,document.getElementById("menu_FileQuitItem"));
	} catch(e) {}

	try {
	  restartitem_appmenu = document.createElement("toolbarbutton");
	  restartitem_appmenu.setAttribute("label", button_label);
	  restartitem_appmenu.setAttribute("id","appMenu-restart-button");
	  restartitem_appmenu.setAttribute("class","subviewbutton subviewbutton-iconic");
	  restartitem_appmenu.setAttribute("key", "R");
	  restartitem_appmenu.setAttribute("insertbefore", "appMenu-quit-button");
	  restartitem_appmenu.setAttribute("onclick", "if (event.button == 0) {RestartMenuFileAppItems.restartApp(false);} else if (event.button == 1) {RestartMenuFileAppItems.restartApp(true)};");
	  restartitem_appmenu.setAttribute("oncommand", "RestartMenuFileAppItems.restartApp(false);");

	  if(document.getElementById("appMenu-quit-button").previousSibling.id != "appMenu-restart-button" )
		document.getElementById("appMenu-quit-button").parentNode.insertBefore(restartitem_appmenu,document.getElementById("appMenu-quit-button"));
	} catch(e) {}

	var sss = Components.classes["@mozilla.org/content/style-sheet-service;1"].getService(Components.interfaces.nsIStyleSheetService);

	// style button icon
	var uri = Services.io.newURI("data:text/css;charset=utf-8," + encodeURIComponent('\
	  \
	  #appMenu-restart-button {\
		list-style-image: url("chrome://browser/skin/reload.svg"); /* icon / path to icon */ \
	  }\
	  #appMenu-restart-button .toolbarbutton-icon {\
		transform: scaleX(-1); /* icon mirroring */\
		color: red; /* icon color name/code */\
	  }\
	  \
	'), null, null);

	sss.loadAndRegisterSheet(uri, sss.AGENT_SHEET);
	
  },

  restartApp: function(clearcaches) {

	var cancelQuit = Components.classes["@mozilla.org/supports-PRBool;1"].createInstance(Components.interfaces.nsISupportsPRBool);
	var observerSvc = Components.classes["@mozilla.org/observer-service;1"].getService(Components.interfaces.nsIObserverService);

	if(clearcaches) {
	  Components.classes["@mozilla.org/xre/app-info;1"].getService(Components.interfaces.nsIXULRuntime).invalidateCachesOnRestart();
	}

	observerSvc.notifyObservers(cancelQuit, "quit-application-requested", "restart");

	if(cancelQuit.data) return false;

	Services.startup.quit(Services.startup.eRestart | Services.startup.eAttemptQuit);

  }

}

RestartMenuFileAppItems.init();

@Acid-Crash
Copy link

Thx, I get the main idea.
Could you please share additional example of any toolbar button (Restart button or Password Manager).
Can't figure out where to place that lang-check if the button has both label and tooltiptext that are defined inside CustomizableUI.createWidget ?

@Aris-t2
Copy link
Owner Author

Aris-t2 commented Aug 12, 2018

Example based on 'restart button' script
// Restart button script for Firefox 60+ by Aris
//
// left-click on restart button: normal restart
// middle-click on restart button: restart + clear caches
// right-click on restart button: no special function
//
// based on 'Quit' button code by 2002Andreas
// restart code from Classic Theme Restorer add-on
// invalidate caches from Session Saver add-on

(function() {

try {
  Components.utils.import("resource:///modules/CustomizableUI.jsm");
  var {Services} = Components.utils.import("resource://gre/modules/Services.jsm", {});
  var sss = Components.classes["@mozilla.org/content/style-sheet-service;1"].getService(Components.interfaces.nsIStyleSheetService);
  
  var button_label = "Restart";
	
	try {
	  switch (document.getElementById("nav-bar").getAttribute("aria-label")) {
		case "Navigations-Symbolleiste": button_label = "Neustarten"; break;
		case "Панель навигации": button_label = "Перезапустить"; break;
	  }
	} catch(e) {}
  
  CustomizableUI.createWidget({
	id: "uc-restart", // button id
	defaultArea: CustomizableUI.AREA_NAVBAR,
	removable: true,
	label: button_label, // button title
	tooltiptext: button_label, // tooltip title
	onClick: function(event) {
	  
	  var cancelQuit   = Components.classes["@mozilla.org/supports-PRBool;1"].createInstance(Components.interfaces.nsISupportsPRBool);
	  var observerSvc  = Components.classes["@mozilla.org/observer-service;1"].getService(Components.interfaces.nsIObserverService);
			
	  if(event.button=='1') { // middle-click - clear caches
		Components.classes["@mozilla.org/xre/app-info;1"].getService(Components.interfaces.nsIXULRuntime).invalidateCachesOnRestart();
	  }
	  
	  if(event.button=='0' || event.button=='1') { // left/middle-click - restart
		observerSvc.notifyObservers(cancelQuit, "quit-application-requested", "restart");
			
		if(cancelQuit.data) return false;
				
		Services.startup.quit(Services.startup.eRestart | Services.startup.eAttemptQuit);
	  }
	},
	onCreated: function(button) {
	  return button;
	}
		
  });
  
  // style button icon
  var uri = Services.io.newURI("data:text/css;charset=utf-8," + encodeURIComponent('\
	\
	  #uc-restart .toolbarbutton-icon {\
		list-style-image: url("chrome://browser/skin/reload.svg"); /* icon / path to icon */ \
		transform: scaleX(-1); /* icon mirroring */\
		fill: red; /* icon color name/code */\
	  }\
	\
  '), null, null);
  
  sss.loadAndRegisterSheet(uri, sss.AGENT_SHEET);
  
} catch (e) {
	Components.utils.reportError(e);
};

})();

@Pizzapops
Copy link

Your Dropbox beta helped me get my Beta and Nightly versions working. I had to update app files and use backup profiles. Switching the Beta to 64 bit caused a repeat of the problem and a redo. I do miss FEBE.

Note: Beware of mortalis13/Bookmarks-Sidebar-Button. It is a Legacy addon that claims to be compatible with Nightly. After a restart, it killed java-script and required use of a backup profile to fix.

@Pizzapops
Copy link

I made buttons for bookmarks sidebar & history sidebar (1 click) based on Aris's restart button with some code from mortalis13. If there is any interest, I will post them. These along with thkquang's left sidebar gets me closer to the look of AiOS/OmniSidebar. Still waiting for an extensions sidebar add-on.

@Acid-Crash
Copy link

Hi here.
Another idea that might come useful.
In Chrome when you right click on the Reload button while devTools are open additional Reload options are presented via context menu (Regular reload, Hard reload, Clear HTTP cache and hard reload).
It would be interning if something similar can be done here (context menu with options for reload button, devtools request isn't that needed).
I am pretty sure that mentioned separate reload options are present within browser (Ctrl+R)... HTTP cache in network tab of devtools

@Aris-t2
Copy link
Owner Author

Aris-t2 commented Aug 14, 2018

@Pizzapops
Sure, post them. That is what this thread is for.

@Acid-Crash
So far I've only seen these to inside browser.xul/.js: BrowserReloadSkipCache(); and BrowserReload();
You could test these commands within buttons onClick function.

Wouldn't 'BrowserReloadSkipCache' equal 'disable http cache' in this case? Not sure what 'hard reload' would do differently than skipping/disabling cache before reloading?

@Pizzapops
Copy link

Pizzapops commented Aug 14, 2018

Buttons for Bookmarks & History Sidebars

// "One Click" Bookmark Sidebar button script for Firefox 60+ 
// 
// based on 'Quit' button code by 2002Andreas
// and 'Restart' script for Firefox 60+ by Aris-t2
// modified by Pizzapops with code from mortalis13

(function() {

try {
  Components.utils.import("resource:///modules/CustomizableUI.jsm");
  var {Services} = Components.utils.import("resource://gre/modules/Services.jsm", {});
  var sss = Components.classes["@mozilla.org/content/style-sheet-service;1"].getService(Components.interfaces.nsIStyleSheetService);
  
  CustomizableUI.createWidget({
	id: "bookmarks-sidebar-button", // button id
	defaultArea: CustomizableUI.AREA_NAVBAR,
	removable: true,
	label: "Bookmarks Sidebar", // button title
	tooltiptext: "Bookmarks Sidebar", // tooltip title
onCommand : function(aEvent) {
       var aWindow = aEvent.target.ownerDocument.defaultView; // edited as mentioned by author
       aWindow.SidebarUI.toggle('viewBookmarksSidebar');
    },
    
    onCreated: function(aNode){
      aNode.setAttribute('type', 'checkbox')
      aNode.setAttribute('group', 'sidebar')
      aNode.setAttribute('observes', 'viewBookmarksSidebar')
      // aNode.setAttribute('observes', 'viewHistorySidebar')
    
	},
  });
  
  // style button icon
  var uri = Services.io.newURI("data:text/css;charset=utf-8," + encodeURIComponent('\
	\
	  #bookmarks-sidebar-button .toolbarbutton-icon {\
		list-style-image: url("chrome://browser/skin/bookmark-star-on-tray.svg"); /* icon / path to icon */ \
		transform: scaleX(-1); /* icon mirroring */\
		fill: black; /* icon color name/code */\
	  }\
	\
  '), null, null);
  
  sss.loadAndRegisterSheet(uri, sss.AGENT_SHEET);
  
} catch (e) {
	Components.utils.reportError(e);
};

})();
// "One Click" History Sidebar button script for Firefox 60+ 
// 
// based on 'Quit' button code by 2002Andreas
// and 'Restart' script for Firefox 60+ by Aris-t2
// modified by Pizzapops with code from mortalis13

(function() {

try {
  Components.utils.import("resource:///modules/CustomizableUI.jsm");
  var {Services} = Components.utils.import("resource://gre/modules/Services.jsm", {});
  var sss = Components.classes["@mozilla.org/content/style-sheet-service;1"].getService(Components.interfaces.nsIStyleSheetService);
  
  CustomizableUI.createWidget({
	id: "history-sidebar-button", // button id
	defaultArea: CustomizableUI.AREA_NAVBAR,
	removable: true,
	label: "History Sidebar", // button title
	tooltiptext: "History Sidebar", // tooltip title
onCommand : function(aEvent) {
      // var aWindow = aEvent.target.ownerDocument.defaultView;
      // aWindow.SidebarUI.toggle('viewBookmarksSidebar');
    },
    
    onCreated: function(aNode){
      aNode.setAttribute('type', 'checkbox')
      aNode.setAttribute('group', 'sidebar')
      aNode.setAttribute('observes', 'viewHistorySidebar')
    
	},
  });
  
  // style button icon
  var uri = Services.io.newURI("data:text/css;charset=utf-8," + encodeURIComponent('\
	\
	#history-sidebar-button .toolbarbutton-icon {\
		list-style-image: url("chrome://browser/skin/history.svg"); /* icon / path to icon */ \
		transform: scaleX(-1); /* icon mirroring */\
		fill: black; /* icon color name/code */\
	  }\
	\
  '), null, null);
  
  sss.loadAndRegisterSheet(uri, sss.AGENT_SHEET);
  
} catch (e) {
	Components.utils.reportError(e);
};

})();

@rayman89
Copy link

Is it possible to make a button to directly show the full download library?

image

@Aris-t2
Copy link
Owner Author

Aris-t2 commented Aug 16, 2018

Yes, it is possible.

// Downloads button script for Firefox 60+ by Aris
//
// left-click on custom downloads button: opens downloads library
// middle-click on custom downloads button: opens 'about:downloads' in a new tab
// right-click on custom downloads button: no special function

(function() {

try {
  Components.utils.import("resource:///modules/CustomizableUI.jsm");
  var {Services} = Components.utils.import("resource://gre/modules/Services.jsm", {});
  var sss = Components.classes["@mozilla.org/content/style-sheet-service;1"].getService(Components.interfaces.nsIStyleSheetService);
  
  var button_label = "Downloads";

  CustomizableUI.createWidget({
	id: "custom-downloads-button", // button id
	defaultArea: CustomizableUI.AREA_NAVBAR,
	removable: true,
	label: button_label, // button title
	tooltiptext: button_label, // tooltip title
	onClick: function(event) {
	  if(event.button=='0') {
		try {
		  //DownloadsPanel.showDownloadsHistory();
		  BrowserDownloadsUI(); // equals the above call
		} catch (e) {}
	  } else if(event.button=='1') {
		try {
		  var mainWindow = Components.classes["@mozilla.org/appshell/window-mediator;1"]
							.getService(Components.interfaces.nsIWindowMediator)
							.getMostRecentWindow("navigator:browser");
		  mainWindow.gBrowser.selectedTab = gBrowser.addTab('about:downloads', {triggeringPrincipal: Services.scriptSecurityManager.getSystemPrincipal()});
		} catch (e) {}
	  }

	},
	onCreated: function(button) {
	  return button;
	}
		
  });
  
  // style button icon
  var uri = Services.io.newURI("data:text/css;charset=utf-8," + encodeURIComponent('\
	\
	  #custom-downloads-button .toolbarbutton-icon {\
		list-style-image: url("chrome://browser/skin/back.svg"); /* icon / path to icon */ \
		transform: rotate(-90deg); /* icon mirroring */\
		fill: blue; /* icon color name/code */\
	  }\
	\
  '), null, null);
  
  sss.loadAndRegisterSheet(uri, sss.AGENT_SHEET);
  
} catch (e) {
	Components.utils.reportError(e);
};

})();

@Pizzapops
Copy link

Pizzapops commented Aug 18, 2018

Current Nightly update broke Downloads Button for me.
Disregard! After two more restarts it is working.

@Aris-t2
Copy link
Owner Author

Aris-t2 commented Aug 18, 2018

Edit: Updated the above code.

For some nonsense reason the addTab call now requires additional parameters. I used the ones from "their example" from Bugzilla.

This however only affected the middle-click feature, the left-click still works for me. Make sure to clean "startupCache" manually at least once, if the button still wont work even, if userChrome.ignoreCache is set to true.

Most likely all scripts will break soon in Fx63. Just look at the error console. Many errors are present for almost every script.

@Pizzapops
Copy link

Scripts in Beta 62.0b18-64 are not working at all. The profile works fine in 60esr. Maybe they will be back in b19.

@Speravir
Copy link

Scripts in Beta 62.0b18-64 are not working at all. The profile works fine in 60esr. Maybe they will be back in b19.

The userChromeJS method is potentially harmful. It works with autoconfig, so developers decided to sandbox this for beta and release versions starting with this beta: Bug 1455601 - Sandbox AutoConfig to its standard API in Firefox 62. For some versions one will be able to set a preference to disable sandboxing. We have to add this to config-prefs.js:
pref("general.config.sandbox_enabled", false);

Aris changed this already in his Custom Scrollbars repository, deep link: Scrollbars/config-prefs.js at master · Aris-t2/Scrollbars.

From what I read this switch is intended to completely be disabled for betas and releases sometime in the future without a chance resetting it, so everyone who wants to use these enhanced config possibilities will then be forced to use nightly, developer or unbranded builds (I also read about ESR, but I guess this will change with next big ESR version after v. 60esr).

@Speravir
Copy link

Speravir commented Aug 20, 2018

@Acid-Crash @Pizzapops
A simpler userChrome.js:

// Deactivate script cache
userChrome.ignoreCache = true;

// Time delay for loading of XUL overlays (in ms)
userChrome.loadOverlayDelay = 1000;

// Import all JS & XUL files from chrome subfolder
userChrome.import("*", "UChrm");

The most important line is the last one: So you do not have to add every single script, but every file with JS extension in the chrome folder will be loaded. Also XUL files will work as long as XUL will be supported, for loading of these there has to be set a time delay which has to be adjusted individually (for older versions before v. 57 some users needed up to 10 seconds if I remember correctly).

@Speravir
Copy link

Speravir commented Aug 20, 2018

@Aris-t2 Please fix the link to the Password Manager button in your first message above. Also perhaps link to ardiman/userChrome.js. This is the original (“official”) repository for scripts from camp-firefox.de. Ardiman (Mithrandir in Camp Firefox) is now barely active and Endor does the job, but from time to time Endor pushes or commits new scripts and script versions (I do not know exactly how) to ardiman.

Note that these scripts

  • are in most cases translated into German, sometimes you can see the Asian origin though. *)
  • may not anymore be functional.
  • may sometimes not be needed anymore, because the feature is available by default now (or by an addon).

*) Repositories I know, but Endor should do know better – partly not updated for years:

Side question: How did you manage the code folding in 2 comments above?

@Speravir
Copy link

Speravir commented Sep 6, 2018

The issues seem to be related to the script cache. Either delete the startup cache or disable the script cache.

The startup cache is for Windows users in C:\Users\<username>\AppData\Local\Mozilla\Firefox\Profiles\<profil_name>\startupCache\ , for the other OSes you have to search for the analog.
For disabling the script cache see my comment from 20th August. Actually, with modern computers you barely will notice a delay.

@TroudhuK
Copy link

TroudhuK commented Sep 6, 2018

The entry to disable the script cache is in userChromeJS package for a long time so I have it...
I deleted all the startupCache folder, the scriptCache* files are recreated. Not better.

userChromeJS doesn't work only in the first window.

@Aris-t2
Copy link
Owner Author

Aris-t2 commented Sep 7, 2018

If nothing helps, I suggest to install "Portable Firefox" in a new folder and setup userChromeJS and own scripts only. Maybe this will help to find some logic in all this.

@Acid-Crash
Copy link

Hi @Aris-t2 Calling to your wisdom and knowledge))
Could you please take a look at Screenshot extension functionality?
It would be good to have a toolbar button of ScreenshotTool?
LeftClick > Launch extension;
RightClick > screenshot of Visible page

@Aris-t2
Copy link
Owner Author

Aris-t2 commented Sep 9, 2018

Doesn't look like "Screenshot" extensions menuitem or location bar button offer any "command" to "steal" from (left-click). Not sure how WebExtensions work here, but page listeners do not seem to be accessible from DOM (toolbar), only from the page after "Screenshot" extension is loaded (right-click).

@Pizzapops
Copy link

[Win10_1803][FxQ_64portable][JS method 2]

Until the JavaScript problem is solved, I am using a bat file to start/fix FxQ portable. Sometimes it requires two new starts.

cd D:\
del D:\FxQ64dev\Data\profile\startupCache\scriptCache*.*
del D:\FxQ64dev\Data\profile\startupCache\startupCache*.*
D:\FxQ64dev\FirefoxPortable.exe

Restarts have a cache problem, both @Aris-t2's and the about:profiles restart. (my default profile is D:\FxQ64dev\Data\profile) @Aris-t2 Restart is displayed but the only thing clickable on the screen is the close X. I find it curious that after a daily update restart, there isn't always a problem.

@Aris-t2
Copy link
Owner Author

Aris-t2 commented Sep 10, 2018

Use middle-click to restart, if you are using my restart v2 scripts. It works for me to invalidate/clear caches on restart.

@rayman89
Copy link

rayman89 commented Sep 11, 2018

Is it possible to use this to add a new context menu item to open a new tab?

I know there are 2 addons that do this (new tab context and new tab beside) but on firefox 63 those addons don't get focus on the url bar like you normally have when opening a new tab so you have to click on the url bar to start typing. I tried contacting them to see if that's fixable but they dont have any mail or github associated.

@Pizzapops
Copy link

@Aris-t2
I deleted all method 2 JS files and Restart files and then reinstalled current updates. Everything is working again. Thanks.

@Aris-t2
Copy link
Owner Author

Aris-t2 commented Sep 11, 2018

@rayman89
Maybe there it a small glitch in new tab functionality of add-ons.

Both "new tab" add-ons focus location bar for me starting with 2. or 3. tab.

@Pizzapops
Good to hear.

@rayman89
Copy link

So js cant be used to add the functionality to open a new tab from context menu?

@Aris-t2
Copy link
Owner Author

Aris-t2 commented Sep 12, 2018

I did not say that. ;-) Just wondering, if this is a Firefox bug or add-on bug.

This script works for me on Fx60&64, so I assume it will work on Fx61-63 too.

// New Tab script for Firefox 60+ by Aris
// Adds 'New Tab' item to tab context menu

var {Services} = Components.utils.import("resource://gre/modules/Services.jsm", {});

var NewTabMenuItem = {
  init: function() {

	var item_label = "New Tab";

	try {
	  addtab_item = document.createElement("menuitem");
	  addtab_item.setAttribute("label", item_label);
	  addtab_item.setAttribute("id","newtab-menuitem");
	  addtab_item.setAttribute("key", "T");
	  addtab_item.setAttribute("oncommand", "NewTabMenuItem.newTab();");
	  document.getElementById("tabContextMenu").appendChild(addtab_item);
	} catch(e) {}

  },

  newTab: function() {
	  
	// adds a new tab
	// replace 'about:newtab' with a custom url, if needed
	try {
	  var mainWindow = Components.classes["@mozilla.org/appshell/window-mediator;1"]
						.getService(Components.interfaces.nsIWindowMediator)
						.getMostRecentWindow("navigator:browser");
	  mainWindow.gBrowser.selectedTab = gBrowser.addTab('about:newtab', {triggeringPrincipal: Services.scriptSecurityManager.getSystemPrincipal()});
	} catch (e) {}
	
	/* focuses location bar */
	try {
	  document.getElementById('urlbar').focus();
	  document.getElementById('urlbar').select();
	} catch (e) {}

  }

}

NewTabMenuItem.init();

Edit: Minor fixes.

Edit: v2 with icon and menuseparator.

// New Tab script for Firefox 60+ by Aris
// Adds 'New Tab' item to tab context menu

var {Services} = Components.utils.import("resource://gre/modules/Services.jsm", {});

var NewTabMenuItem = {
  init: function() {

	var item_label = "New Tab";

	try {
	  addtab_sep = document.createElement("menuseparator");
	  addtab_sep.setAttribute("id","newtab-menuitem_sep");
	  document.getElementById("tabContextMenu").appendChild(addtab_sep);
	} catch(e) {}

	try {
	  addtab_item = document.createElement("menuitem");
	  addtab_item.setAttribute("label", item_label);
	  addtab_item.setAttribute("id","newtab-menuitem");
	  addtab_item.setAttribute("class","menuitem-iconic");
	  addtab_item.setAttribute("key", "T");
	  addtab_item.setAttribute("oncommand", "NewTabMenuItem.newTab();");
	  document.getElementById("tabContextMenu").appendChild(addtab_item);
	} catch(e) {}
	
	var sss = Components.classes["@mozilla.org/content/style-sheet-service;1"].getService(Components.interfaces.nsIStyleSheetService);

	// style button icon
	var uri = Services.io.newURI("data:text/css;charset=utf-8," + encodeURIComponent('\
	  \
	  #newtab-menuitem .menu-iconic-icon {\
		list-style-image: url("chrome://browser/skin/new-tab.svg"); /* icon / path to icon */ \
	  }\
	  \
	'), null, null);

	sss.loadAndRegisterSheet(uri, sss.AGENT_SHEET);

  },

  newTab: function() {
	  
	// adds a new tab
	// replace 'about:newtab' with a custom url, if needed
	try {
	  var mainWindow = Components.classes["@mozilla.org/appshell/window-mediator;1"]
						.getService(Components.interfaces.nsIWindowMediator)
						.getMostRecentWindow("navigator:browser");
	  mainWindow.gBrowser.selectedTab = gBrowser.addTab('about:newtab', {triggeringPrincipal: Services.scriptSecurityManager.getSystemPrincipal()});
	} catch (e) {}
	
	/* focuses location bar */
	try {
	  document.getElementById('urlbar').focus();
	  document.getElementById('urlbar').select();
	} catch (e) {}

  }

}

NewTabMenuItem.init();

@rayman89
Copy link

rayman89 commented Sep 12, 2018

Thank you Aris you are great. Is it possible to position the new tab next to the right clicked tab that initiated the "new tab command" instead of making it the same as pressing the new tab button?

BTW if you are interested they pointed me to this bug which appears to be the reason why the addon can't get the focus https://bugzilla.mozilla.org/show_bug.cgi?id=1485307

@Aris-t2
Copy link
Owner Author

Aris-t2 commented Sep 12, 2018

I can't answer that. Never looked into tab position/order before.

Doesn't look like they are going to fix this bug anytime soon, does it?

@yurikhan
Copy link

Looks like they are; it’s marked Importance: P1, Keywords: regression, and has an Assignee.

@Pizzapops
Copy link

@Aris-t2
Isn't it time to combine this JS issue, the Restart issue and Scrollbars to your front page?
CustomJSforFX??? It would put a little more separation betweedn CSS & JS.

@rayman89
Copy link

@Aris-t2 It has P1 and an Assignee but In my experience it could take 5 or 6 months easily or more. I usually have bad luck with bugs I post or follow.

@Aris-t2
Copy link
Owner Author

Aris-t2 commented Sep 13, 2018

@Pizzapops
I had originally such plans, but after the mess Mozilla started with Fx62 (and the workaround removal in the near future) and the removal of XBL support in the near future, I'm not sure how long such a project would be alive.
But I agree, adding JS scripts to an own repository would improve script management here. ;-)

@rayman89
I get it, most add-on related fixes take too much time regarding their priority. I reported a lot of stuff in the last seven years, but almost everything got ignored. ;-)

@Aris-t2
Copy link
Owner Author

Aris-t2 commented Sep 17, 2018

Here is a new JavaScript related repository CustomJSforFX ;-)
Script discussions inside "issue" area will be easier to follow that way. My scripts present in this thread already went into repositories "scripts" folder. All of you can of course add your own/modified scripts there too.

@LionWrathz
Copy link

LionWrathz commented Sep 20, 2018

Here is a new JavaScript related repository CustomJSforFX ;-)
Script discussions inside "issue" area will be easier to follow that way. My scripts present in this thread already went into repositories "scripts" folder. All of you can of course add your own/modified scripts there too.

could you please check this code again ''List all tabs'' doesn't work.
firefox 62

toolbarbutton#alltabs-button {
-moz-binding: url("./userChrome/userChrome.xml#execute_javascript_code");
}

@Aris-t2
Copy link
Owner Author

Aris-t2 commented Sep 20, 2018

I know, the item you attach the code to will stop working. All tabs button received a code update in Fx 62 or 61, which causes the trouble. You can attach the code to any other button inside the visible part of the ui.

I use this:

toolbarbutton#characterencoding-button {
  -moz-binding: url("./userchrome/userChrome.xml#execute_javascript_code");
}

#main-window:not([customizing="true"]) toolbarbutton#characterencoding-button {
  visibility: collapse;
}

Move characterencoding button to a toolbar first.

@LionWrathz
Copy link

LionWrathz commented Sep 20, 2018

I know, the item you attach the code to will stop working. All tabs button received a code update in Fx 62 or 61, which causes the trouble. You can attach the code to any other button inside the visible part of the ui.

I use this:

toolbarbutton#characterencoding-button {
  -moz-binding: url("./userchrome/userChrome.xml#execute_javascript_code");
}

#main-window:not([customizing="true"]) toolbarbutton#characterencoding-button {
  visibility: collapse;
}

Move characterencoding button to a toolbar first.

need to drags Text Encoding" button to the menu bar it works now ,thank you so much. :)

Repository owner deleted a comment from krystian3w Sep 24, 2018
@Acid-Crash
Copy link

Acid-Crash commented Oct 5, 2018

Hi @Aris-t2.
Could you please take a look if it's possible to add a separate toolbar button for the "Undo Close Tab" (the one that is shown in the drop-down when the number of tabs exceeds the window width)
screen1

thx in advance

@Aris-t2
Copy link
Owner Author

Aris-t2 commented Oct 5, 2018

Yes, it possible to use default 'undoCloseTab();' command.
https://github.com/Aris-t2/CustomJSforFx/blob/master/scripts/undo_closetab_button.uc.js

Just a question (and I'm asking, because I'm not using any of them), don't the multiple "undo close tab" buttons on AMO do basically the same thing?

@krystian3w
Copy link
Contributor

Maybe move discussion to new repo?

@Acid-Crash
Copy link

Acid-Crash commented Oct 5, 2018

@Aris-t2
THX, works fine!

Just a question (and I'm asking, because I'm not using any of them), don't the multiple "undo close tab" buttons on AMO do basically the same thing?

off-top Yes, they do something similar: either reopen the last tab or show the dropdown list of closed tabs. In this specific situation, I thought that I can remove the extension if it's functionality can be achieved by userJS

@Aris-t2
Copy link
Owner Author

Aris-t2 commented Oct 5, 2018

Continue here: Aris-t2/CustomJSforFx#4

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests