Getting nsIChannel request's nsIDOMWindow always returns null on e10s - firefox

I have an observer on "http-on-modify-request" and I need to get the DOMWindow that request is associated with.
The following code was taken from AdBlock Plus and is based on this article.
function getRequestWindow(/**nsIChannel*/ channel) /**nsIDOMWindow*/
{
try
{
if (channel.notificationCallbacks)
return channel.notificationCallbacks.getInterface(Ci.nsILoadContext).associatedWindow;
} catch(e) {}
try
{
if (channel.loadGroup && channel.loadGroup.notificationCallbacks)
return channel.loadGroup.notificationCallbacks.getInterface(Ci.nsILoadContext).associatedWindow;
} catch(e) {}
return null;
}
However, this code is no longer working on multiprocess Firefox (v36+, right now on Firefox Nightly).
Any ideas?

I haven't tried that myself, so take with a grain of salt:
Instead of getting the nsIDOMWindow itself from the channel you can get the innerWindowId from the nsIChannel.loadInfo. The window id can then be resolved inside a frame script by QueryInterfaceing to nsIDOMWindowUtils.

To talk to content, the recommended path for this sort of use case is probably Frame Scripts, see this documentation on MDN for more.

Related

How to implement message passing callbacks in an all-in-one (Edge/Firefox/Chrome) browser extension's content script?

Development Environment OS: Windows 7 Enterprise LTS
Browser compatibility minimum requirements: Should support all Edge, Firefox, Chrome browsers, as of 2018.
Current ongoing issue: Unable to run VM on dev workstation; Cannot run Windows 10 VMs to debug Microsoft Edge extensions.
To explain:
An "all-in-one browser extension" refers to a browser extension code that uses the same code with minor differences to work on various WebExtensions / Chrome Extensions supported browsers. At bare minimum, the same codebase should work and run on Edge, Firefox, and Chrome with very minor changes.
Callbacks on the content scripts for Edge/Firefox/Chrome extensions are handled differently.
For unknown reasons, I cannot run VM on my workstation machine. When VM is running, VM client is black. This is a localized issue on my end that I cannot resolve, so I'm forced to find a different solution/alternative.
How are they handled differently on the content scripts:
Edge: browser.runtime.sendMessage uses callbacks, and returns undefined.
Firefox: browser.runtime.sendMessage uses Promises, and returns a Promise.
Chrome: chrome.runtime.sendMessage uses callbacks, and returns undefined.
According to various references:
Firefox / Chrome / MS Edge extensions using chrome.* or browser.*
https://www.smashingmagazine.com/2017/04/browser-extension-edge-chrome-firefox-opera-brave-vivaldi/
On the content scripts, you can declare the following JavaScript snippet at the top in order to create a global variable that can be referenced everywhere else:
//Global "browser" namespace definition.
window.browser = (function() {
return window.msBrowser || window.browser || window.chrome;
})();
Unfortunately, because of the issue I'm experiencing (VM not running), I cannot tell if window.msBrowser is still being used. And this solution is not helpful for me when handling message callbacks when using namespace.runtime.sendMessage.
With all that said, my main question is: How to write a message passing function that can handle callbacks properly?
Currently, I'm using the following code:
function sendGlobalMessage(messageRequest, callback) {
if (chrome && window.openDatabase) {
//This is Chrome browser
chrome.runtime.sendMessage(messageRequest, callback);
}
else if (browser) {
try {
//Edge will error out because of a quirk in Edge IndexedDB implementation.
//See https://gist.github.com/nolanlawson/a841ee23436410f37168
let db = window.indexedDB.open("edge", (Math.pow(2, 30) + 1));
db.onerror = function(e) {
throw new Error("edge is found");
};
db.onsuccess = function(e) {
//This is Firefox browser.
browser.runtime.sendMessage(messageRequest).then(callback);
};
}
catch (e) {
//This is Edge browser
browser.runtime.sendMessage(messageRequest, callback);
}
}
}
I truly felt this is a hacky solution, because the code is based off of browser platform exclusive quirks in order to separate chrome.runtime.sendMessage and browser.runtime.sendMessage API calls, so as to handle callbacks in their respective platforms. I really wanted to change this.
So I'm asking what better ways are there, out there, that is useful to detect the different platforms, and handle message passing callbacks properly at the same time?
Thanks in advance.
I believed I solved it.
EDIT: The FINAL final version (updated and more stable, less message passing):
//Global "browser" namespace definition, defined as "namespace". Can be renamed to anything else.
window.namespace = (function() {
return window.browser || window.chrome;
})();
function sendGlobalResponse(message, callback){
if (window.namespace === window.chrome) {
//Chrome
window.namespace.runtime.sendMessage(message, callback);
}
else if (window.namespace === window.browser) {
//Using instanceof to check for object type, and use the returned evaluation as a truthy value.
let supportPromises = false;
try {
supportPromises = window.namespace.runtime.getPlatformInfo() instanceof Promise;
}
catch(e) { }
if (supportPromises){
//Firefox
window.namespace.runtime.sendMessage(message).then(callback);
}
else {
//Edge
window.namespace.runtime.sendMessage(message, callback);
}
}
}
(Original Post):
The final version (Now obsoleted):
//Global "browser" namespace definition.
window.namespace = (function() {
return window.browser || window.chrome;
})();
function sendGlobalResponse(message, callback){
if (window.namespace === window.chrome) {
//Chrome
window.namespace.runtime.sendMessage(message, callback);
}
else if (window.namespace === window.browser) {
let returnValue = window.namespace.runtime.sendMessage({});
if (typeof returnValue === "undefined"){
//Edge
window.namespace.runtime.sendMessage(message, callback);
}
else {
//Firefox
window.namespace.runtime.sendMessage(message).then(callback);
}
}
}
In the second if statement, by checking to see if the return value of a window.browser.runtime.sendMessage is a Promise or undefined, we can detect if the platform is Firefox or Edge.
I think this is the only solution to handle message passing callbacks/message responses on the content scripts.
I really couldn't think of a better solution than this. So I'll be using this from now on.
But if anyone else knows a better way, a way where you don't need to send out 1 extra dummy message for Firefox and Edge per function call, that would be great!
It sucks that anything inside the content script is not persistent, and even if you store information about what platform the code is being run on, you still have to fetch the information from the background script before filtering out which runtime.sendMessage function to call on, so it doesn't really save much time.

