Context menu in Chrome - two actions (left/right click on item menu) - javascript

I want to create an extension for chrome browsers: item menu in context menu with two different actions when you use left or right click on item menu.
For Firefox it can be realized, but for Chrome? How?
background.js:
chrome.runtime.onInstalled.addListener(function() {
chrome.contextMenus.create({
title: 'do action (left cl. - first, right cl. - second)',
id: 'test',
contexts: ['link'],
});
});
chrome.contextMenus.onClicked.addListener(function(info, tab) {
if (info.menuItemId === "test") {
console.log("first action completed")
}
});

Distinguishing between two clicks in a context menu is impossible in Chrome.
To be fair, it's a very confusing idea, I don't think people expect that from a context menu UI.
Now, clicking with a modifier key is something more common (e.g. Delete vs Shift+Delete in a file manager), but Chrome does not support it either.
You can see the full list of data available here.

Related

Contextmenu in Safari extension

I've searched for contextmenu with icon and Additional 3 sub menu items and can't seem to find a way to do that process to my Safari extension. Are either of these things possible in Safari extensions?
As my Experience there is no way to put icon in context menu item and also it is not possible to put second level menu(sub menu) in context menu. In Extension Builder of Safari browser there is no option available to set icon.
You can add an icon in your context menu, see the image on the Turn Off the Lights blog post (of the Turn Off the Lights Safari extension:
https://www.turnoffthelights.com/blog/apple-safari-support-is-dead/
lampmenu = safari.extension.createMenu("lampmenu");
sharemenu = safari.extension.createMenu("sharemenu");
lampmenu.appendMenuItem("totl", "Turn Off the Lights");
lampmenu.appendSeparator();
lampmenu.appendMenuItem("welcomeguide", "Welcome Guide");
lampmenu.appendMenuItem("supportdev", "Support Development");
var itemrate = lampmenu.appendMenuItem("ratethis", "Rate this extension");
itemrate.image = safari.extension.baseURI + "images/browser_star#2x.png";
See source of the open source Turn Off the Lights Safari extension: https://github.com/turnoffthelights/

Why am I receiving webNavigation.onCompleted events for tabs that never received an onCreated event in my Chrome extension?

I'm trying to write an extension to Chrome that keeps close track of the various tabs open. It seems that new tabs keep appearing out of thin air, though. What's going on here?
Here is a very simple background page that illustrates what I'm talking about:
(function () {
'use strict';
var tabKeeper = {};
function logError(tabId) {
if (!tabKeeper[tabId]) {
console.log('Tab ' + tabId + ' not found!');
console.log(JSON.stringify(tabKeeper));
tabKeeper[tabId] = true;
}
}
chrome.tabs.onCreated.addListener((tab) => {
console.log('Tab created: ' + tab.id);
tabKeeper[tab.id] = true;
});
chrome.webNavigation.onCompleted.addListener((details) => {
console.log('Navigation complete: ' + details.tabId);
logError(details.tabId);
});
chrome.tabs.query({}, (tabs) => {
if (!tabs) { return; }
tabs.forEach((tab) => {
console.log('Tab found at startup: ' + tab.id);
tabKeeper[tab.id] = true;
});
});
})();
Steps to reproduce behavior (Chrome 47.0.2526.73):
Start Chrome
Create a new tab
Type "abc " (with a space after it) into the address bar of the new tab
Here is what I see in the console log:
Tab found at startup: 2
Navigation complete: 2
Tab created: 4
Navigation complete: 4
Navigation complete: 4
Navigation complete: 6
Tab 6 not found!
{"2":true,"4":true}
This seems to be very repeatable. What is tab 6? Where did it come from? Why don't I get an event when it is created?
This is due to the Chrome Prerendering feature. When you enter an address to the address bar, before you actually get the tabs opened up, it is rendered as a hidden tab which gets visible when you press enter. The content scripts and your chrome extension are active for these hidden tabs also. It basically speeds up the process for better user experience by keeping the content ready before any user actually access it.
More details here.
Also knowing about how the visibility state change for any page would be very helpful to understand why these events are invoked.
This is the basic cause of why the events are triggered but the tabs are yet not open and visible to you. Also in case of prerendering i.e when the visibility state changes, the chrome.tabs.onCreated.addListener() is not invoked but another listener called chrome.tabs.onReplaced() is called. More details on page visibility state here.
This is a hidden prerendered tab created automatically when an omnibox search is performed.
Its tab.index property is -1 (the zero-based index of the tab within its window).
If the search is cancelled or changed the tab is destroyed.
If the search is confirmed this tab becomes visible.
The behavior is controlled by Prefetch resources to load pages more quickly option in Chrome settings.

How to add a right click on my Firefox extension's icon?

Good Day!
I've searched and searched again and I didn't find any help for this problem...
Context :
I've developed a Google Chrome extension that is very simple: send email to somebody with one click. To configure this, there is an option page on this extension to set the email address to which to send. My Google Chrome extension is available here (English translation, just the text, not the install).
Users have asked me to make this extension for Firefox so I'm working on it!
I've read tutorials on cfx and it's OK. But I need to have my extension respond to a right-click on my extension's icon in the toolbar. Not on the page, on my icon.
I'm using ActionButton (or ToggleButton) to add my icon to this the toolbar but I can't find a way to add a menu on the right click (there's already the default Firefox context menu but I want to add "Options".)
If somebody has the solution it would be great!
(I'm not familiar with XUL. So, if possible, a JavaScript only solution, please ^^ )
PS : I'm French so please excuse me for my bad English
EDIT : I've found how to set preferences in my "package.json" file but I want my own window.
And if we could "bind" the button "Options" in Add-on Manager to my own window it would be perfect!
EDIT 2 : as it's not clear for everyone I would detail here what I want for my extension :
- simple click (left click) on the icon get the current URL and send it to a mail address (OK for this)
- simple click ONLY DO THIS. This extension aims to be very very simple !
- right click on the icon shows Firefox's context-menu and I want to add "Options" here to show my options page
- Addon Manager could have a "Options" button near "Deactivate" and "Debug" and I want this option button to show my options page.
=> 2 way to see my option page : by the right click or by the addon manager and this is why I need your help !
General UI comments
Using right-click to directly activate your function is contrary to the general UI that is used system wide. Right-click is, system-wide (on some systems), used to open the context menu. In Firefox in the toolbar this is used to bring up the context menu for the toolbar area. This is what your users are generally going to expect to happen when they use right-click. You are probably better off either using something like shift-left-click, or letting the user define what combination is to be used to activate your function. If it is that you are attempting to add an option to the context menu, then that would normally be accessed via right-click.
Alternatives used in other add-ons:
A second section to your button with a down arrow. Clicking on the down arrow opens an expanded action or options menu.
Use the tooltip to display an action or options menu when the mouse is hovered over your button. This is done by creating a custom tooltip by enclosing the popup within a <tooltip id="myTooltip"></tooltip> element and referencing it in the button with <button tooltip="myTooltip"/> (tooltip property, tooltip attribute).
Using right-click
The problem appears to be that the Add-on SDK ActionButton has abstracted away your ability to have listeners for arbitrary events. It also does not give you access to the actual event object which is normally passed to event handlers (listeners). Further, its click event appears to actually be a command event, not a click event. One of the significant differences between a click and a command event is that the command event does not normally fire on a right-click.
You are going to need to gain access to the button outside of the ActionButton interface and add a listener for click events and then in your click event handler, you can make a choice to perform your action based on the state of event.button and event.shiftKey.
Adapting some code based on what I posted as an answer for a different question, you are going to want something like (not tested with modifications):
function loadUi(buttonId) {
if (window === null || typeof window !== "object") {
//If you do not already have a window reference, you need to obtain one:
// Add a "/" to un-comment the code appropriate for your add-on type.
/* Add-on SDK:
var window = require('sdk/window/utils').getMostRecentBrowserWindow();
//*/
/* Overlay and bootstrap (from almost any context/scope):
var window=Components.classes["#mozilla.org/appshell/window-mediator;1"]
.getService(Components.interfaces.nsIWindowMediator)
.getMostRecentWindow("navigator:browser");
//*/
}
forEachCustomizableUiById(buttonId, loadIntoButton, window);
}
function forEachCustomizableUiById(buttonId ,func, myWindow) {
let groupWidgetWrap = myWindow.CustomizableUI.getWidget(buttonId);
groupWidgetWrap.instances.forEach(function(windowUiWidget) {
//For each button do the load task.
func(windowUiWidget.node);
});
}
function loadIntoButton(buttonElement) {
//Make whatever changes to the button you want to here.
//You may need to save some information about the original state
// of the button.
buttonElement.addEventListener("click",handleClickEvent,true);
}
function unloadUi(buttonId) {
if (window === null || typeof window !== "object") {
//If you do not already have a window reference, you need to obtain one:
// Add a "/" to un-comment the code appropriate for your add-on type.
/* Add-on SDK:
var window = require('sdk/window/utils').getMostRecentBrowserWindow();
//*/
/* Overlay and bootstrap (from almost any context/scope):
var window=Components.classes["#mozilla.org/appshell/window-mediator;1"]
.getService(Components.interfaces.nsIWindowMediator)
.getMostRecentWindow("navigator:browser");
//*/
}
forEachCustomizableUiById(buttonId, unloadFromButton, window);
}
function unloadFromButton(buttonElement) {
//Return the button to its original state
buttonElement.removeEventListener("click",handleClickEvent,true);
}
function handleClickEvent(event) {
If( (event.button & 2) == 2 && event.shiftKey){
event.preventDefault();
event.stopPropagation();
doMyThing();
}
}
function doMyThing() {
//Whatever it is that you are going to do.
}
As should be implied by the above code, you will need to make sure to remove your listener when uninstalling/disabling your add-on. You will also want to make sure that loadUi() gets called when a new window opens so that your handler is added to the new button.
Adding to the context menu
There is no direct way to change the context menu just for your icon. The ID for the context menu is toolbar-context-menu. What you can do is add items to the context menu which are normally hidden="true". When you get the event that the right-click has happened on your icon you can change the state of hidden for those items you added. Then in an event handler that is called on the the popuphidden event for the context menu (<menupopup id="toolbar-context-menu">) you can set the state of hidden="true" for the <menuitem> element(s) which you have added to the <menupopup id="toolbar-context-menu"> in each browser window.
Something along the lines of:
function loadIntoContextMenu(win){
let doc = win.ownerDocument;
let contextPopupEl = doc.getElementById("toolbar-context-menu");
contextPopupEl.insertAdjacentHTML("beforeend",
'<menuitem label="My Item A" id="myExtensionPrefix-context-itemA"'
+ ' oncommand="doMyThingA();" hidden="true" />'
+ '<menuitem label="My Item B" id="myExtensionPrefix-context-itemB"'
+ ' oncommand="doMyThingB();" hidden="true" />');
contextPopupEl.addEventListener("popuphidden",hideMyContextMenuItems,true);
}
function unloadFromContextMenu(win){
let doc = win.ownerDocument;
let contextPopupEl = doc.getElementById("toolbar-context-menu");
let itemA = doc.getElementById("myExtensionPrefix-context-itemA");
let itemB = doc.getElementById("myExtensionPrefix-context-itemB");
contextPopupEl.removeChild(itemA);
contextPopupEl.removeChild(itemB);
contextPopupEl.removeEventListener("popuphidden",hideContextMenuItems,true);
}
function setHiddenMyContextMenuItems(element,text){
//The element is the context menu.
//text is what you want the "hidden" attribute to be set to.
let child = element.firstChild;
while(child !== null){
if(/myExtensionPrefix-context-item[AB]/.test(child.id)){
child.setAttribute("hidden",text);
}
child = child.nextSibling;
}
}
function showContextMenuItems(event){
//The target of this event is the button for which you want to change the
// context menu. We need to find the context menu element.
let contextmenuEl = event.target.ownerDocument
.getElementById("toolbar-context-menu");
setHiddenMyContextMenuItems(contextmenuEl,"false");
}
function hideContextMenuItems(event){
//This is called for the popuphidden event of the context menu.
setHiddenMyContextMenuItems(event.target,"true");
}
//Change the handleClickEvent function in the code within the earlier section:
function handleClickEvent(event) {
If( (event.button & 2) == 2){
//don't prevent propagation, nor the default as the context menu
// showing is desired.
showContextMenuItems(event);
}
}
Again, I have not tested this. It should demonstrate one way to accomplish what you desire.
However, given that we are talking about the context-menu, it is probably better to use the contextmenu event rather than the click event and testing for a right-click. In which case, we would change some of the functions above to be the following:
function loadIntoButton(buttonElement) {
//Make whatever changes to the button you want to here.
buttonElement.addEventListener("contextmenu",handleContextmenuEvent,true);
}
function handleContextmenuEvent(event) {
showContextMenuItems(event);
}
You can obtain each open primary browser window through the use of nsIWindowMediator. The following function, from MDN, will run the function you pass to it once for each open window:
Components.utils.import("resource://gre/modules/Services.jsm");
function forEachOpenWindow(todo) // Apply a function to all open browser windows
{
var windows = Services.wm.getEnumerator("navigator:browser");
while (windows.hasMoreElements()) {
todo(windows.getNext().QueryInterface(Components.interfaces.nsIDOMWindow));
}
}
In the Add-on SDK:
function forEachOpenWindow(todo) // Apply a function to all open browser windows
var windows = require("sdk/windows");
for (let window of windows.browserWindows) {
todo(windows.getNext().QueryInterface(Components.interfaces.nsIDOMWindow));
}
}
You can add a listener which calls loadIntoContextMenu for new windows with the following code (also from MDN):
Components.utils.import("resource://gre/modules/Services.jsm");
Services.wm.addListener(WindowListener);
var WindowListener =
{
onOpenWindow: function(xulWindow)
{
var window = xulWindow.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
.getInterface(Components.interfaces.nsIDOMWindow);
function onWindowLoad()
{
window.removeEventListener("load",onWindowLoad);
if (window.document.documentElement.getAttribute("windowtype") == "navigator:browser"){
loadIntoContextMenu(window);
//It would be better to only do this for the current window, but
// it does not hurt to do it to all of them again.
loadUi(buttonId);
}
}
window.addEventListener("load",onWindowLoad);
},
onCloseWindow: function(xulWindow) { },
onWindowTitleChange: function(xulWindow, newTitle) { }
};
I have implemented a menu-button that has a primary and secondary action. Although it isn't right/left click, the button has two sides:
This allows you to associate two different actions with your button without altering the usual context menu flow of Firefox. Download the files on GitHub and store them in your lib folder.
Usage is similar to other button types. Include the following code in main.js (or any js file in the lib directory)
const { MenuButton } = require('./menu-button');
var btn = MenuButton({
id: 'my-menu-button',
label: 'My menu-button',
icon: {
"16": "./firefox-16.png",
"32": "./firefox-32.png"
},
onClick: click
});
The click function will be passed the same state object as the toggle and action buttons, and will be passed an additional boolean argument: isMenu. It should be used like so
function click(state, isMenu) {
if (isMenu) {
//menu-button clicked
} else {
//icon clicked
}
}
I tried your extension on Chrome after answering this question and see that my answer probably isn't what you're looking for, so I'll make a different suggestion (leaving the other answer up because I think it is useful for people looking for multiple actions on a single button).
One thing I would say is that (some) Chrome users know that the Options menu item refers to the extension and not browser options. Those users know that the menu item is there, and use it to change their extension settings. Firefox users wouldn't expect that to be the case, because the context menu actions all affect the browser, not the extension. In the same way, (some) Firefox users know that to change their extension settings, they must navigate to about:addons (or Tools/Addons) and click the Preferences button next to the extension. This is the expected route to changing your preferences. So I would argue that adding a context-menu option is very complicated and not a good solution.
Instead, if your users haven't yet set their preferences, I think you should do what you already do in Chrome: create a Panel, associate it with your button (by using position: button in the panel constructor), and tell your users that they need to set their preferences by navigating to Tools/Addons. If you use the simple prefs module, a Preferences button will appear next to your extension and the options that you set in your package.json will be editable there.
Unfortunately, this is a very basic page, and won't look like the nice HTML options page you made.
Bonne chance.
Besides all the reservations in the other answers and without reusing the existing toolbar contextmenu, here is how:
const utils = require('sdk/window/utils');
const window = utils.getMostRecentBrowserWindow();
const doc = window.document;
const XUL_NS = 'http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul';
const { getNodeView } = require("sdk/view/core");
let ButContext = doc.createElementNS(XUL_NS,'menupopup');
ButContext.setAttribute("id","customIDString");
menuitem = doc.createElementNS(XUL_NS,"menuitem");
menuitem.setAttribute("label", "customLabelString");
ButContext.appendChild(item);
var myBut = require("sdk/ui/button/action").ActionButton({
id: "myButton",
label: "Right click me!"
// And other options
});
//Here is the context magic
getNodeView(myBut).setAttribute('context', "customIDString");
//either ; gets removed together with the button
getNodeView(myBut).appendChild(ButContext);
//or ; the correct place but needs to be removed manually
doc.getElementById("mainPopupSet").appendChild(ButContext);

addon firefox - open window with specific dimensions

I have made an addon for firefox. I install it but i have two problems.I use windows.open because the panel isn`t suitable for me because if the user want to copy something in it, the panel is disappearing when he leaves it. So i have windows. I have this code:
var widgets = require("sdk/widget");
var windows = require("sdk/windows").browserWindows;
var self = require("sdk/self");
var widget = widgets.Widget({
id: "open window",
label: "test",
contentURL: self.data.url("favicon.ico"),
onClick: function() {
windows.open({
url: "http://www.example.com",
onOpen: function(window) {
}
});
}
});
I don`t know where to put the attributes of width,height,no scroll :/ in order to be displayd as a popup window.
And the second problem is that the button is displayed at the bar of addons.How it is possible to display it at the nav bar next to firebug?
The windows module does not support specifying window features.
You could use the unstable window/utils module and the openDialog function to provides.
Or you could get yourself chrome privileges and re-implement the stuff yourself. The implementation of openDialog is surprisingly pretty straight forward and can be borrowed from easily.
Either way, you'll need to wait for a window to actually fully load (newWindow.addEventListener("load", ...)) before you can safely interact with it. Or get somewhat hackish and listen for the first open event via the windows module.

Disable chrome context menu option on own site

How do I disable a context menu item created by my own chrome extension within my own site? For content scripts in a chrome extension, there is the excludes_matches option but context menus don't appear to have an equivalent.
I just don't want the context menu item I'm adding to show up when the user is on my own site.
UPDATE
People seem to be confused about what I'm doing so here's the code. In my "background_page" I add an item to the context menu like so:
chrome.contextMenus.create(
{
"title": "My Context Menu Item",
"contexts": ["link"],
"onclick": myContextItemClicked
});
The item shows up when a user right clicks on any <a> tag as expected. What I want to do is prevent it from showing up when a user is within my own site.
I solved similar problem by triggering menu creation on mousedown event in a content script injected to every page. Something like:
content script:
document.addEventListener("mousedown", function(event){
if(event.button == 2) {
chrome.extension.sendRequest({"createMenu"});
}
}, true);
background page:
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if(request === "createMenu") {
chrome.contextMenus.removeAll(function() {
if(sender.tab.url != "http://mysite.com") {
chrome.contextMenus.create({...});
}
});
}
});
Doesn't look very effective but there is no other way around afaik. It works pretty smooth though so users won't be able to see that you are recreating the menu before displaying it.

Categories