Firefox addon - monitoring network - firefox-addon

If I add an nsIHttpChannel observer, is there any way I can know what initiated the HTTP request(script, iframe, image etc..)
In chrome when monitoring the network from the background page you have the request type telling you if it came from an iframe, script etc...

Don't accept this as solution yet. I hope some other people can come and help build this solution.
I know this is for sure correct:
TEST FOR: XHR - identify XHR (ajax) response while listening to http response in firefox addon
Get load context of request (like which tab, which html window, which xul window) - Firefox add-on pageMod, catch ajax done in contentScriptFile (this is marked as optional though in the code below it requires a helper function: https://gist.github.com/Noitidart/644494bdc26f996739ef )
This I think is correct, by this i mean it works in my test cases but I'm not sure if its the recommended way:
TEST FOR: Frame or full page load - Can we differentiate between frame and non-frame loads with Ci in firefox addon
This I don't know how to do so I need help from community on this:
TEST FOR image - Comment on "identify XHR (ajax) response while listening to http response in firefox addon"
Image detection can be done through the MIME type. Check channel.contentType
Solution in progress:
var myobserve = function(aSubject, aTopic, aData) {
var httpChannel = aSubject.QueryInterface(Ci.nsIHttpChannel);
//start - test if xhr
var isXHR;
try {
var callbacks = httpChannel.notificationCallbacks;
var xhr = callbacks ? callbacks.getInterface(Ci.nsIXMLHttpRequest) : null;
isXHR = !!xhr;
} catch (e) {
isXHR = false;
}
//end - test if xhr
//start - test if frame OR full page load
var isFrameLoad;
var isFullPageLoad;
if (httpChannel.loadFlags & Ci.nsIHttpChannel.LOAD_INITIAL_DOCUMENT_URI) {
isFullPageLoad = true;
isFrameLoad = false;
} else if (httpChannel.loadFlags & Ci.nsIHttpChannel.LOAD_DOCUMENT_URI) {
isFrameLoad = true;
isFullPageLoad = false;
}
//end - test if frame OR full page load
//start - test if image
var isImg;
var isCss;
var isJs;
var isAudio;
//can keep going here
var mimeType = httpChannel.contentType;
if (/^image/i.test(mimeType)) {
isImg = true;
}
if (/^audio/i.test(mimeType)) {
isAudio = true;
}
if (/\/css$/i.test(mimeType)) {
isCss = true;
}
if (/\/js$/i.test(mimeType)) {
isJs = true;
}
//end - test if image
//start - OPTIONAL use loadContext to get a bunch of good stuff
//must paste the function from here: https://gist.github.com/Noitidart/644494bdc26f996739ef somewhere in your code
var goodies = loadContextAndGoodies(aSubject, true);
/*
//goodies is an object that holds the following information:
var goodies = {
loadContext: loadContext,
DOMWindow: DOMWindow,
gBrowser: gBrowser,
contentWindow: contentWindow,
browser: browser,
tab: tab
};
*/
// test if resource (such as image, or whatever) is being loaded is going into a frame [can also be used as altnerative way to test if frame load or full page]
var itemDestinationIsFrame;
var itemDestinationIsTopWin;
if (goodies.contentWindow) {
if (goodies.contentWindow.frameElement) {
itemDestinationIsFrame = true;
itemDestinationIsTopWin = false;
} else {
itemDestinationIsFrame = false;
itemDestinationIsTopWin = true;
}
}
//end - OPTIONAL use loadContext to get a bunch of good stuff
}
Of course to start observing:
Services.obs.addObserver(myobserve, 'http-on-modify-request', false);
and to stop:
Services.obs.removeObserver(myobserve, 'http-on-modify-request', false);
To start observing
To start start obseving all requests do this (for example on startup of your addon)
for (var o in observers) {
observers[o].reg();
}
To stop observing
Its important to stop observring (make sure to run this at least on shutdown of addon, you dont want to leave the observer registered for memory reasons)
for (var o in observers) {
observers[o].unreg();
}

Related

Cloudflare service worker code to "Bypass cache on cookie" not working

I wrote this code as a Cloudflare Service Worker which is meant to precisely emulate their native function for "Bypass cache on cookie". Specifically, if someone has a Wordpress cookie - it would bypass cache, otherwise it does not.
It does not seem to function at all - in that despite having a cookie and being logged in (confirmed via Chrome developer tools) - I still get a Cloudflare cache HIT on this example domain - Tallyfy. Anything wrong with it? Help appreciated!
// A Service Worker which skips cache if the request contains a cookie.
addEventListener('fetch', event => {
let request = event.request;
var flag=false;
if(request.headers.cookie) {
var pairs = request.headers.cookie.split(";");
var patt = new RegExp("wp-.*|wordpress.*|comment_.*|woocommerce_.*")
for(var i=0;i<pairs.length;i++){
if(patt.test(pairs[i])){
flag = true;
break;
}
}
}
if (request.headers.has('Cookie') && flag) {
// Cookie present. Add Cache-Control: no-cache.
let newHeaders = new Headers(request.headers)
newHeaders.set('Cache-Control', 'no-cache')
event.respondWith(fetch(request, {headers: newHeaders}))
}
// Use default behavior.
return
})
try this and let me know
addEventListener('fetch', event => {
let request = event.request
var flag = false;
if (request.headers.has('Cookie')) {
var cookie = request.headers.get('Cookie');
pairs = cookie.split(";");
var patt = new RegExp("wordpress_logged_in.*|wp_woocommerce_session.*");
for(var i=0;i<pairs.length;i++){
if(patt.test(pairs[i])){
flag = true;
break;
}
}
console.log(flag);
if (request.headers.has('Cookie') && flag) {
let newHeaders = new Headers(request.headers)
newHeaders.set('Cache-Control', 'no-cache')
newHeaders.set('Pragma', 'no-cache')
event.respondWith(fetch(request, {headers: newHeaders}))
}
// Use default behavior.
return;
}
})

Firefox SDK: How to make trigger for certain domain

I need to catch requests on sites with URLs *.net and take some actions (stop request and put HTML code from disk, but this I can do). How do I catch these requests?
I tried to use progress listeners, but something is wrong:
const STATE_START = Ci.nsIWebProgressListener.STATE_START;
var myListener = {
QueryInterface: XPCOMUtils.generateQI(["nsIWebProgressListener",
"nsISupportsWeakReference"]),
onStateChange: function(aWebProgress, aRequest, aFlag, aStatus) {
if (aFlag & STATE_START) {
// actions
}
}
use nsIHTTPChannel and observer service. copy paste it. however .net can be included in resources like javascript things, if you want to test if its specfically a window you have to check for some load flags of LOAD_INITIAL_DOCUMENT_URI, also will want to chec
Cu.import('resource://gre/modules/Services.jsm');
var httpRequestObserver = {
observe: function (subject, topic, data) {
var httpChannel, requestURL;
if (topic == "http-on-modify-request") {
httpChannel = subject.QueryInterface(Ci.nsIHttpChannel);
requestURL = httpChannel.URI.spec;
var newRequestURL, i;
if (httpChannel.loadFlags & httpChannel.LOAD_INITIAL_DOCUMENT_URI) {
//ok continue because loadFlags is a document
} else {
//its not a document, probably a resource like a js file image or css or something, but maybe could be ajax call
return;
}
if (requestURL.indexOf('.net')) {
var goodies = loadContextGoodies(httpChannel);
if (goodies) {
httpChannel.cancel(Cr.NS_BINDING_ABORTED);
goodies.contentWindow.location = self.data.url('pages/test.html');
} else {
//dont do anything as there is no contentWindow associated with the httpChannel, liekly a google ad is loading or some ajax call or something, so this is not an error
}
}
return;
}
}
};
Services.obs.addObserver(httpRequestObserver, "http-on-modify-request", false);
//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';
if (aTab == null) {
return null;
}
else {
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
}

How to create a "loading" spinner in Breeze?

I'm trying to create a loading spinner that will be displayed when breeze is communicating with the server. Is there some property in Breeze that is 'true' only when breeze is sending data to the server, receiving data, or waiting for a response (e.g. after an async call has been made but no response yet)? I thought of binding this data to a knockout observable and binding the spinner to this observable,
Thanks,
Elior
Use spin.js
http://fgnass.github.io/spin.js/
Its so simple..make it visible before you execute the query and disable it after the query succeeds or fails.
I don't see any property that is set or observable while Breeze is querying, but if you are using a datacontext, or some JavaScript module for your data calls, this is what you can do -
EDIT
Taking John's comments into account, I added a token'd way of tracking each query.
var activeQueries = ko.observableArray();
var isQuerying = ko.computed(function () {
return activeQueries().length !== 0;
});
var toggleQuery = function (token) {
if (activeQueries.indexOf(token) === -1)
{ activeQueries.push(token); }
else { activeQueries.remove(token); }
};
var getProducts = function (productsObservable, forceRemote) {
// Don't toggle if you aren't getting it remotely since this is synchronous
if (!forceRemote) {
var p = getLocal('Products', 'Product','product_id');
if (p.length > 0) {
productsObservable(p);
return Q.resolve();
}
}
// Create a token and toggle it
var token = 'products' + new Date().getTime();
toggleQuery(token);
var query = breeze.EntityQuery
.from("Products");
return manager.executeQuery(query).then(querySucceeded).fail(queryFailed);
function querySucceeded(data) {
var s = data.results;
log('Retrieved [Products] from remote data source', s, true);
// Toggle it off
toggleQuery(token);
return productsObservable(s);
}
};
You will need to make sure all of your fail logic toggles the query as well.
Then in your view where you want to place the spinner
var spinnerState = ko.computed(function () {
datacontext.isQuerying();
};

How to open the page in browser at the time of uninstalling the firefox addon

I want to open the link when the user uninstalls the addon, so for this what i have to code and under which event.
If anybody know about this then please help me out.
Currently this is what I am doing at the time of uninstall. But gBrowser.addTab(Website + 'uninstalled=true&token=' + uniqueguid); is not working over here.
var UninstallObserver = {
_uninstall : false,
observe : function(subject, topic, data) {
//===Write Code here for Delete File Uninsatll Time
//alert("Uninstall Time Delete File");
var Filename = "webmail";
// Delete all template file.
try{
var pref = Components.classes["#mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
var finished = "";
pref.setBoolPref("myextension.install.just_installed", false);
}
catch(e) {}
gBrowser.addTab(Website + 'uninstalled=true&token=' + uniqueguid);
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+"\\DefaultTemplate.txt");
if ( file.exists() == true )
{
var aFile = Components.classes["#mozilla.org/file/local;1"].createInstance();
if (aFile instanceof Components.interfaces.nsILocalFile)
{
aFile.initWithPath(Components.classes["#mozilla.org/file/directory_service;1"].getService( Components.interfaces.nsIProperties).get("ProfD", Components.interfaces.nsIFile).path + "\\DefaultTemplate.txt");
aFile.remove(false);
}
}
//=======
if (topic == "em-action-requested") {
subject.QueryInterface(Components.interfaces.nsIUpdateItem);
if (subject.id == MY_EXTENSION_UUID)
{
if (data == "item-uninstalled")
{
//==Delete File Whenever Uninstall
//alert("When Uninatall");
//===========
data = "item-cancel-action";
this._uninstall = true;
}
if (data == "disabled")
{
// alert("You are not allow to disable SysLocker.");
this._uninstall = true;
}
else if (data == "item-cancel-action")
{
this._uninstall = false;
}
}
}
else if (topic == "quit-application-granted")
{
data = "item-cancel-action";
if (this._uninstall)
{
//Code here to delete registry
}
this.unregister();
}
},
register : function() {
var observerService =
Components.classes["#mozilla.org/observer-service;1"].
getService(Components.interfaces.nsIObserverService);
observerService.addObserver(this, "em-action-requested", false);
observerService.addObserver(this, "quit-application-granted", false);
},
unregister : function() {
var observerService =
Components.classes["#mozilla.org/observer-service;1"].
getService(Components.interfaces.nsIObserverService);
observerService.removeObserver(this,"em-action-requested");
observerService.removeObserver(this,"quit-application-granted");
}
}
Thanks
0) What kind of extension is this? I assume it's a regular extension requiring restart; bootstrapped (restartless) extensions have their own uninstall notification.
1) Per the MDC docs, the em-action-requested notification was replaced with a different notification in Firefox 4+, are you testing with Firefox 4 or 3.6?
2) How exactly is gBrowser.addTab "not working over here"? Does the code get to that point? Do you get any messages in the Error Console (see that page for set up tips)? If you put your code in an XPCOM component (which is correct), you'll first have to get a reference to a browser window. See Working with windows in chrome code.
I don't think that the em-action-requested topic is posted to observers until the extension is actually uninstalled, which happens on restart (assuming it is not a restartless extension). When are you expecting the new tab to appear? I would try setting a pref when the uninstall topic is triggered and checking for that pref on startup. If it is there, you can display your tab and remove the pref.

How to get images from cache using a XPCOM Component in Firefox

I need to get the cache file path for ever image loaded in a document, I am wondering what are the Interfaces I need to use in order to do that
https://developer.mozilla.org/en/XPCOM_Interface_Reference
This is what I used to evict cache entry:
function removeItem(url){
let cacheService = Components.classes["#mozilla.org/network/cache-service;1"]
.getService(Components.interfaces.nsICacheService);
var Ci = Components.interfaces;
var session = cacheService.createSession("image", Ci.nsICache.STORE_ANYWHERE, false);
if(!session){
return;
}
var entry;
try{
entry = session.openCacheEntry(url, Ci.nsICache.ACCESS_READ, false);
if(!entry){
return;
}
}catch(ex){
return;
}
entry.doom();
entry.close();
}
}
Once you have entry you should be able to open a stream to it - possibly getting the content or even replacing it - I haven't tried it though.

Resources