I have a requirement to add a tab whenever a new Firefox window is loaded for my bootstrap extension. Below is the code snippet I am using:
var WindowListener = {
setupBrowserUI: function(window) {
window.gBrowser.selectedTab=window.gBrowser.addTab("http://google.com");
},
tearDownBrowserUI: function(window) {
},
// nsIWindowMediatorListener functions
onOpenWindow: function(xulWindow) {
var domWindow = xulWindow.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
.getInterface(Components.interfaces.nsIDOMWindow);
// Wait for it to finish loading
domWindow.addEventListener("load", function listener() {
domWindow.removeEventListener("load", listener, false);
// If this is a browser window then setup its UI
if (domWindow.document.documentElement.getAttribute("windowtype")=="navigator:browser") domWindow.gBrowser.selectedTab=domWindow.gBrowser.addTab("http://google.com");
}, false);
},
onCloseWindow: function(xulWindow) {
},
onWindowTitleChange: function(xulWindow, newTitle) {
}
};
let wm = Components.classes["@mozilla.org/appshell/window-mediator;1"].
getService(Components.interfaces.nsIWindowMediator);
// Wait for any new browser windows to open
wm.addListener(WindowListener);
You can experiment with this code in Scratchpad.
The onOpenWindow method contains the logic to open a tab in a new window, but it seems to execute before the window is fully loaded, causing issues with adding tabs in this state. This contradicts the MDN code that suggests "Wait for it to finish loading".
While setting a timeout using the setTimeout function does solve the problem, it may not be the most elegant solution.
domWindow.setTimeout(function(){domWindow.gBrowser.selectedTab=domWindow.gBrowser.addTab("http://google.com");},1000);
Is there a way to add a tab for new Firefox windows only after the window has completely loaded without relying on setTimeouts?