I'm trying to create a firefox addon that will look for a certain page on startup and grab some info from it. I'm having trouble finding the page at load. Here's what I have so far:
var myfancyaddon = {
onLoad: function() {
var observerService = Components.classes["#mozilla.org/observer-service;1"].getService(Components.interfaces.nsIObserverService);
observerService.addObserver(function restored() {
observerService.removeObserver( restored, "sessionstore-windows-restored");
var browser = myfancyaddon.findMySite();
if (browser) {
alert("tree falling in the woods"); // THIS LINE NEVER RUNS
browser.contentWindow.addEventListener("load", function tab_loaded(){
browser.contentWindow.removeEventListener("load", tab_loaded(), false);
alert("mysite loaded!");
}, false);
}
}, "sessionstore-windows-restored", false);
},
findMySite: function() {
var browsers = gBrowser.browsers;
for ( var i = 0; i < browsers.length; i++ ) {
var browser = browsers[i];
if (!browser.currentURI.spec) continue;
if ( browser.currentURI.spec.match('^https?://(www\.)?mysite\.com/') ) return browser;
}
return null;
}
};
window.addEventListener("load", function ff_loaded(){
window.removeEventListener("load", ff_loaded, false); //remove listener, no longer needed
myfancyaddon.onLoad();
},false);
after some investigation it seems the currentURI.spec is "about:blank" for a short time before it becomes mysite.com. Any ideas?
Instead of filtering first and then adding the load listener, you could use gBrowser.addEventListener("DOMContentLoaded", myfunction, false); to listen for page loads on all tab documents and then only run your code based on the url.
https://developer.mozilla.org/en/XUL_School/Intercepting_Page_Loads
The "sessionstore-windows-restored" notification is sent when the tabs from the previous session have been restored and the loading in these tabs has been started (sometimes: "Don't load tabs until selected" option means that the load isn't even started in the background tabs). But the location of these tabs is still about:blank until the server is contacted because the address loaded might redirect or the server might be unreachable (meaning an internal redirect to about:neterror). Firefox only changes browser location when content is definitely being served from the new location.
It should be indeed better to intercept page loads rather than waiting for session restore.
Related
I have an angularjs application running on tomcat, and behind a loadbalancer
If the app is requested via the loadbalancer with https, the balancer still requests the application internally via http, of course.
Problem: I'd like to hide one tab that shows mixed content in this case (because I have to embed external pdf links which do not support https, thus I'd like to hide them).
I cannot use $location.protocol() because the app is behind the loadbalancer and always only gets http.
Question: is there a chance I could detect if the browser is actually showing mixed content?
You can't detect it in the simple way. You can try to listen load event on iframe and set timeout, and when timeout triggered, block iframe because iframe didn't loaded like this (jsfiddle example):
checkMixedContent(urlToCheck, function(urlToCheck) {
// For example, change location
alert('ok');
// load iframe
}, function() {
alert('Error: resource timed out');
// hide iframe / show message
}, checkDelay);
function checkMixedContent(urlToCheck, successCallback, errorCallback, checkDelay, dontCheckOnError) {
checkDelay = checkDelay || 10000;
// 1. Create invisible iframe and append it to body
var iframeHelper = document.createElement("iframe");
iframeHelper.src = urlToCheck;
iframeHelper.height = 0;
iframeHelper.width = 0;
iframeHelper.style.visibility = 'hidden';
document.body.appendChild(iframeHelper);
// 2. Set time out and while content on iframeHelper.src should be definitely loaded
var checkTimeout = window.setTimeout(function() {
errorCallback(urlToCheck);
}, checkDelay);
var onLoad = function() {
window.clearTimeout(checkTimeout); // if OK - not show error => clearTimeout
iframeHelper.removeEventListener('load', onLoad);
iframeHelper.removeEventListener('error', onError);
document.body.removeChild(iframeHelper);
successCallback(urlToCheck);
};
var onError = function() {
window.clearTimeout(checkTimeout); // if OK - not show error => clearTimeout
iframeHelper.removeEventListener('load', onLoad);
iframeHelper.removeEventListener('error', onError);
document.body.removeChild(iframeHelper);
errorCallback(urlToCheck);
};
// 3. If everything is fine - "load" should be triggered
iframeHelper.addEventListener('load', onLoad);
// Turn "true" in case of "X-Frame-Options: SAMEORIGIN"
if (!dontCheckOnError) {
iframeHelper.addEventListener('error', onError);
}
}
I'm currently trying to build a firefox extension that determines a proxy for each http request based on Regular Expressions. The Proxy that has been used for loading a page should be remembered for any new request coming from that page, ie. any image/script/css file needed for that page, any outgoing links or ajax requests. That also means that the proxy needs to be remembered for each open tab.
This is where I run into my problem: Up until now I tried to mark each open tab by inserting a unique id as an attribute of the browser element of the tab, and looking for this id in an implementation of the shouldLoad() method of nsiContentPolicy. The code I'm using for this is shown below, and it was extracted from the addon sdk's getTabForContentWindow method in tabs/utils.js.
shouldLoad: function(contentType, contentLocation, requestOrigin, context, mimeTypeGuess, extra)
{
var tabId = null;
if (!(context instanceof CI.nsIDOMWindow))
{
// If this is an element, get the corresponding document
if (context instanceof CI.nsIDOMNode && context.ownerDocument)
context = context.ownerDocument;
// Now we should have a document, get its window
if (context instanceof CI.nsIDOMDocument)
context = context.defaultView;
else
context = null;
}
let browser;
try {
browser = context.QueryInterface(CI.nsIInterfaceRequestor)
.getInterface(CI.nsIWebNavigation)
.QueryInterface(CI.nsIDocShell)
.chromeEventHandler;
} catch(e) {
this.console.log(e);
}
let chromeWindow = browser.ownerDocument.defaultView;
if ('gBrowser' in chromeWindow && chromeWindow.gBrowser &&
'browsers' in chromeWindow.gBrowser) {
let browsers = chromeWindow.gBrowser.browsers;
let i = browsers.indexOf(browser);
if (i !== -1)
tabId = chromeWindow.gBrowser.tabs[i].getAttribute("PMsMark");
}
return CI.nsIContentPolicy.ACCEPT;
}
This works fine for any load that does not change the displayed document, but as soon as the document is changed(ie. a new page is loaded), the variable browser is null.
I have looked at the other mechanisms for intercepting page loads described on https://developer.mozilla.org/en-US/Add-ons/Overlay_Extensions/XUL_School/Intercepting_Page_Loads , but those seem to be unsuitable for what I want to achieve, because as far as I understand they work on HTTP requests, and for a request to exist, the proxy already needed to be determined.
So, if anybody knows a way to catch imminent loads before they become requests, and at the same time, it's possible to find out which tab is responsible for those loads-to-be, I'd be glad if they could let me know in the answers! Thanks in advance!
https://developer.mozilla.org/en-US/docs/Code_snippets/Tabbed_browser#Getting_the_browser_that_fires_the_http-on-modify-request_notification
Components.utils.import('resource://gre/modules/Services.jsm');
Services.obs.addObserver(httpObs, 'http-on-opening-request', false);
//Services.obs.removeObserver(httpObs, 'http-on-modify-request'); //uncomment this line, or run this line when you want to remove the observer
var httpObs = {
observe: function (aSubject, aTopic, aData) {
if (aTopic == 'http-on-opening-request') {
/*start - do not edit here*/
var oHttp = aSubject.QueryInterface(Components.interfaces.nsIHttpChannel); //i used nsIHttpChannel but i guess you can use nsIChannel, im not sure why though
var interfaceRequestor = oHttp.notificationCallbacks.QueryInterface(Components.interfaces.nsIInterfaceRequestor);
//var DOMWindow = interfaceRequestor.getInterface(Components.interfaces.nsIDOMWindow); //not to be done anymore because: https://developer.mozilla.org/en-US/docs/Updating_extensions_for_Firefox_3.5#Getting_a_load_context_from_a_request //instead do the loadContext stuff below
var loadContext;
try {
loadContext = interfaceRequestor.getInterface(Components.interfaces.nsILoadContext);
} catch (ex) {
try {
loadContext = aSubject.loadGroup.notificationCallbacks.getInterface(Components.interfaces.nsILoadContext);
//in ff26 aSubject.loadGroup.notificationCallbacks was null for me, i couldnt find a situation where it wasnt null, but whenever this was null, and i knew a loadContext is supposed to be there, i found that "interfaceRequestor.getInterface(Components.interfaces.nsILoadContext);" worked fine, so im thinking in ff26 it doesnt use aSubject.loadGroup.notificationCallbacks anymore, but im not sure
} catch (ex2) {
loadContext = null;
//this is a problem i dont know why it would get here
}
}
/*end do not edit here*/
/*start - do all your edits below here*/
var url = oHttp.URI.spec; //can get url without needing loadContext
if (loadContext) {
var contentWindow = loadContext.associatedWindow; //this is the HTML window of the page that just loaded
//aDOMWindow this is the firefox window holding the tab
var aDOMWindow = contentWindow.top.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIWebNavigation).QueryInterface(Ci.nsIDocShellTreeItem).rootTreeItem.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindow);
var gBrowser = aDOMWindow.gBrowser; //this is the gBrowser object of the firefox window this tab is in
var aTab = gBrowser._getTabForContentWindow(contentWindow.top); //this is the clickable tab xul element, the one found in the tab strip of the firefox window, aTab.linkedBrowser is same as browser var above //can stylize tab like aTab.style.backgroundColor = 'blue'; //can stylize the tab like aTab.style.fontColor = 'red';
var browser = aTab.linkedBrowser; //this is the browser within the tab //this is what the example in the previous section gives
//end getting other useful stuff
} else {
Components.utils.reportError('EXCEPTION: Load Context Not Found!!');
//this is likely no big deal as the channel proably has no associated window, ie: the channel was loading some resource. but if its an ajax call you may end up here
}
}
}
};
I'm developing a Firefox extension and I need to change the user agent of a single tab. I have used extensions such as User Agent Switcher, but it only let me change the user agent in the entire browser. Do you know if that is possible? Where can I read about?
Thanks a lot,
G.
this is a fun addon. i wanted to make an addon which enabled proxy only in single tab, i think this here helping u will lead me to make that sometime soon
copy paste code. it will spoof user-agent in all things loaded in tab 1. in all other tabs it will let the load go through. however if there is no loadContext you wont be able to tell which tab its coming from, so probably just ignore it and let it go.
we need advice from ppl more experienced then me. in what cases do we get a null loadContext?
on to the copy paste code
const {classes: Cc, Constructor: CC, interfaces: Ci, utils: Cu, results: Cr, manager: Cm} = Components;
Cu.import('resource://gre/modules/Services.jsm');
var myTabToSpoofIn = Services.wm.getMostRecentBrowser('navigator:browser').gBrowser.tabContainer[0]; //will spoof in the first tab of your browser
var httpRequestObserver = {
observe: function (subject, topic, data) {
var httpChannel, requestURL;
if (topic == "http-on-modify-request") {
httpChannel = subject.QueryInterface(Ci.nsIHttpChannel);
var goodies = loadContextGoodies(httpChannel)
if (goodies) {
if (goodies.aTab == myTabToSpoofIn) {
httpChannel.setRequestHeader('User-Agent', 'user agent spoofeddddd', false);
} else {
//we arent spoofing in this tab so ignore it
}
} else {
//no goodies so we dont know what tab its from, im not sure when we dont have a loadContext we need to ask other ppl
//no goodies for this channel, so dont know what tab its in so probably just load this, your decision though, make it option to user, if cannot find associated load context ask user if they want the data to be loaded with default user agent or just not load it at all
//httpChannel.cancel(Cr.NS_BINDING_ABORTED); //uncomment this to abort it
}
}
}
};
Services.obs.addObserver(httpRequestObserver, "http-on-modify-request", false);
//Services.obs.removeObserver(httpRequestObserver, "http-on-modify-request", false); //run this on shudown of your addon otherwise the observer stags registerd
//this function gets the contentWindow and other good stuff from loadContext of httpChannel
function loadContextGoodies(httpChannel) {
//httpChannel must be the subject of http-on-modify-request QI'ed to nsiHTTPChannel as is done on line 8 "httpChannel = subject.QueryInterface(Ci.nsIHttpChannel);"
//start loadContext stuff
var loadContext;
try {
var interfaceRequestor = httpChannel.notificationCallbacks.QueryInterface(Ci.nsIInterfaceRequestor);
//var DOMWindow = interfaceRequestor.getInterface(Components.interfaces.nsIDOMWindow); //not to be done anymore because: https://developer.mozilla.org/en-US/docs/Updating_extensions_for_Firefox_3.5#Getting_a_load_context_from_a_request //instead do the loadContext stuff below
try {
loadContext = interfaceRequestor.getInterface(Ci.nsILoadContext);
} catch (ex) {
try {
loadContext = subject.loadGroup.notificationCallbacks.getInterface(Ci.nsILoadContext);
} catch (ex2) {}
}
} catch (ex0) {}
if (!loadContext) {
//no load context so dont do anything although you can run this, which is your old code
//this probably means that its loading an ajax call or like a google ad thing
return null;
} else {
var contentWindow = loadContext.associatedWindow;
if (!contentWindow) {
//this channel does not have a window, its probably loading a resource
//this probably means that its loading an ajax call or like a google ad thing
return null;
} else {
var aDOMWindow = contentWindow.top.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIWebNavigation)
.QueryInterface(Ci.nsIDocShellTreeItem)
.rootTreeItem
.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIDOMWindow);
var gBrowser = aDOMWindow.gBrowser;
var aTab = gBrowser._getTabForContentWindow(contentWindow.top); //this is the clickable tab xul element, the one found in the tab strip of the firefox window, aTab.linkedBrowser is same as browser var above //can stylize tab like aTab.style.backgroundColor = 'blue'; //can stylize the tab like aTab.style.fontColor = 'red';
var browser = aTab.linkedBrowser; //this is the browser within the tab //this is where the example in the previous section ends
return {
aDOMWindow: aDOMWindow,
gBrowser: gBrowser,
aTab: aTab,
browser: browser,
contentWindow: contentWindow
};
}
}
//end loadContext stuff
}
also a note. because you want to change user request make sure that third parameter is set to false in httpChannel.setRequestHeader('MyCustomRequestHeader', 'hiiii', false); otherwise it will merge the pre-existing user agent with the new one you supply
In my chat application i am having the logout button and it works fine.
Now I need to logout the application when I closed the browser window also..How can I achieve this...
Thanks in advance...
There is no exact way to do this with the clientside. There is no event that is fired when the page is exited. It should be done with the Session End event on the server.
You can try to use onbeforeunload or unload, but race conditions will prevent that from happening. AND they do not fire for browsers crashing, lost internet connection, etc.
I dealt with this issue recently in my angularJS app - The main issue was that I don't want to log you out if you refresh, but I do want to if you close the tab.. Ajax requests with onbeforeunload/onunload aren't guaranteed to wait for response, so here is my solution:
I set a sessionStorage cookie on login that is just a bool - set to true when I get login response
sessionStorage.setItem('activeSession', 'true');
Obviously, on logout, we set this flag to false
Either when controller initializes or using window.onload (in my app.js file) - I check for this activeSession bool.. if it is false, I have this small if statement - where if conditions are met I call my logout method ONLOAD instead of onunload
var activeSession = sessionStorage.activeSession;
if (sessionStorage.loggedOutOnAuth) {
console.log('Logged out due to expiry already')
}
else if (!activeSession) {
sessionStorage.loggedOutOnAuth = true;
_logout()
}
Basically, the "loggedOutAuth" bool let's me know that I just expired you on page load due to the absence of an activeSession in sessionStorage so you don't get stuck in a loop
This was a great solution for me since I didn't want to implement a heartbeat/websocket
Add your logout code to the on onunload event.
window.onunload = function () {
//logout code here...
}
In JQuery you can use the .unload() function. Remember that you don't have much time so you may send the Ajax request but the result may not reach the client.
Another trick is to open a small new window and handle the logout there.
window.open("logout url","log out","height=10,width=10,location=no,menubar=no,status=no,titlebar=no,toolbar=no",true);
If you want to disable closing the window (or at least warn the user), you can use this code:
window.onbeforeunload = function(event) {
//if you return anything but null, it will warn the user.
//optionally you can return a string which most browsers show to the user as the warning message.
return true;
}
Another trick is to keep pinging the client every few seconds. If no reply comes back, assume the user has closed the window, browser has crashed or there is a network issue that ended the chat session anyway. On the client side, if you don't receive this ping package, you can assume that network connection or server has a problem and you can show the logout warning (and optionally let the user login again).
Some websites are using the following script to detect whether window is closed or not.
if(window.screenTop > 10000)
alert("Window is closed");
else
alert("Window stillOpen");
You need to add the correct action instead of alert()
also take a look HERE - I think this is somthing you need to detect the window closing
I got the Solution by,
window.onunload = function () {
//logout code here...
}
Thanks for all who supported me...
Another approach is some sort of "keepalive": the browser page "pings" the server with a small ajax request every minute or so. If the server doesn't get the regular pings, the session is closed and can no longer be used.
As an optimization, the pings can be skipped if we have made another request to the server in the interim.
Advantages:
still works with multiple windows open
no problem with F5 / refresh
can provides some usage statistics to the server
Disadvantages:
when the window is closed, there is a delay before the user is logged out
uses a little network bandwidth
additional load on the server
users might have concerns about the page constantly "phoning home"
more difficult to implement
I've never actually done this in a web app, and not sure if I would; just putting it out there as an alternative. It seems like a good option for a chat app, where the server does need to know if you are still there.
Rather than polling / pinging, another possibility is to keep a "long running request" open while the page is open. A chat app needs some such socket to receive new messages and notifications. If the page is closed, the socket is closed too, and the server can notice that it has been closed. It then waits a brief time for the client to establish a new socket, and if it doesn't we assume the page is closed and delete the session. This would require some slightly unusual software on the server.
I was with this problem here and I come with a different solution:
checkSessionTime();
$interval(checkSessionTime, 2000);
function checkSessionTime() {
var now = (new Date()).getTime();
if (!$localStorage.lastPing) {
$localStorage.lastPing = now;
}
if ($localStorage.lastPing < now - 5000) {
$localStorage.lastPing = undefined;
AuthService.logout();
} else {
$localStorage.lastPing = now;
}
}
I like this solution cause it doesnt add overhead pinging the server nor rely on the window unload event. This code was put inside the $app.run.
I am using angular with a JWT auth, this way to me to log out just mean to get rid of the auth token. However, if you need to finish up the session server-side you can just build the Auth service to do one ping when finishing the session instead of keep pinging to maitain session alive.
This solutionsolves my case cause my intetion is just to prevent unwanted users to access someones account when they closed the tab and went away from the PC.
After lots of search I wrote the below customized code in javascript and server side code for session kill in c#.
The below code is extended in case of same website is open in multiple tabs so the session is alive till one tab of website is open
//Define global varible
var isCloseWindow = false;
//Jquery page load function to register the events
$(function () {
//function for onbeforeuload
window.onbeforeunload = ConfirmLeave;
//function for onload
window.onload = ConfirmEnter;
//mouseover for div which spans the whole browser client area
$("div").on('mouseover', (function () {
//for postback from the page make isCloseWindow global varible to false
isCloseWindow = false;
}));
//mouseout event
$("div").on('mouseout', (function () {
//for event raised from tabclose,browserclose etc. the page make isCloseWindow global varible to false
isCloseWindow = true;
}));
});
//Key board events to track the browser tab or browser closed by ctrl+w or alt+f4 key combination
$(document).keydown(function (e) {
if (e.key.toUpperCase() == "CONTROL") {
debugger;
isCloseWindow = true;
}
else if (e.key.toUpperCase() == "ALT") {
debugger;
isCloseWindow = true;
}
else {
debugger;
isCloseWindow = false;
}
});
function ConfirmEnter(event) {
if (localStorage.getItem("IsPostBack") == null || localStorage.getItem("IsPostBack") == "N") {
if (localStorage.getItem("tabCounter") == null || Number(localStorage.getItem("tabCounter")) == 0) {
//cookie is not present
localStorage.setItem('tabCounter', 1);
} else {
localStorage.setItem('tabCounter', Number(localStorage.getItem('tabCounter')) + 1);
}
}
localStorage.setItem("IsPostBack", "N");
}
function ConfirmLeave(event) {
if (event.target.activeElement.innerText == "LOGOUT") {
localStorage.setItem('tabCounter', 0);
localStorage.setItem("IsPostBack", "N");
} else {
localStorage.setItem("IsPostBack", "Y");
}
if ((Number(localStorage.getItem('tabCounter')) == 1 && isCloseWindow == true)) {
localStorage.setItem('tabCounter', 0);
localStorage.setItem("IsPostBack", "N");
**Call Web Method Kill_Session using jquery ajax call**
} else if (Number(localStorage.getItem('tabCounter')) > 1 && isCloseWindow == true) {
localStorage.setItem('tabCounter', Number(localStorage.getItem('tabCounter')) - 1);
}
}
//C# server side WebMethod
[WebMethod]
public static void Kill_Session()
{
HttpContext.Current.Session.Abandon();
}
For this issue I tried 2 solutions: window.onbeforeunload event and sessionStorage
Since window.onbeforeunload is not only for closing the browser but also redirect, tab refresh, new tab, it was not a robust solution. Also there are cases which the event does not happen: closing the browser through the command line, shutting down the computer
I switched to using sessionStorage. When the user logs in I set a sessionStorage variable to 'true'; when the application is loaded I would check to see if this variable is there, otherwise I would force the user to log in. However I need to share the sessionStorage variable across tabs so that a user is not forced to log in when they open a new tab in the same browser instance, I was able to do this by leveraging the storage event; a great example of this can be found here
tabOrBrowserStillAliveInterval;
constructor() {
// system should logout if the browser or last opened tab was closed (in 15sec after closing)
if (this.wasBrowserOrTabClosedAfterSignin()) {
this.logOut();
}
// every 15sec update browserOrTabActiveTimestamp property with new timestamp
this.setBrowserOrTabActiveTimestamp(new Date());
this.tabOrBrowserStillAliveInterval = setInterval(() => {
this.setBrowserOrTabActiveTimestamp(new Date());
}, 15000);
}
signin() {
// ...
this.setBrowserOrTabActiveTimestamp(new Date());
}
setBrowserOrTabActiveTimestamp(timeStamp: Date) {
localStorage.setItem(
'browserOrTabActiveSessionTimestamp',
`${timeStamp.getTime()}`
);
}
wasBrowserOrTabClosedAfterSignin(): boolean {
const value = localStorage.getItem('browserOrTabActiveSessionTimestamp');
const lastTrackedTimeStampWhenAppWasAlive = value
? new Date(Number(value))
: null;
const currentTimestamp = new Date();
const differenceInSec = moment(currentTimestamp).diff(
moment(lastTrackedTimeStampWhenAppWasAlive),
'seconds'
);
// if difference between current timestamp and last tracked timestamp when app was alive
// is more than 15sec (if user close browser or all opened *your app* tabs more than 15sec ago)
return !!lastTrackedTimeStampWhenAppWasAlive && differenceInSec > 15;
}
How it works:
If the user closes the browser or closes all opened your app tabs then after a 15sec timeout - logout will be triggered.
it works with multiple windows open
no additional load on the server
no problem with F5 / refresh
Browser limitations are the reason why we need 15sec timeout before logout. Since browsers cannot distinguish such cases: browser close, close of a tab, and tab refresh. All these actions are considered by the browser as the same action. So 15sec timeout is like a workaround to catch only the browser close or close of all the opened your app tabs (and skip refresh/F5).
I posted this originally here but I will repost here for continuity.
There have been updates to the browser to better tack the user when leaving the app. The event 'visibilitychange' lets you tack when a page is being hidden from another tab or being closed. You can track the document visibility state. The property document.visibilityState will return the current state. You will need to track the sign in and out but its closer to the goal.
This is supported by more newer browser but safari (as we know) never conforms to standards. You can use 'pageshow' and 'pagehide' to work in safari.
You can even use new API's like sendBeacon to send a one way request to the server when the tab is being closed and shouldn't expect a response.
I build a quick port of a class I use to track this. I had to remove some calls in the framework so it might be buggy however this should get you started.
export class UserLoginStatus
{
/**
* This will add the events and sign the user in.
*/
constructor()
{
this.addEvents();
this.signIn();
}
/**
* This will check if the browser is safari.
*
* #returns {bool}
*/
isSafari()
{
if(navigator && /Safari/.test(navigator.userAgent) && /Chrome/.test(navigator.userAgent))
{
return (/Google Inc/.test(navigator.vendor) === false);
}
return false;
}
/**
* This will setup the events array by browser.
*
* #returns {array}
*/
setupEvents()
{
let events = [
['visibilitychange', document, () =>
{
if (document.visibilityState === 'visible')
{
this.signIn();
return;
}
this.signOut();
}]
];
// we need to setup events for safari
if(this.isSafari())
{
events.push(['pageshow', window, (e) =>
{
if(e.persisted === false)
{
this.signIn();
}
}]);
events.push(['pagehide', window, (e) =>
{
if(e.persisted === false)
{
this.signOut();
}
}]);
}
return events;
}
/**
* This will add the events.
*/
addEvents()
{
let events = this.setupEvents();
if(!events || events.length < 1)
{
return;
}
for(var i = 0, length = events.length; i < length; i++)
{
var event = events[i];
if(!event)
{
continue;
}
event[1].addEventListener(event[0], event[3]);
}
}
/**
*
* #param {string} url
* #param {string} params
*/
async fetch(url, params)
{
await fetch(url,
{
method: 'POST',
body: JSON.stringify(params)
});
}
/**
* This will sign in the user.
*/
signIn()
{
// user is the app
const url = '/auth/login';
let params = 'userId=' + data.userId;
this.fetch(url, params);
}
/**
* This will sign out the user.
*/
signOut()
{
// user is leaving the app
const url = '/auth/logout';
let params = 'userId=' + data.userId;
if(!('sendBeacon' in window.navigator))
{
// normal ajax request here
this.fetch(url, params);
return;
}
// use a beacon for a more modern request the does not return a response
navigator.sendBeacon(url, new URLSearchParams(params));
}
}
I am writing a Firefox add-on and I need to be able to run some code after all the tabs have been loaded.
I tried something like:
window.addEventListener("load", function(e) {
gBrowser.addEventListener("load", function(ee) {
// code to run after all tabs have loaded
// thank user for installing my add-on
alert('Thank you for installing my add-on');
// add tab to my website
gBrowser.selectedTab = gBrowser.addTab("http://www.mywebsite.com/");
}, true);
}, false);
But this does not work because this will run the code for each tab after it is loaded. I want to wait until all of the tabs have loaded. I want to print an alert message when the Firefox restarts after the users installs my add-on. I also want to add a new tab to my website.
How do I do this?
I guess that you mean to wait until the session is restored when the browser starts up. There is a sessionstore-windows-restored notification sent out that you can listen to via observer service. Something like this:
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
var observer =
{
QueryInterface: XPCOMUtils.generateQI([Components.interfaces.nsIObserver]),
observe: function(subject, topic, data)
{
observerService.removeObserver(observer, "sessionstore-windows-restored");
addTabNow();
}
};
var observerService = Components.classes["#mozilla.org/observer-service;1"]
.getService(Components.interfaces.nsIObserverService);
observerService.addObserver(observer, "sessionstore-windows-restored", false);