Firefox extension, opening a local file in a new foreground tab from menu - firefox

I am learning how to program Firefox extensions. I have created a new menu and when the menu item is clicked, I want a new tab to be opened, in the foreground, containing a local file contained within the contents directory.
For example:
MENU -> Item1
When Item1 is selected, I want a new tab to open in the foreground containing what is located in /myextension/content/content.html.
Where can I find out how to do this?
For clarity, I can get the local file to open in a new tab, I just do not know how to get to open in a new focused tab.

I use the following function to open a tab, make sure it hasn't already been opened and switch focus to it:
function OpenAndReuseOneTabPerURL(url)
{
var wm = Components.classes["#mozilla.org/appshell/window-mediator;1"].getService(Components.interfaces.nsIWindowMediator);
var browserEnumerator = wm.getEnumerator("navigator:browser");
// Check each browser instance for our URL
var found = false;
while (!found && browserEnumerator.hasMoreElements())
{
var browserWin = browserEnumerator.getNext();
var tabbrowser = browserWin.gBrowser;
// Check each tab of this browser instance
var numTabs = tabbrowser.browsers.length;
for (var index = 0; index < numTabs; index++)
{
var currentBrowser = tabbrowser.getBrowserAtIndex(index);
if (url == currentBrowser.currentURI.spec)
{
// The URL is already opened. Select this tab.
tabbrowser.selectedTab = tabbrowser.tabContainer.childNodes[index];
// Focus *this* browser-window
browserWin.focus();
found = true;
break;
}
}
}
// Our URL isn't open. Open it now.
if (!found)
{
var recentWindow = wm.getMostRecentWindow("navigator:browser");
if (recentWindow) {
// Use an existing browser window
recentWindow.delayedOpenTab(url, null, null, null, null);
} else {
// No browser windows are open, so open a new one.
window.open(url);
}
}
}
Use it like:
OpenAndReuseOneTabPerURL("http://yoururl.com");

Related

Fastest way to close other tabs in the browser

How can I close "other" tabs in Firefox in a fast way? I am currently doing the following:
var tabs = windows.activeWindow.tabs
for (let n in tabs) {
let tab = tabs[n];
tab.close();
}
But this method is painfully slow when the user has many tabs open.
This is the way I do it, but it might have the same speed hit as the method above.
Please open scrtachpad, set environment to browser, and run this code to let me know the speed.
console.time('time to close all other tabs');
var cTabIndex = gBrowser.selectedTab._tPos;
var cntTabs = gBrowser.tabContainer.childNodes.length;
// close tabs to right
for (var i=cTabIndex+1; i<cntTabs; i++) {
gBrowser.removeTab(gBrowser.tabContainer.childNodes[i]);
}
// close tabs to left
for (var i=0; i<cTabIndex; i++) {
gBrowser.removeTab(gBrowser.tabContainer.childNodes[i]);
}
console.timeEnd('time to close all other tabs');
The other method I based on this work here:
https://stackoverflow.com/a/26744281/5062337
What this method does is it moves out the current tab to a new window, and it closes the old window:
function moveTabToWin(aTab, tDOMWin) {
//tDOMWin means target DOMWindow means the window you want the tab in
//if tDOMWin == 'tabbed' or == 'non-tabbed' it opens in a new window
//if aTopContWin is the last in its window, then its window is closed
if (tDOMWin == 'tabbed' || tDOMWin == 'non-tabbed') {
var sa = Cc["#mozilla.org/supports-array;1"].createInstance(Ci.nsISupportsArray);
var wuri = Cc["#mozilla.org/supports-string;1"].createInstance(Ci.nsISupportsString);
wuri.data = 'about:blank';
sa.AppendElement(wuri);
let features = "chrome,dialog=no";
if (tDOMWin == 'tabbed') {
features += ',all';
}
var sDOMWin = aTab.ownerGlobal; //source DOMWindow
if (PrivateBrowsingUtils.permanentPrivateBrowsing || PrivateBrowsingUtils.isWindowPrivate(sDOMWin)) {
features += ",private";
} else {
features += ",non-private";
}
var XULWindow = Services.ww.openWindow(null, 'chrome://browser/content/browser.xul', null, features, sa);
XULWindow.addEventListener('load', function() {
var DOMWindow = XULWindow.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowInternal || Ci.nsIDOMWindow);
DOMWindow.gBrowser.selectedTab.linkedBrowser.webNavigation.stop(Ci.nsIWebNavigation.STOP_ALL);
var oldWin = aTab.ownerDocument.defaultView;
DOMWindow.gBrowser.swapBrowsersAndCloseOther(DOMWindow.gBrowser.selectedTab, aTab);
//DOMWindow.gBrowser.selectedTab = newTab;
oldWin.close();
console.timeEnd('time to move tab to new win and close old win');
}, false);
} else if (tDOMWin) {
//existing dom window
var newTab = tDOMWin.gBrowser.addTab('about:blank');
var oldWin = aTab.ownerDocument.defaultView;
newTab.linkedBrowser.webNavigation.stop(Ci.nsIWebNavigation.STOP_ALL);
tDOMWin.gBrowser.swapBrowsersAndCloseOther(newTab, aTab);
tDOMWin.gBrowser.selectedTab = newTab;
oldWin.close();
console.timeEnd('time to move tab to new win and close old win');
}
}
console.time('time to move tab to new win and close old win');
var oldWin = Services.wm.getMostRecentWindow('navigator:browser');
moveTabToWin(oldWin.gBrowser.selectedTab, 'tabbed');
Both of them have timers attached, both can run from scratchpad, please share the timings. The new window does tak about 1 second for me, but there is no freezing as there was in the first method with lots of tabs.

