Is it possible to migrate preferences from a Firefox XUL addon to an SDK addon? - firefox

I'm down to the (hopefully) last hurdle in the process of migrating our extension from XUL to Firefox SDK, but I've got one last sticking point:
Preferences.
There are a number of preferences set that simply MUST be migrated when the SDK version of the addon is installed over the top of the XUL addon. These preferences are not exposed to the end user for various reasons. The preference namespacing between the two architectures are completely different. For example -
A "version_number" preference in XUL is named arbitrarily by the developer, and appears as such in about:config :
my.preference.name
However, in SDK, they are scoped to the extension in question:
extensions.[extension ID].my.preference.name
Can preferences from XUL addons be migrated for re-use inside SDK addons? If so, how?

While it didn't seem possible to read from preferences outside the SDK addon's namespace, it WAS possible to write into the EXPECTED namespace in the old XUL extension. The solution we came up with was to publish a small, final point release of the old XUL addon with a small bit of extra logic responsible for carrying out this migration before we publish the new SDK version to AMO.
Here's a pseudocode representation of our approach:
ContentScript.js
function initNewFFInstallation() {
...
if (checkIsUpgrade()) {
var keys = getPrefKeys()
migratePrefs(keys);
}
}
Utils.js - acts as a bridge to expose Overlay functionality to the content script
Util.prototype.getPrefsBranch = function() {
return Components.classes["#mozilla.org/preferences-service;1"].
getService(Components.interfaces.nsIPrefService).
getBranch("my.prefs.ns.");
}
Util.prototype.getV2PrefsBranch = function() {
return Components.classes["#mozilla.org/preferences-service;1"].
getService(Components.interfaces.nsIPrefService).
getBranch("extensions.[SDK_ADDON_ID].");
}
Util.prototype.setBoolPref = function(key, val) {
this.getPrefsBranch().setBoolPref(key, val);
this.getPrefsBranch().setBoolPref(key, val);
}
Util.prototype.setCharPref = function(key, val) {
this.getPrefsBranch().setCharPref (key, val);
this.getV2PrefsBranch().setCharPref (key, val);
}
//copies all the preferences over
Util.prototype.migratePrefs = function(boolPrefKeys, charPrefKeys) {
boolPrefKeys.each(function (key) {
this.getV2PrefsBranch().setBoolPref(key, this.getPrefsBranch().getBoolPref(key));
});
charPrefKeys.forEach(function (key) {
this.getV2PrefsBranch().setCharPref(key, this.getPrefsBranch().getCharPref(key));
});
}
Then in our scriptcompiler.js, which actually injects the scripts onto the page, the util methods are hooked onto the SafeWindow object.
injectScript: function(script, unsafeContentWin) {
var safeWin=new XPCNativeWrapper(unsafeContentWin);
var sandbox=new Components.utils.Sandbox(safeWin, {"sandboxPrototype":safeWin});
sandbox.window=safeWin;
sandbox.document=sandbox.window.document;
sandbox.unsafeWindow=unsafeContentWin;
var util = new Util();
//...other APIs
sandbox.migratePreferences=app_gmCompiler.hitch(util , "migratePreferences");
try {
Components.utils.evalInSandbox("(function(){"+script+"})()", sandbox);
} catch (e) {
}
}

Related

Howto add a custom link provider

