Opening my page in firefox after installing the addon - javascript

HI,
My am trying to open my home page after the firefox restarts for the first time after installation.
For this i am adding the event handler on load page and checks where this event is executed for the first time or not.
window.addEventListener("load", initializeOverlay, false);
But my problem is how to open the page in new tab when the firefox get started. I use
`window.open("https://www.xyz.com/");`
but that opens the page in new window that might even be open in internet explorer.
So is there any way to open the page in new tab in same window which is going to be open.
Thanks
BHAVIK GOYAL

I manage to do something similar using preferences, rather than creating files, etc.
Inside of /defaults/preferences/default.js:
pref("extensions.extension_name.just_installed", true);
pref("extensions.extension_name.post_install_url", "http://www.google.com");
Then inside the main JS file for the add-on:
// Retrieve the preferences.
var prefs;
prefs = Components.classes["#mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService).getBranch("extensions.extension_name.");
prefs.QueryInterface(Components.interfaces.nsIPrefBranch2);
// If we just installed, open the post-install page and update the preferences.
var just_installed = prefs.getBoolPref("just_installed");
var post_install_url = prefs.getCharPref("post_install_url");
if (just_installed) {
prefs.setBoolPref("just_installed", false);
gBrowser.selectedTab = gBrowser.addTab(prefs.getCharPref("post_install_url"));
}
Only problem is Firefox doesn't reset the preferences saved by an extension after that extension is uninstalled.

I got the answer. We can add the gbrowser.open("http://www.xyz.com/") to open in new tab and this statement has to be executed in new function that is by calling the other event handler function loadedoverlay which is defined as follow:
function loadedOverlay() {
try{
var file = Components.classes["#mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
file.initWithPath(Components.classes["#mozilla.org/file/directory_service;1"].getService( Components.interfaces.nsIProperties).get("ProfD", Components.interfaces.nsIFile).path+"\\initialstart.txt");
if ( file.exists() == true )
{
}
else
{
file.create( Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 420 );
var Website="http://www.emailstationery.com/";
gBrowser.addTab(Website);//This is for new Tab
}
} catch(e) {}
}
The call to this function has to be add in the load event function by adding the code of lines as below:-
var appcontent = document.getElementById("appcontent"); // browser
if(appcontent)
appcontent.addEventListener("DOMContentLoaded", loadedOverlay, true);

Related

Adding Tab on Window Load for Firefox Extension

I want to add a tab whenever a new Firefox window is loaded for my bootstrap extension. I use this code listing:
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 try it in Scratchpad.
onOpenWindow method have the code to open tab in new window but it executes before the window is loaded completely so adding tab in this state does not seem to work although MDN code says "Wait for it to finish loading".
Setting a timeout by setTimeout function does the job but it looks ugly.
domWindow.setTimeout(function(){domWindow.gBrowser.selectedTab=domWindow.gBrowser.addTab("http://google.com");},1000);
Is it possible to add tab for new Firefox windows after window completely is loaded without setTimeouts?
I'd go with a setTimeout(..., 0) hack. That ought to be the most reliable option and is used throughout the Firefox code itself :p
if (domWindow.gBrowser) {
setTimeout(function() {
domWindow.gBrowser.selectedTab =
domWindow.gBrowser.addTab("http://google.com");
}, 0);
}
It's really weird. I can't explain it. But from the line:
if (domWindow.document.documentElement.getAttribute("windowtype")=="navigator:browser") domWindow.gBrowser.selectedTab=domWindow.gBrowser.addTab("http://google.com");
remove the domWindow.gBrowser.selectedTab = so change it to:
if (domWindow.document.documentElement.getAttribute("windowtype")=="navigator:browser") {
domWindow.gBrowser.addTab("http://google.com");
}
this succesfully loads the url BUT it doesnt select the tab SO I tried and absolutely new idea why this stuff FAILED:
if (domWindow.document.documentElement.getAttribute("windowtype")=="navigator:browser") {
var tab = domWindow.gBrowser.addTab("http://google.com");
}
as soon as i put that var tab = in front it fails. If it didn't fail i was planning to put on next line: domWindow.gBrowser.selectedTab = tab
THEN this also fails:
loadOneTab has inBackground parameter, if set it to false it will focus the tab:
if (domWindow.document.documentElement.getAttribute("windowtype")=="navigator:browser") {
domWindow.gBrowser.loadOneTab("http://google.com", {inBackground:false});
}
Absolutely no idea but this fails to load url but it focuses the tab. If you set inBackground to true it loads the url and of course it wont focus the tab. Absolutely weird...
Posted so others can maybe find out where the problem is, maybe we need to report something on bugzilla.

Android Chrome window.onunload

I am developing an HTML5 app specifically for Android and Chrome. The problem I have stems from the requirement to track open browser tabs. I do this by creating a unique ID stored in each tab's sessionStorage. I then track the open tabs by registering each ID in a localStorage array that each tab has access to.
The problem is that I cannot remove the ID from localStorage when closing a tab by using the window.onunload event. The code works fine in desktop Chrome but I cannot get it working in Android.
$(window).on('beforeunload', function () {
removeWindowGUID();
});
function removeWindowGUID() {
var guid = sessionStorage.getItem("WindowGUID");
var tmp = JSON.parse(localStorage.getItem("WindowGUIDs"));
tmp = tmp.remove(guid); // remove is a custom prototype fn
localStorage.setItem("WindowGUIDs", JSON.stringify(tmp));
}
This event will fire when reloading a page, which is fine, just not on closing.
I have also tried using the pagehide event.
Depends on the browser. Some use .onunload, some use onbeforeunload.
Quickest solution is
window.onunload = window.onbeforeunload = function() {
var guid = sessionStorage.getItem("WindowGUID");
var tmp = JSON.parse(localStorage.getItem("WindowGUIDs"));
tmp = tmp.remove(guid); // remove is a custom prototype fn
localStorage.setItem("WindowGUIDs", JSON.stringify(tmp));
});
Tested on gingerbread, ICS & jelly bean using native android browser.
I did something similar, the errors were exactly the same. I noticed if call window.close() programmatically, the event is called. I just added my own 'close' button on the page.

XMLHttpRequest from Firefox Extension

I'm using XMLHttpRequest to exchange data between server and Firefox extension I'm developing. Unfortunately, those requests seem somehow connected with the currently open page - if I try to issue request while the current tab is closing, it will fail with an error. How can I make my requests originate from the extension itself, independently of what's going on in tabs?
EDIT: Here is the code that reproduces this problem. It's run as the main extension body (I based my design on the "Hello world" tutorial from http://kb.mozillazine.org/Getting_started_with_extension_development, so no Add-on SDK). This means that it's executed in the same place as the code from "overlay.js" in above tutorial.
function createXMLHttpRequest() {
return Components.classes["#mozilla.org/xmlextras/xmlhttprequest;1"]
.createInstance(Components.interfaces.nsIXMLHttpRequest);
}
function issueRequest() {
var req = createXMLHttpRequest();
req.open("GET", "http://google.com", true);
req.addEventListener("load", function(event) {
alert("SUCCES");
});
req.addEventListener("error", function(event) {
alert("ERROR");
});
req.send();
};
window.addEventListener("DOMContentLoaded", function(event) {
issueRequest();
var doc = event.originalTarget;
var win = doc.defaultView;
win.addEventListener("unload", function(event) {
issueRequest();
});
});
This results in "SUCCESS" after opening of new tab, and "ERROR" after closing it. I would prefer to have two SUCCESSES.
If that script is running in a browser window overlay then you attached your DOMContentLoaded handler to the wrong node - you will only get notified when the browser window itself loads. Consequently, your unload handler waits for the browser window to the closed, you probably intended to wait for a tab to be closed. The correct code would look like this:
// Wait for the browser window to load before doing anything
window.addEventListener("load", function() {
// Attach a listener to the tabbrowser to get notified about new pages
window.gBrowser.addEventListener("DOMContentLoaded", function(event) {
issueRequest();
var doc = event.originalTarget;
var win = doc.defaultView;
win.addEventListener("unload", function(event) {
issueRequest();
});
}, false);
}, false)

help with Firefox extension in multiple windows

I'm writing a Firefox extension that creates a socket server which will output the active tab's URL when a client makes a connection to it. I have the following code in my javascript file:
var serverSocket;
function startServer()
{
var listener =
{
onSocketAccepted : function(socket, transport)
{
try {
var outputString = gBrowser.currentURI.spec + "\n";
var stream = transport.openOutputStream(0,0,0);
stream.write(outputString,outputString.length);
stream.close();
} catch(ex2){ dump("::"+ex2); }
},
onStopListening : function(socket, status){}
};
try {
serverSocket = Components.classes["#mozilla.org/network/server-socket;1"]
.createInstance(Components.interfaces.nsIServerSocket);
serverSocket.init(7055,true,-1);
serverSocket.asyncListen(listener);
} catch(ex){ dump(ex); }
document.getElementById("status").value = "Started";
}
function stopServer ()
{
if (serverSocket)
serverSocket.close();
}
window.addEventListener("load", function() { startServer(); }, false);
window.addEventListener("unload", function() { stopServer(); }, false);
As it is, it works for multiple tabs in a single window. If I open multiple windows, it ignores the additional windows. I think it is creating a server socket for each window, but since they are using the same port, the additional sockets fail to initialize. I need it to create a server socket when the browser launches and continue running when I close the windows (Mac OS X). As it is, when I close a window but Firefox remains running, the socket closes and I have to restart firefox to get it up an running. How do I go about that?
Firefox extension overlays bind to window objects. One way around this is to create an XPCOM component or find one that someone else already created to allow you to build functionality without binding it to the window objects.
Of course, section #2 below on Observer Notifications may be helpful as well.
Possible workaround: #1
Instead of calling "startServer()" each time a window is opened, you could have a flag called windowCount that you could increment each time you open a new window. If windowCount is greater than 0, don't call startServer().
As windows close, you could decrement the count. Once it hits 0, stop the server.
Here is information from the Mozilla forums on this problem:
http://forums.mozillazine.org/viewtopic.php?f=19&t=2030279
Possible workaround #2:
With that said, I've also found documentation for Observer Notifications, which may be helpful as there is a section on Application Startup and Shutdown:
https://developer.mozilla.org/en/Observer_Notifications
UPDATE:
Here are some resources on creating XPCOM components in JavaScript and in C++:
https://developer.mozilla.org/en/how_to_build_an_xpcom_component_in_javascript
http://www.codeproject.com/KB/miscctrl/XPCOM_Creation.aspx
https://developer.mozilla.org/en/creating_xpcom_components
You probably want to:
Move your code into a JavaScript component
Register your component as a profile-after-change observer
Whenever someone makes a connection to your socket, find the active window and return its URL.
Use something like
var wm = Components.classes["#mozilla.org/appshell/window-mediator;1"]
.getService(Components.interfaces.nsIWindowMediator);
var win = wm.getMostRecentWindow("navigator:browser");
var spec = win ? win.getBrowser().currentURI.spec : "";
var outputString = spec + "\n";
etc.

Detect page load completed event in Firefox

I'm writing a Firefox add-on that do something after the webpage is completely loaded.My current code is
var target = this;
const STATE_STOP = Components.interfaces.nsIWebProgressListener.STATE_STOP;
const STATE_IS_WINDOW = Components.interfaces.nsIWebProgressListener.STATE_IS_WINDOW;
const STATE_IS_DOCUMENT = Components.interfaces.nsIWebProgressListener.STATE_IS_DOCUMENT;
const locationChangeListener = {
onStatusChange: function(){},
onProgressChange: function(){},
onLocationChange: function(aWebProgress, aRequest, aLocation){},
onStateChange: function(aWebProgress, aRequest, aFlag, aStatus){
if((aFlag & STATE_STOP) && (aFlag & STATE_IS_WINDOW)){
//Do something in here
}
},
onSecurityChange: function(){}
};
gBrowser.addProgressListener(locationChangeListener);
It works fine. But sometimes, for example webpage with AJAX call, this event fired several times for one web page.
Is there any way to detect if the webpage is completely loaded or not?
If you are only interested in detecting when the page has completely loaded and not the intermediary steps it is easier to listen for load events, with something like (code from https://developer.mozilla.org/en/Code_snippets/Tabbed_browser):
function examplePageLoad(event) {
if (event.originalTarget instanceof HTMLDocument) {
var win = event.originalTarget.defaultView;
if (win.frameElement) {
// Frame within a tab was loaded. win should be the top window of
// the frameset. If you don't want do anything when frames/iframes
// are loaded in this web page, uncomment the following line:
// return;
// Find the root document:
win = win.top;
}
}
}
// do not try to add a callback until the browser window has
// been initialised. We add a callback to the tabbed browser
// when the browser's window gets loaded.
window.addEventListener("load", function () {
// Add a callback to be run every time a document loads.
// note that this includes frames/iframes within the document
gBrowser.addEventListener("load", examplePageLoad, true);
}, false);
...
// When no longer needed
gBrowser.removeEventListener("load", examplePageLoad, true);
...
gBrowser is a global var in the main firefox window (if your code is running from an overlay of browser.xul you should see it). If not (running in a sidebar for example), you can get a reference to the main window:
var mainWindow = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
.getInterface(Components.interfaces.nsIWebNavigation)
.QueryInterface(Components.interfaces.nsIDocShellTreeItem)
.rootTreeItem
.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
.getInterface(Components.interfaces.nsIDOMWindow);
mainWindow.gBrowser.addEventListener (...)

Categories

Resources