How to programmatically move a tab to another window in a firefox Addon-SDK extension?

While it looks like you can change the order of a tab within a window by updating the tab .index property, it doesn't look like the tabs api directly supports the move of a tab to another window.
Am I missing something? Is there a viable workaround?
It is possible through the low level module window/utils. The example below duplicates the active tab across every open window
const { getMostRecentBrowserWindow, windows: getWindows } = require("sdk/window/utils");
const { ActionButton } = require("sdk/ui/button/action");
var button = ActionButton({
id: "duplicatetab-button",
label: "Duplicate tab",
icon: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAACUElEQVQ4jaWTTWtTURCGjzc33CCpbVKN4kexC9EUY1Hov+iqPyDrbgtuCrViKUERqsWVguBGQaW4UiKiaEVxoShFGgnuBMUqNW3zce49Z+ZxUWtwoRR8YXbzPswM7xj+JgVEiXGsYVknxgII4Ltt5p8AB8RArOAUVQfqQJNtAFA8QgvF6i9PR1Dt0KbVBTjncM4hIni/OZv3HsRB+wvefiP2LcQnJIkQe49FEJFNQLPZZHh4mEwmQyqVoqenh3K5TGvlK1dOlageH+HG4DFar1/S0A6Lr99xdN8QxWKRXC6HGR0dJZvNMjk5Sb1ep1gskk6nuTo/D+/ec7dvkBdhP9cKeX7UXxEZQ2/YRxRFLC8vY+bm5qhUKnjvsdYyPj5OFEWcnTnHujiS5TfcPDbAw50h9w7u5f7UadLZFLVaDRHBiGzuY61lbGyMXC5HoVBgrbGGWAW/TvvxHR7s7udFKs/1oyfZ+PSRTqeDqm7eoFqtEoYhmUyG2dlZVJU4iREfI/WP3Nt9iMUdu7jdf5Anly5i0oaVlRWazSZmYWGBIAiIoohyucz09DQTExPMnJli9dlT5vcM8Kh3gFsHDuNqb9mb7yXMRBhjWFpawpRKJVKpFMYYgiAgDEOCIOD81BkunBjh8pEhKqUhGkvP6bQ/U//wgUP5/YRhSDabxbTbbVQV5xyq2q0kgR8NdOM7JKuo/Y5qggqIdPvMlnkrQCKCquJFsOrxeHAJxA48eFU6Xv4EqOpv41YqnQirqliv4MEmQtN7RBSs7wL+/gvb038DfgJnyUabbHzUbQAAAABJRU5ErkJggg==",
onClick: function() {
var xulwindows = getWindows("navigator:browser");
var xulactivewindow = getMostRecentBrowserWindow();
var xulactivetab = xulactivewindow.gBrowser.selectedTab;
xulwindows.forEach(function(win){
if(win === xulactivewindow)
return;
var duplicatedtab = win.gBrowser.duplicateTab(xulactivetab);
win.gBrowser.moveTabTo(duplicatedtab, 0); // the second argument is the index
});
}
});
#paa's solution is nice but it doesn't move a tab. His is duplicating the tab. So flash movies will not retain their position etc. And its not a move its a duplicatio, like he explained.
I did a lot of research was real fun. The way they move tabs in Firefox is via docShell swapping. This will accomplish what you want. It's written for bootstrap though so needs touch up for addon sdk.
Pass second argument as string of tabbed or non-tabbed if you want to move it to a new window. Else pass second argument an existing window and it will be moved there. can copy paste and run this code from sratchpad.
this uses the gBrowser.swapBrowsersAndCloseOther function
function moveTabToWin(aTab, tDOMWin) {
//tDOMWin means target DOMWindow means the window you want the tab in
//if tDOMWin == 'tabbed' or == 'non-tabbed' it opens in a new window
//if aTopContWin is the last in its window, then its window is closed
if (tDOMWin == 'tabbed' || tDOMWin == 'non-tabbed') {
var sa = Cc["#mozilla.org/supports-array;1"].createInstance(Ci.nsISupportsArray);
var wuri = Cc["#mozilla.org/supports-string;1"].createInstance(Ci.nsISupportsString);
wuri.data = 'about:blank';
sa.AppendElement(wuri);
let features = "chrome,dialog=no";
if (tDOMWin == 'tabbed') {
features += ',all';
}
var sDOMWin = aTab.ownerGlobal; //source DOMWindow
if (PrivateBrowsingUtils.permanentPrivateBrowsing || PrivateBrowsingUtils.isWindowPrivate(sDOMWin)) {
features += ",private";
} else {
features += ",non-private";
}
var XULWindow = Services.ww.openWindow(null, 'chrome://browser/content/browser.xul', null, features, sa);
XULWindow.addEventListener('load', function() {
var DOMWindow = XULWindow.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowInternal || Ci.nsIDOMWindow);
DOMWindow.gBrowser.selectedTab.linkedBrowser.webNavigation.stop(Ci.nsIWebNavigation.STOP_ALL);
DOMWindow.gBrowser.swapBrowsersAndCloseOther(DOMWindow.gBrowser.selectedTab, aTab);
//DOMWindow.gBrowser.selectedTab = newTab;
}, false);
} else if (tDOMWin) {
//existing dom window
var newTab = tDOMWin.gBrowser.addTab('about:blank');
newTab.linkedBrowser.webNavigation.stop(Ci.nsIWebNavigation.STOP_ALL);
tDOMWin.gBrowser.swapBrowsersAndCloseOther(newTab, aTab);
tDOMWin.gBrowser.selectedTab = newTab;
}
}
moveTabToWin(gBrowser.selectedTab, 'tabbed');
I'v got inspired by #Noitidart's answer and came up with my solution.
I'm adding setWindow(window, index) method to Tab's prototype, so that any SDK tab can be moved to another window from anywhere in the addon with a simple call like this:
browserWindows[0].activeTab.setWindow(browserWindows.activeWindow, 0);
This will move active tab of window 0 to the beginning of active window.
And here is the method:
Update:
I've put together a module to do exactly this: jetpack-tab-setwindow
Old solution (breaks in FF43)
var Tab = require("sdk/tabs/tab").Tab;
Tab.prototype.setWindow = function (window, index) {
var tab = this;
var oldWindow = tab.window;
if ( oldWindow !== window ) {
// We have to use lower-level API here
var Ci = require('chrome').Ci;
var viewFor = require("sdk/view/core").viewFor;
var aTab = viewFor(tab);
var aWin = viewFor(window);
var gBrowser = aWin.gBrowser;
// Get tab properties
var isSelected = oldWindow.activeTab == tab;
var isPinned = aTab.pinned;
// Log for debugging:
var tabId = tab.id;
console.log('setWindow', {index, isSelected, isPinned, tab, tabId});
// Create a placeholder-tab on destination windows
var newTab = gBrowser.addTab('about:newtab');
newTab.linkedBrowser.webNavigation.stop(Ci.nsIWebNavigation.STOP_ALL); // we don't need this tab anyways
// If index specified, move placeholder-tab to desired index
if ( index != undefined ) {
var length = gBrowser.tabContainer.childElementCount;
if ( index < 0 ) index = length - index;
if( 0 <= index && index < length ) {
gBrowser.moveTabTo(newTab, index);
}
}
// Copy tab properties to placeholder-tab
if ( isPinned ) {
gBrowser.pinTab(newTab);
}
// For some reason this doesn't seem to work :-(
if ( isSelected ) {
gBrowser.selectedTab = newTab;
}
// Swap tabs and remove placeholder-tab
gBrowser.swapBrowsersAndCloseOther(newTab, aTab);
}
};