UmbrellaException which contains ClassCastException when using GWTBootstrap3 Extras Summernote event handling (KeyUp Event)

I try to handle a Summernote Keyup event with this:
myEditor.addSummernoteKeyUpHandler(new SummernoteKeyUpHandler() {
#Override
public void onSummernoteKeyUp(final SummernoteKeyUpEvent event) {
// TODO Auto-generated method stub
log.fine("hello");
}
});
I get a UmbrellaException which is IMHO a class cast exception.
This is the call stack
I identified the following spot where te cast failes:
#HasNoSideEffects
static native boolean canCast(Object src, JavaScriptObject dstId) /*-{
if (#com.google.gwt.lang.Cast::instanceOfString(*)(src)) {
return !!#com.google.gwt.lang.Cast::stringCastMap[dstId];
} else if (src.#java.lang.Object::castableTypeMap) {
return !!src.#java.lang.Object::castableTypeMap[dstId]; //<-- this returns false!!!
} else if (#com.google.gwt.lang.Cast::instanceOfDouble(*)(src)) {
return !!#com.google.gwt.lang.Cast::doubleCastMap[dstId];
} else if (#com.google.gwt.lang.Cast::instanceOfBoolean(*)(src)) {
return !!#com.google.gwt.lang.Cast::booleanCastMap[dstId];
}
return false;
}-*/;
dstId contains:
Any help greatly appreciated!
I tested this with a small demo which actually works. But in my large application, I get this exception and I don't see why.
Do you have any idea whats wrong here?
Best regards
Hannes
As Andrei suggested I set the style to DETAILED. I use Eclipse as a development environment. I decided to clean build the system (which I had done before). Now the problem has simply vanished !! Furthermore, I use SDBG (see: https://sdbg.github.io/) to debug my GWT application. This works pretty well (even without -style DETAILED). Now the very very strange thing remains. I can set breakpoints for my application and they all work well, except setting a breakpoint within the event handling method. I use a logger to print some text to the console, so I see that the event handler for summernote is actually called but the debugger will not stop. I checked whether the breakpoint is listed in the tab "Breakpoints" and it is and it is checked. I don't get it. Perhaps I have to rebuild all again.
But to keep long things short:
The solution to the problem is probably to really issue a clean build and then hope for the best.

GoogleUser.getAuthResponse() doesn't contain access_token

UPDATE2: I revisited this issue and have solved the problem by carefully following the doco linked below. But first, for those who are struggling with this, you are in good company. There are so many versions of the doco from Google it is confusing! Do you include platform.js or client.js in your html? Do you load gapi.auth or gapi.auth2? Do you use gapi.auth2.render or gapi.auth.authorize, or gapi.auth2.init, and so on.
The way that returns an access_token (as of this article date) is linked below. I managed to get this working by carefully following the guide and reference using platform.js. Other libraries are then dynamically loaded such as client.js using gapi.load('drive', callback).
https://developers.google.com/identity/sign-in/web/listeners
https://developers.google.com/identity/sign-in/web/reference
==== ORIGINAL ISSUE FOR PROSPERITY ====
UPDATE 1:
I've updated the code sample to do a recursive search of the googleUser object. At least this shouldn't break in a subsequent library.
Below is a code snippet to handle an issue where the access_token in the Google gapi.auth2.AuthResponse object is not at the top level... it is hidden :( in the depths of the object!
So it is retrievable, but not at the top level!!?? I've noticed it seems to be a timing issue... once the application is running for a while on subsequent checks, it does contain the access token at the top level!!
var authResponse = _.googleUser.getAuthResponse();
_.id_token = authResponse.id_token; // Always exists
// access_token should also be a param of authResponse
if (authResponse.access_token) {
debug("Worked this time?");
_.access_token = authResponse.access_token;
} else {
// !!! Internal object access !!!
debug("Attempt to get access token from base object.");
_.access_token = _.objRecursiveSearch("access_token", _.googleUser);
if (_.access_token) {
debug("Access token wasn't on authResponse but was on the base object, WTF?");
} else {
debug("Unable to retrieve access token.");
return false;
}
}
_.objRecursiveSearch = function(_for, _in) {
var r;
for (var p in _in) {
if (p === _for) {
return _in[p];
}
if (typeof _in[p] === 'object') {
if ((r = _.objRecursiveSearch(_for, _in[p])) !== null) {
return r;
}
}
}
return null;
}
I'm guessing getAuthResponse somehow provides a callback once it is ready, but I can't see where in the API.
https://developers.google.com/identity/sign-in/web/reference
I know this question is fairly old, but it appears first when googling for ".getAuthResponse() doesn't have access_token," which is how I got here.
So for those of you in 2016 (and maybe later) here's what I have found out
There's a secret argument on .getAuthResponse, not documented anywhere I have found. If you would run the following in your app
console.log(gapi.auth2.getAuthInstance().currentUser.get().getAuthResponse);
You would see that you get the following (copy/pasted from my console)
function (a){if(a)return this.hg;a=.HE;var c=.rf(this.hg);!a.Ph||a.dL||a.Lg||(delete c.access_token,delete c.scope);return c}
This shows that the .getAuthResponse() function looks for an argument, and as far as I can tell doesn't even check its value -- it simply checks if it is there and then returns the whole object. Without that function, the rest of the code runs and we can see very clearly it is deleting two keys: access_token and scope.
Now, if we call this function with and without the argument, we can check the difference in the output. (note: I used JSON.stringify because trying to copy/paste the object from my browser console was causing me some issues).
console.log(JSON.stringify(gapi.auth2.getAuthInstance().currentUser.get().getAuthResponse()));
console.log(JSON.stringify(gapi.auth2.getAuthInstance().currentUser.get().getAuthResponse(true)));
getAuthResponse() object
{
"token_type":"Bearer",
"login_hint":"<Huge mess of letters>",
"expires_in":2112,
"id_token":"<insert your ridiculously long string here>",...}
getAuthResponse(true) object
{
"token_type":"Bearer",
"access_token":"<an actual access token goes here>",
"scope":"<whatever scopes you have authorized>",
"login_hint":"<another mess of letters>",
"expires_in":2112,
"id_token":"<Insert your ridiculously long string here>",
...}
Figured out the fix for this. Turns out that if we don't provide the login scope config in gapi.auth2.init it doesn't return access_token in getAuthResponse. Please call gapi.auth2.init as given below and access_token will be present.
gapi.auth2.init({
client_id: <googleClientID>,
'scope': 'https://www.googleapis.com/auth/plus.login'
})

Mozilla reload API method doesn't work

I try to reload a Web page using (JavaXPCOM):
nsIWebBrowser webBrowser = (nsIWebBrowser) browser
.getWebBrowser();
nsIWebNavigation webNavigation = (nsIWebNavigation) webBrowser.queryInterface(nsIWebNavigation.NS_IWEBNAVIGATION_IID);
try {
nsISHistory sessionHistory = webNavigation.getSessionHistory();
if (sessionHistory != null) {
webNavigation = (nsIWebNavigation) sessionHistory.queryInterface(nsIWebNavigation.NS_IWEBNAVIGATION_IID);
}
} catch (XPCOMException e) {
}
webNavigation.reload(nsIWebNavigation.LOAD_FLAGS_NONE);
But reload doesn't happen at all. I tried force it by using the following flags, but page doesn't refresh as well:
nsIWebNavigation.LOAD_FLAGS_BYPASS_PROXY|nsIWebNavigation.LOAD_FLAGS_BYPASS_CACHE
Anyone knows what can be the reason for that?
Thanks!
Did you try checking Error Console for syntax errors? You seem to be trying to use C++ type casts in JavaScript. That cannot work. Assuming that browser is a <browser> element, this should work:
browser.reload();
Or:
browser.reloadWithFlags(Components.interfaces.nsIWebNavigation.LOAD_FLAGS_BYPASS_PROXY|Components.interfaces.nsIWebNavigation.LOAD_FLAGS_BYPASS_CACHE);
See https://developer.mozilla.org/en/XUL/browser for documentation on the <browser> element.
Edit: Given that this is apparently using JavaXPCOM the code seems to be correct with the exception that the entire try .. catch block should be removed. The only flag should be LOAD_FLAGS_BYPASS_CACHE to make sure you don't get a cached response.

Extjs store.on('save', afterSave(resp));

I have a simple ExtJs (3.4) Grid with a Writer. When the user makes some changes the store is saved to the server as follows:
store.on('save', afterSave(resp));
All is fine. However, I want to get a response as to wheather the record has been saved successfully, failed or an update conflict happed. How to best do this?
Are you using Ext.data.proxy.Ajax to load your stores? If so, you can use the reader property to evaluate and handle the server responses.
Another option would be to make AJAX called directly and handle the responses from there as well
I used exception listener to parse the data as suggested here. But, is this the right way to do this.
Ext.data.DataProxy.addListener('exception', function(proxy, type, action,
options, res) {
if (type == 'response') {
var success = Ext.util.JSON.decode(res.responseText).success;
if (success) {
console.log('UPDATE OK');
} else {
console.log('UPDATE FAILED');
}
}
});

Resources