In the latest release of vscode (1__49), there is a code snippet on creating a new link provider. https://code.visualstudio.com/updates/v1_49. I can't seem to find a reference on where to apply this code.
window.registerTerminalLinkProvider({
provideTerminalLinks: (context, token) => {
// Detect the first instance of the word "test" if it exists and linkify it
const startIndex = (context.line as string).indexOf('test');
if (startIndex === -1) {
return [];
}
// Return an array of link results, this example only returns a single link
return [
{
startIndex,
length: 'test'.length,
tooltip: 'Show a notification',
// You can return data in this object to access inside handleTerminalLink
data: 'Example data'
}
];
},
handleTerminalLink: (link: any) => {
vscode.window.showInformationMessage(`Link activated (data = ${link.data})`);
}
});
What is the process for getting the editor to utilize this feature?
You will need to create a vscode extension that includes your code.
As it so happens, I have just set up a fresh extension that will use the TerminalLinkProvider. You can take a look at how the sample code integrates into a sample extension on GitHub.
A good place to start with your first extension is the official guide.
After that, just add your code to the activate(...) function of your extension.
You can built your extension as a .vsix file and install it in any vscode instance you use, but if you think that your code might be of value to others, consider publishing it!

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.

Using find bar routines programmatically causes find bar to appear

Update: It appears that the fix for bug 967982 is what's causing this. It would still be great to know either (a) how to work around this or (b) if there's an alternative way to find text in a given page.
One of my Firefox extensions programmatically uses the browser's find bar to locate text on a web page. In recent versions of Firefox, executing my add-ons code causes the find bar to appear when a search term is not found, something it didn't do previously. My routine looks like this:
// Reuse the find bar mechanisms in Firefox (we get a bunch of stuff for free that way)
FindInPage: function(term, e) {
var findBar = document.defaultView.gFindBar;
var shiftKey = e.shiftKey;
var findObj;
var cachedFindTerm;
if ("_find" in findBar) {
findObj = {
find: function(t) {
findBar._find(findBar._findField.value = t);
},
findNext: function() {
findBar._findAgain(false);
},
findPrevious: function() {
findBar._findAgain(true);
}
};
cachedFindTerm = gFindBar._findField.value;
} else {
findObj = findBar;
cachedFindTerm = getBrowser().findString;
}
if (cachedFindTerm == term) {
if(shiftKey)
findObj.findPrevious();
else
findObj.findNext();
} else {
findObj.find(term);
if(shiftKey)
findObj.findPrevious();
}
},
Is there some way I can prevent the find bar from appearing when this block gets executed? I'm aware that using private functions like this is not a best practice, but is there a better way to find a given word in a web page? Some sort of search API available to add-on authors that I'm not aware of?

Get Firefox to run XUL type script on startup