Have embedded images open with FancyBox, not in new window

This section of code in my /js/global.js file activate each image to open in a new window when clicked. Is it possible to alter this code to have each open in a FancyBox instead? I have downloaded a FancyBox plugin for a Vanilla forum I am running, and it currently only targets images embedded in posts After You Click On The Post Itself. On the main page, clicking on an image opens a new window.
// Shrink large images to fit into message space, and pop into new window when clicked.
// This needs to happen in onload because otherwise the image sizes are not yet known.
jQuery(window).load(function() {
var props = ['Width', 'Height'], prop;
while (prop = props.pop()) {
(function (natural, prop) {
jQuery.fn[natural] = (natural in new Image()) ?
function () {
return this[0][natural];
} :
function () {
var
node = this[0],
img,
value;
if (node.tagName.toLowerCase() === 'img') {
img = new Image();
img.src = node.src,
value = img[prop];
}
return value;
};
}('natural' + prop, prop.toLowerCase()));
}
jQuery('div.Message img').each(function(i,img) {
var img = jQuery(img);
var container = img.closest('div.Message');
if (img.naturalWidth() > container.width() && container.width() > 0) {
img.wrap('');
}
});
// Let the world know we're done here
jQuery(window).trigger('ImagesResized');
});
Add an specific class to your wrapped images, modifying this line
img.wrap('');
... into this :
img.wrap('<a class="fancybox" href="'+$(img).attr('src')+'"></a>');
Then bind fancybox to that selector (".fancybox") in a custom script like :
$(".fancybox").fancybox();
This assumes that you have properly loaded the fancybox js and css files.

