I'm trying to write an addon for a certain file type, and I would like to add an "Send to MyAddonName" option to the download file dialog, under the "Open with" and "Save file" options. Not referring to the Download Manager.
Is there any way to achieve this using the Firefox Addon SDK? This is my first extension so I am not extremely familiar with the SDK or the more advanced XUL addons.
I'm not sure how to do this with addon sdk. But this is how i would do it from a bootstrap addon.
I would use Services.wm.addEventListener to add this and listen to window load of chrome://mozapps/content/downloads/unknownContentType.xul
var windowListener = {
//DO NOT EDIT HERE
onOpenWindow: function(aXULWindow) {
// Wait for the window to finish loading
let aDOMWindow = aXULWindow.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowInternal || Ci.nsIDOMWindow);
aDOMWindow.addEventListener('load', function() {
aDOMWindow.removeEventListener('load', arguments.callee, false);
windowListener.loadIntoWindow(aDOMWindow);
}, false);
},
onCloseWindow: function(aXULWindow) {},
onWindowTitleChange: function(aXULWindow, aNewTitle) {},
register: function() {
// Load into any existing windows
let DOMWindows = Services.wm.getEnumerator(null);
while (DOMWindows.hasMoreElements()) {
let aDOMWindow = DOMWindows.getNext();
windowListener.loadIntoWindow(aDOMWindow);
}
// Listen to new windows
Services.wm.addListener(windowListener);
registered = true;
},
unregister: function() {
// Unload from any existing windows
let DOMWindows = Services.wm.getEnumerator(null);
while (DOMWindows.hasMoreElements()) {
let aDOMWindow = DOMWindows.getNext();
windowListener.unloadFromWindow(aDOMWindow);
}
for (var u in unloaders) {
unloaders[u]();
}
//Stop listening so future added windows dont get this attached
Services.wm.removeListener(windowListener);
},
//END - DO NOT EDIT HERE
loadIntoWindow: function(aDOMWindow) {
if (!aDOMWindow) {
return;
}
if (aDOMWindow.location == 'chrome://mozapps/content/downloads/unknownContentType.xul'); {
//check file type
var fileName = aDOMWindow.document.getElementById('location').value;
var fileType = fileName.substr(fileName.lastIndexOf('.'));
if (fileType == 'zip') {
var myxul = document.createElementNS('xul namescpae here look it up', 'element you want');
aDOMWindow.document.insertBefore(elementToInsertBefore, myXul);
}
}
},
unloadFromWindow: function(aDOMWindow) {
if (!aDOMWindow) {
return;
}
}
}
};
Related
I am currently facing an issue where I have event listeners running for my client's website which track all hover and clicks on the website. We have 4 clients and our code works fine on 3 of them but it does not work correctly on the 1 client's website.
We are running the following code when a click is triggered:
async function objectClick(obj) {
var tag = obj.target;
if (tag.nodeName == 'IMG') {
objectName = tag.src;
} else {
objectName = tag.innerText || tag.textContent || tag.value;
}
var data_tag = tag.getAttribute("data-*");
if (data_tag != null) {
if (data_tag.includes("abc")) {
var layout = JSON.parse(window.localStorage.getItem(page));
layout.ctr = 1;
window.localStorage.setItem(page, JSON.stringify(layout))
await sendToHistory(uid, url, JSON.stringify(layout));
} else if (data_tag.includes("reward")) {
var layout = JSON.parse(window.localStorage.getItem(page));
layout.reward = 1;
window.localStorage.setItem(page, JSON.stringify(layout))
await sendToHistory(uid, url, JSON.stringify(layout));
}
}
if (data_tag === "abc" || data_tag === "reward") {
await sendToJourney(uid, "Clicked", -1, tag.nodeName, JSON.stringify({ text: objectName, data_nostra: null }), url, page);
} else {
await sendToJourney(uid, "Clicked", -1, tag.nodeName, JSON.stringify({ text: objectName, data_nostra: data_nostra_tag }), url, page);
}
}
For most of our clients, all the code runs in the function runs, including the sendToJourney function. For this client, after sendToHistory runs, the page switches and sendToJourney is not triggered. Do you know why this is?
sendToJourney and sendToHistory are functions that send some data to an API. Let me know if you need more information. Lastly, the client's website is created using Elementor which is a WordPress plugin. 2 of the other 4 clients also use Elementor but the function is fully executed for them but just not for this 1 client. Is there something that can be preventing the code from fully executing?
We have tried using obj.preventDefault but we cannot get the event to be triggered afterwards once our code is executed so what solution could be use here?
I call objectClick() by attaching an event listener as such:
(async function (document) {
await initData()
var trackable = document.querySelectorAll("img,button,p,h1,h2,h3,h4,h5,h6,a,span,input[type='submit'],[data-*]");
for (var i = 0; i < trackable.length; i++) {
trackable[i].addEventListener('mouseover', onHover, false);
trackable[i].addEventListener('mouseout', offHover, false);
trackable[i].addEventListener('click', objectClick, false);
}
})(document);
I'd like to know how to update URL addresses in Firefox using Web Extensions.
I'm trying to port a simple extension I've created with Chrome APIs to Firefox, but I don't really understand the tab URL mechanisms in Firefox.
This extension was made to switch between YouTube desktop/TV version with a click.
It works well on Chrome, but I don't know why it's not working on Firefox.
UPDATE 1: Placing most important code block related to the question:
chromeApi.browserAction.onClicked.addListener(function(tab) {
var actionUrl = '';
var tabUrl = tab.url;
if (getCurrentPageVersion(tabUrl) !== undefined) {
actionUrl = getConvertedActionUrl(tabUrl);
if (actionUrl !== tabUrl) {
chromeApi.tabs.update(tab.id, {url: actionUrl});
}
}
});
Full source
(function(chromeApi) {
getCurrentPageVersion = function (tabUrl) {
var ytValidRegex = /^(https?\:\/\/)?(www\.)?(youtube\.com|youtu\.?be)/g;
var ytValidStdPageRegex = /^(https?\:\/\/)?(www\.)?(youtube\.com|youtu\.?be)?(\/watch\?v=).+$/g;
var ytValidTvPageRegex = /^(https?\:\/\/)?(www\.)?(youtube\.com|youtu\.?be)?(\/tv#\/watch(\/video)?\/(idle|control)\?v=).+$/g;
if (!ytValidRegex.test(tabUrl)) {
return undefined;
} else if (ytValidStdPageRegex.test(tabUrl)) {
return "std";
} else if (ytValidTvPageRegex.test(tabUrl)) {
return "tv";
}
return undefined;
};
getConvertedActionUrl = function (tabUrl) {
var result = '';
var shortStdYtUrlRegex = /\/watch\?v=.+/g;
var shortTvYtUrlRegex = /\/tv#\/watch\/video\/(idle|control)\?v=.+/g;
var shortStdYtUrlReplaceRegex = /\/watch\?v=/g;
var shortTvYtUrlReplaceRegex = /\/tv#\/watch\/video\/(idle|control)\?v=/g;
if (shortStdYtUrlRegex.test(tabUrl)) {
result = tabUrl.replace(shortStdYtUrlReplaceRegex, '/tv#/watch/idle?v=');
}
else {
result = tabUrl.replace(shortTvYtUrlReplaceRegex, '/watch?v=');
}
// YouTube standard website video url
//https://www.youtube.com/watch?v=9tRDQK2MtRs
// YouTube TV url
//https://www.youtube.com/tv#/watch/video/idle?v=9tRDQK2MtRs
return result;
}
onInit = function () {
};
// Called when the user clicks on the browser action.
chromeApi.browserAction.onClicked.addListener(function(tab) {
var actionUrl = '';
var tabUrl = tab.url;
if (getCurrentPageVersion(tabUrl) !== undefined) {
actionUrl = getConvertedActionUrl(tabUrl);
if (actionUrl !== tabUrl) {
chromeApi.tabs.update(tab.id, {url: actionUrl});
}
}
});
chromeApi.tabs.onUpdated.addListener(function(tabId, changeInfo, tab){
if(!changeInfo.url) return; // URL did not change
// Might be better to analyze the URL to exclude things like anchor changes
var pageVersion = getCurrentPageVersion(tab.url);
if (pageVersion === undefined) return;
/* ... */
chromeApi.browserAction.setBadgeText({text: pageVersion.toUpperCase(), tabId: tab.id});
});
chromeApi.tabs.onCreated.addListener(function(tab){
var pageVersion = getCurrentPageVersion(tab.url);
if (pageVersion === undefined) return;
/* ... */
chromeApi.browserAction.setBadgeText({text: pageVersion.toUpperCase(), tabId: tab.id});
});
})(chrome);
If you pay attention, the core functionality happens on the chromeApi.browserAction.onClicked event, whenever you click the add-on/extension button.
The extension updates correctly between each YouTube version in Chrome, but in Firefox, this one redirects to YouTube TV once and never goes back to the desktop version no matter how many times you click on it.
But there's something weird in Firefox: browser history is updated correctly whenever the tab.update method is called, but it redirects to the TV version by itself again.
IMPORTANT: Both Firefox/Chrome extensions are using the currentTab permission, so it's not an extension issue by itself.
Extension on GitHub
UPDATE 2 (2018-11-25): I've updated the source code based on previous feedback
Referring to this question: Add-on Builder: ContentScript and back to Addon code?
Here is my addon code:
var widget = widgets.Widget({
id: "addon",
contentURL: data.url("icon.png"),
onClick: function() {
var workers = [];
for each (var tab in windows.activeWindow.tabs) {
var worker = tab.attach({contentScriptFile: [data.url("jquery.js"), data.url("myScript.js")]});
workers.push(worker);
}
}
});
And here is myScript.js:
var first = $(".avatar:first");
if (first.length !== 0) {
var url = first.attr("href");
self.port.emit('got-url', {url: url});
}
Now that I have multiple workers where do I put
worker.port.on('got-url', function(data) {
worker.tab.url = data.url;
});
Since in the other question I only had one worker but now I have an array of workers.
The code would be:
// main.js:
var data = require("self").data;
var windows = require("windows").browserWindows;
var widget = require("widget").Widget({
id: "addon",
label: "Some label",
contentURL: data.url("favicon.png"),
onClick: function() {
//var workers = [];
for each (var tab in windows.activeWindow.tabs) {
var worker = tab.attach({
contentScriptFile: [data.url("jquery.js"),
data.url("inject.js")]
});
worker.port.on('got-url', function(data) {
console.log(data.url);
// worker.tab.url = data.url;
});
worker.port.emit('init', true);
console.log("got here");
//workers.push(worker);
}
}
});
// inject.js
$(function() {
self.port.on('init', function() {
console.log('in init');
var first = $(".avatar:first");
if (first.length !== 0) {
var url = first.attr("href");
console.log('injected!');
self.port.emit('got-url', {url: url});
}
});
});
Edit: sorry, should have actually run the code, we had a timing issue there where the content script was injected before the worker listener was set up, so the listener was not yet created when the 'got-url' event was emitted. I work around this by deferring any action in the content script until the 'init' event is emitted into the content script.
Here's a working example on builder:
https://builder.addons.mozilla.org/addon/1045470/latest/
The remaining issue with this example is that there is no way to tell if a tab has been injected by our add-on, so we will 'leak' or use more memory every time the widget is clicked. A better approach might be to inject the content script using a page-mod when it is loaded, and only emit the 'init' event in the widget's onclick handler.
I'm writing the extension which will change layout of google in my browser.
My script using external css file when browser shows google.com. And it works fine before I opening a new tag - css is cleared. How can I match my css only for google search page?
window.addEventListener("load", function() { myExtension.init(); }, false);
var myExtension = {
init: function() {
var appcontent = document.getElementById("appcontent"); // browser
if(appcontent)
appcontent.addEventListener("DOMContentLoaded", myExtension.onPageLoad, true);
var messagepane = document.getElementById("messagepane"); // mail
if(messagepane)
messagepane.addEventListener("load", function(event) { myExtension.onPageLoad(event); }, true);
},
onPageLoad: function(aEvent) {
var patt_g=new RegExp('google.com','g');
Firebug.Console.log('Hide my ass started');
this.doc = aEvent.originalTarget; // doc is document that triggered "onload" event
CSSProvider.init();
if(patt_g.test(this.doc.location.href)) {
Firebug.Console.log('Hide my ass -> in');
CSSProvider.loadCSS();
} else {
Firebug.Console.log('Hide my ass -> out');
CSSProvider.unloadCSS();
}
// add event listener for page unload
aEvent.originalTarget.defaultView.addEventListener("unload", function(event){ myExtension.onPageUnload(event); }, true);
},
onPageUnload: function(aEvent) {
Firebug.Console.log('Hide my ass deleted');
if(patt_g.test(this.doc.location.href) ) {
Firebug.Console.log('Hide my ass -> out');
CSSProvider.unloadCSS();
}
}
};
var CSSProvider = {
init: function(){
this.sss = Components.classes["#mozilla.org/content/style-sheet-service;1"]
.getService(Components.interfaces.nsIStyleSheetService);
this.ios = Components.classes["#mozilla.org/network/io-service;1"]
.getService(Components.interfaces.nsIIOService);
this.uri = this.ios.newURI("chrome://hms/content/style.css", null, null);
this.isRegistered = this.sss.sheetRegistered(this.uri, this.sss.USER_SHEET)
},
loadCSS: function(){
if(!this.isRegistered){
this.sss.loadAndRegisterSheet(this.uri, this.sss.USER_SHEET);
}
},
unloadCSS: function(){
if(this.isRegistered){
this.sss.unregisterSheet(this.uri, this.sss.USER_SHEET);
}
}
};
Don't load/unload the CSS file each time a tab is opened - adding a user stylesheet will always apply it to all existing tabs, unloading it will remove it from all tabs. Simply add the stylesheet when your extension loads and put the CSS rules in the stylesheet into a #-moz-document section:
#-moz-document domain(google.com)
{
...
}
Documentation: https://developer.mozilla.org/en/CSS/#-moz-document
I have the following code snippet to enable extension after firefox quit,
observe: function (subject, topic, data) {
if (topic == "quit-application") {
LOG("inside quit-application Testing ");
var os = Components.classes["#mozilla.org/observer-service;1"]
.getService(Components.interfaces.nsIObserverService);
//os.addObserver(this, "http-on-examine-cached-response", false);
os.addObserver(this, "quit-application", false);
var appInfo = Components.classes["#mozilla.org/xre/app-info;1"]
.getService(Components.interfaces.nsIXULAppInfo);
var tempappVersion = appInfo.version;
var appVersion = tempappVersion.split(".");
// adding add-on listener dsable event on add-on for FF4 and later versions.
if (appVersion[0] >= 4) {
setAddonEnableListener();
LOG("\napp-startup Testing from javascript file....");
}
return;
}
}
And inside the setAddonEnableListener I am trying to enable the extension like this:
function setAddonEnableListener() {
try {
alert("setAddonEnableListener akbar nsListener called from ");
Components.utils.import("resource://gre/modules/AddonManager.jsm");
AddonManager.getAddonByID("somename#extension.com", function(addon)
{
if (addon.userDisabled)
addon.userDisabled = false;
});
} catch (ex) {
}
}
And I am registering the quit-application event var like this:
myModule = {
registerSelf: function (compMgr, fileSpec, location, type) {
var compMgr = compMgr.QueryInterface(Components.interfaces.nsIComponentRegistrar);
compMgr.registerFactoryLocation(this.myCID,
this.myName,
this.myProgID,
fileSpec,
location,
type);
var catMgr = Components.classes["#mozilla.org/categorymanager;1"].getService(Components.interfaces.nsICategoryManager);
catMgr.addCategoryEntry("app-startup", this.myName, this.myProgID, true, true);
catMgr.addCategoryEntry("quit-application", this.myName, this.myProgID, true, true);
}
When Firefox quits, inside quit-application Testing message is not getting displayed. What am I doing wrong here?
There is no category quit-application. You should receive app-startup notification (or rather profile-after-change starting with Firefox 4) and register your observer for quit-application:
observe: function (subject, topic, data) {
if (topic == "app-startup" || topic == "profile-after-change") {
var observerService = Components.classes["#mozilla.org/observer-service;1"]
.getService(Components.interfaces.nsIObserverService);
observerService.addObserver(this, "quit-application", false);
}
else if (topic == "quit-application") {
var observerService = Components.classes["#mozilla.org/observer-service;1"]
.getService(Components.interfaces.nsIObserverService);
observerService.removeObserver(this, "quit-application");
...
}
}
To quote the documentation:
Unless otherwise noted you register for the topics using the nsIObserverService.
And there is no note about registration via category manager on any shutdown notifications.
Btw, I sincerely recommend XPCOMUtils for component registration. You shouldn't need to write the module definition yourself.