With Firefox 17.0.1 I am using an add-on called KeyConfig 20110522 to set some new hot keys and also set the acceltext of menuitems for my new keys as well as for add-ons that do not bother to do so.
I want the acceltext of the menuitems to be set when Firefox starts, but currently I am just using a hot key to execute the following code against the UI via KeyConfig:
document.getElementById("tabmix-menu")
.setAttribute("acceltext","Alt+Ctrl+Shift+T");
// more of the same...
I need a couple of beginners tips:
How can I execute arbitrary code against the UI in the same way as I execute against an HTML page via the console?
Is there a sneaky way to get a clump of code to execute on browser start-up without delving into XUL development?
Is there a way to trace commands executed against the UI so I can get at command calls instead of using triggers when I set my hot keys like so:
document.getElementById("tabmix-menu").click();
Any other tips on this type of low-level hacking would also be welcome.
You can execute arbitrary code against the Firefox UI from an addon, but as you say, doing all the XUL related stuff is a bit boring :-)
Enter "Bootstrapped" extensions!
Part 1:
A "Bootstrapped" (or re-startless) extension needs only an install.rdf file to identify the addon, and a bootstrap.js file to implement the bootstrap interface.
Bootstrapped Extension: https://developer.mozilla.org/en-US/docs/Extensions/Bootstrapped_extensions
Good example: http://blog.fpmurphy.com/2011/02/firefox-4-restartless-add-ons.html
The bootstrap interface can be implemented very simply:
function install() {}
function uninstall() {}
function shutdown(data, reason) {}
function startup(data, reason) { /* YOUR ARBITRARY CODE HERE! */ }
You compile the extension by putting install.rdf and bootstrap.js into the top-level of a new zip file, and rename the zip file extension to .xpi.
Part 2:
Your code is privileged and can use any of the Mozilla platform APIs. There is however an issue of timing. The moment-in-time at which the "startup" function is executed is one at which no Chrome window objects exist yet!
If it's important for your code that you have a Chrome Window, we need to wait for it to appear:
// useful services.
Cu.import("resource://gre/modules/Services.jsm");
var loader = Cc["#mozilla.org/moz/jssubscript-loader;1"]
.getService(Ci.mozIJSSubScriptLoader);
var wmSvc = Cc["#mozilla.org/appshell/window-mediator;1"]
.getService(Ci.nsIWindowMediator);
var logSvc = Cc["#mozilla.org/consoleservice;1"]
.getService(Ci.nsIConsoleService);
// get the first gBrowser
var done_startup = 0;
var windowListener;
function do_startup(win) {
if (done_startup) return;
done_startup = 1;
wmSvc.removeListener(windowListener);
var browserEnum = wmSvc.getEnumerator("navigator:browser");
var browserWin = browserEnum.getNext();
var tabbrowser = browserWin.gBrowser;
/* your code goes here! */
}
// window listener implementation
windowListener = {
onWindowTitleChange: function(aWindow, aTitle) {},
onCloseWindow: function(aWindow) {},
onOpenWindow: function(aWindow) {
var win = aWindow.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIDOMWindowInternal || Ci.nsIDOMWindow);
win.addEventListener("load", function(aEvent) {
win.removeEventListener("load", arguments.callee, false);
if (aEvent.originalTarget.nodeName != "#document") return;
do_startup();
}
};
// CODE ENTRY POINT (put this in bootstrap "startup" function)
wmSvc.addListener(windowListener);

Ajax call: What is the difference between new ActiveXObject("Msxml2.XMLHTTP") and new ActiveXObject("Microsoft.XMLHTTP")?

I hope both the object invocations are referring to the ActiveXObject.
But why are we passing two different parameters to work in IE.
1. Msxml2.XMLHTTP and
2. Microsoft.XMLHTTP
Are they both same ? Or Are they browser dependent(IE7 and IE8) ?
I used both. I did not get any exception. Both are looking same for me. I am using IE 8.
Both are actually outdated. There are various versions of Microsoft's venerable MSXML ActiveX object (I believe the last one was version 5.0 and came with some version of Office.) The versions have minor differences in behavior, and bug fixes that usually don't come into play in AJAX scenarios.
Starting with IE7, Microsoft supported the standardized "XmlHttpRequest" object that other modern browsers had adopted. See http://msdn.microsoft.com/en-us/library/ms537505(VS.85).aspx. You should definitely be using that as IE7 is now the de-facto lowest common denominator. IE6 has been declared dead by most major organizations, so there's no reason to support the old Microsoft-specific ActiveX ProgIDs.
And of course, there is very little reason these days to roll your own AJAX calls, as libraries like jQuery and ASP.NET Ajax do it for you, abstracting away these obscure browser quirks. I would strongly suggest learning one of those libraries.
Jordan Rieger
jquery (at least 1.4.2) has problem on $.ajax() calling. It makes great memory leakage (like fountain)
tragedy code:
if ( window.ActiveXObject ) {
jQuery.ajaxSettings.xhr = function() {
if ( window.location.protocol !== "file:" ) {
try {
return new window.XMLHttpRequest();
} catch(xhrError) {}
}
try {
return new window.ActiveXObject("Microsoft.XMLHTTP");
} catch(activeError) {}
};
}
resolution:
if ( window.ActiveXObject ) {
jQuery.ajaxSettings.xhr = function() {
if ( window.location.protocol !== "file:" ) {
if ( window.ActiveXObject ) {
try {
return new window.ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
try {
return new window.XMLHttpRequest();
} catch(xhrError) {}
}
try {
return new window.ActiveXObject("Microsoft.XMLHTTP");
} catch(activeError) {}
};
}

Resources