How to get right click context menu on certain file types in Visual Studio

I am trying to developing an AddIn for Visual Studio to get a right click context menu for javascript files and image files. I have managed to add my Addin to the right click of all project items
What I want to achieve is to get the Addin ONLY on javascript files and image files. Something like this (Note:- currently I am getting Addin on ALL file types)
Below is the code I have in the connect
if (connectMode == ext_ConnectMode.ext_cm_UISetup)
{
object[] contextGUIDS = new object[] { };
Commands2 commands = (Commands2)_applicationObject.Commands;
string toolsMenuName = "Tools";
//Place the command on the tools menu.
//Find the MenuBar command bar, which is the top-level command bar holding all the main menu items:
Microsoft.VisualStudio.CommandBars.CommandBar menuBarCommandBar = ((Microsoft.VisualStudio.CommandBars.CommandBars)_applicationObject.CommandBars)["MenuBar"];
//Find the Tools command bar on the MenuBar command bar:
CommandBarControl toolsControl = menuBarCommandBar.Controls[toolsMenuName];
CommandBarPopup toolsPopup = (CommandBarPopup)toolsControl;
Microsoft.VisualStudio.CommandBars.CommandBar itemToolBar = ((Microsoft.VisualStudio.CommandBars.CommandBars)_applicationObject.CommandBars)["Item"];
//This try/catch block can be duplicated if you wish to add multiple commands to be handled by your Add-in,
// just make sure you also update the QueryStatus/Exec method to include the new command names.
try
{
//Add a command to the Commands collection:
Command command = commands.AddNamedCommand2(_addInInstance, "CrmAddin", "CrmAddin", "Executes the command for CrmAddin", true, 59, ref contextGUIDS, (int)vsCommandStatus.vsCommandStatusSupported + (int)vsCommandStatus.vsCommandStatusEnabled, (int)vsCommandStyle.vsCommandStylePictAndText, vsCommandControlType.vsCommandControlTypeButton);
//Add a control for the command to the tools menu:
if ((command != null) && (toolsPopup != null))
{
command.AddControl(toolsPopup.CommandBar, 1);
}
if ((command != null) && (itemToolBar != null))
{
command.AddControl(itemToolBar, 1);
}
}
catch (System.ArgumentException)
{
//If we are here, then the exception is probably because a command with that name
// already exists. If so there is no need to recreate the command and we can
// safely ignore the exception.
}
I tried to filter out the file types in the QueryStatus method like this but it is of no help
if (neededText == vsCommandStatusTextWanted.vsCommandStatusTextWantedNone)
{
if (commandName == "CrmAddin.Connect.CrmAddin")
{
bool supportedFileTypes = true;
foreach (Project project in _applicationObject.Solution.Projects)
{
foreach (ProjectItem projectItem in project.ProjectItems)
{
if (!projectItem.Name.EndsWith(".js"))
{
supportedFileTypes = false;
}
}
}
if (supportedFileTypes)
{
status = (vsCommandStatus)vsCommandStatus.vsCommandStatusSupported | vsCommandStatus.vsCommandStatusEnabled;
}
else
{
status = (vsCommandStatus)vsCommandStatus.vsCommandStatusSupported;
}
return;
}
}
Please help if anyone can point me to the right direction.
Just for info.
Was looking for a solution to similar problem, found this first, then after some searching I saw your question on MSDN (?)
http://social.msdn.microsoft.com/Forums/en-US/vsx/thread/c8f35f82-c694-4a6a-8c4a-a8404a4df11f
Which gave the answer :)

Persistent Dashboard Widget Preferences

I'm building a Dashboard Widget and I'm attempting to store preferences that persist across "sessions" (i.e., a user closing the widget and opening it again).
I've tried:
function setEmail(event)
{
var preferenceKey = "email";
var preferenceValue = $F("email");
widget.setPreferenceForKey(preferenceValue, preferenceKey);
}
function getEmail() {
var preferenceForKey = "email";
preferenceForKey = widget.preferenceForKey(preferenceForKey);
return preferenceForKey;
}
This works fine for the current session, but if the widget is closed and opened again, the data is lost.
Thanks!
This seems to do the trick:
// Values you provide
var preferenceKey = "key"; // replace with the key for a preference
var preferenceValue = "value"; // replace with a preference to save
// Preference code
widget.setPreferenceForKey(preferenceValue, preferenceKey);

Resources