Google Chrome Extensions: create a window only once - javascript

I'm opening a new window by clicking on the extension button near the search bar.
I'd like to open a new window only if it's not already opened; in that case, I'd prefer showing the old one.
Here is my code, but it doesn't work.
var v = null;
var vid = null;
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.windows.getAll({}, function(list) {
// check if already exists
for(window in window_list)
if(window.id == vid) { window.focus(); return; }
chrome.windows.getCurrent(function(w) {
v = chrome.windows.create({'url': 'my_url', 'type': 'panel', 'focused': true});
vid = w.id;
});
});
});
Can someone explain me how to fix it?
Most probably, both v and vid values are deleted after closing the app (after it finish to execute the script), but how can I fix it? If possible, without using localStorage or cookies.
I've tried specifying the tabId properties while creating the window, but it doesn't work.
I've also tried using the chrome.windows.onRemoved.addListener functionality, but it doesn't work too.

Change window to another variable name.
Be consistent in variable names. window_list and list are different things.
Use chrome.windows.update instead of window.focus(), because the latter does not work.
Use chrome.windows.get to see whether the window exists, instead of maintaining a list of windows.
The details of the new window are available in the callback of chrome.windows.create. Use this method in the correct way:
Code:
chrome.windows.get(vid, function(chromeWindow) {
if (!chrome.runtime.lastError && chromeWindow) {
chrome.windows.update(vid, {focused: true});
return;
}
chrome.windows.create(
{'url': 'my_url', 'type': 'panel', 'focused': true},
function(chromeWindow) {
vid = chromeWindow.id;
}
);
});
Or, instead of checking whether the window exists, just update the window, and when an error occurs, open a new one:
chrome.windows.update(vid, {focused: true}, function() {
if (chrome.runtime.lastError) {
chrome.windows.create(
{'url': 'my_url', 'type': 'panel', 'focused': true},
function(chromeWindow) {
vid = chromeWindow.id;
});
}
});

chrome.windows.getAll({}, function(window_list) {
var extWindow = '';
window_list.forEach(function(chromeWindow) {
//Check windows by type
if (chromeWindow.type == 'panel') {
extWindow = chromeWindow.id;
//Update opened window
chrome.windows.update(extWindow, {focused: true});
return;
}
});
if (extWindow == '') {
//Open window
chrome.windows.create(
{
'url' : 'my_url',
'type' : 'panel',
'focused' : true
},
function(chromeWindow) {
extWindow = chromeWindow.id;
}
);
}
});
It is an alternative code that works for me

Related

How I can make a browser action button that looks and acts like a toggle

The target is get a WebExtension for Firefox that can be activated/deactivated by a user in the toolbar, like an on/off switch.
I'm using a background.js with this code:
browser.browserAction.onClicked.addListener(function (tab) {
switch (button) {
case 'turn-on':
enable();
break;
case 'turn-off':
disable();
break;
}
});
function enable() {
browser.browserAction.setIcon({ path: '/ui/is-on.png', });
browser.browserAction.setPopup({ popup: '/ui/turn-off.js', });
browser.webNavigation.onCommitted.addListener(onTabLoad);
}
function disable() {
browser.browserAction.setIcon({ path: '/ui/is-off.png', });
browser.browserAction.setPopup({ popup: '/ui/turn-on.js', });
browser.webNavigation.onCommitted.removeListener(onTabLoad);
}
function onTabLoad(details) {
browser.tabs.executeScript(details.tabId, {
file: '/gc.js',
allFrames true,
});
}
enable(); // enable or disable by default
Obviously I'm doing something wrong. I'm kind newbie in coding. This is a personal project I'm trying to finish.
Your code
While you added a switch statement to switch on button, you never defined button, nor changed its state. You also did not have a default case, just in case the button variable was not one of the values for which you were testing in your case statements.
You should not be using browserAction.setPopup() to set a popup. Setting a popup will result in the popup being opened instead of your background page receiving a click event. In addition, the popup needs to be an HTML page, not JavaScript.
See the section below for the Firefox bug which you need to work around in onTabLoad().
Listening to webNavigation.onCommitted is not sufficient to cover all cases of when your script will need to be injected. In other words, webNavigation.onCommitted does not fire every time a page is loaded. To fully cover every situation where your script will need to be injected is something that you will need to ask in another question.
var nextButtonState;
browser.browserAction.onClicked.addListener(function (tab) {
switch (nextButtonState) {
case 'turn-on':
enable();
break;
case 'turn-off':
default:
disable();
break;
}
});
function enable() {
browser.browserAction.setIcon({ path: '/ui/is-on.png', });
//browser.browserAction.setPopup({ popup: '/ui/turn-off.js', });
browser.webNavigation.onCommitted.addListener(onTabLoad);
nextButtonState = 'turn-off';
}
function disable() {
browser.browserAction.setIcon({ path: '/ui/is-off.png', });
//browser.browserAction.setPopup({ popup: '/ui/turn-on.js', });
browser.webNavigation.onCommitted.removeListener(onTabLoad);
nextButtonState = 'turn-on';
}
function onTabLoad(details) {
//Add a setTimout to avoid a Firefox bug that Firefox is not quite ready to
// have tabs.executeScript() inject a script when the onCommitted event fires.
setTimeout(function(){
chrome.tabs.executeScript(details.tabId, {
file: '/gc.js',
allFrames true,
});
},0);
}
enable(); // enable or disable by default
Workaround for a Firefox webNavigation.onCommitted bug
There is a change needed to your onTabLoad() code for using a webNavigation.onCommitted listener to inject scripts using tabs.executeScript() in Firefox (this is not needed in Chrome). This is due to a bug in Firefox which causes tabs.executeScript() to fail if executed immediately from a webNavigation.onCommitted listener. The workaround I use is to inject the script after a setTimeout(function,0) delay. This allows Firefox to execute the code needed to set up the environment necessary for executeScript() to be functional.
function onTabLoad(details) {
//Add a setTimout to avoid a Firefox bug that Firefox is not quite ready to
// have tabs.executeScript() inject a script when the onCommitted event fires.
setTimeout(function(){
chrome.tabs.executeScript(details.tabId, {
file: '/gc.js',
allFrames true,
});
},0);
}
Generalized solution for multi-state buttons (e.g. a toggle button)
The code I use to make a Browser Action button behave like a toggle is below. I have modified the browserButtonStates Object, which describes both what the buttons do and what they look like, to add and remove your webNavigation.onCommitted listener, onTabLoad(). See above for the issues with onTabLoad().
The code below is more complex than what you need. I wrote it intending to be able to move it from project to project with only needing to change the contents of the browserButtonStates object. Then, just by changing that object the icon, text, badge text, badge color, and action that is performed in each state (e.g. on/off) can be changed.
background.js
//The browserButtonStates Object describes the states the button can be in and the
// 'action' function to be called when the button is clicked when in that state.
// In this case, we have two states 'on' and 'off'.
// You could expand this to as many states as you desire.
//icon is a string, or details Object for browserAction.setIcon()
//title must be unique for each state. It is used to track the state.
// It indicates to the user what will happen when the button is clicked.
// In other words, it reflects what the _next_ state is, from the user's
// perspective.
//action is the function to call when the button is clicked in this state.
var browserButtonStates = {
defaultState: 'off',
on: {
icon : '/ui/is-on.png'
//badgeText : 'On',
//badgeColor : 'green',
title : 'Turn Off',
action : function(tab) {
chrome.webNavigation.onCommitted.removeListener(onTabLoad);
},
nextState : 'off'
},
off: {
icon : '/ui/is-off.png'
//badgeText : 'Off',
//badgeColor : 'red',
title : 'Turn On',
action : function(tab) {
chrome.webNavigation.onCommitted.addListener(onTabLoad);
},
nextState : 'on'
}
}
//This moves the Browser Action button between states and executes the action
// when the button is clicked. With two states, this toggles between them.
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.browserAction.getTitle({tabId:tab.id},function(title){
//After checking for errors, the title is used to determine
// if this is going to turn On, or Off.
if(chrome.runtime.lastError){
console.log('browserAction:getTitle: Encountered an error: '
+ chrome.runtime.lastError);
return;
}
//Check to see if the current button title matches a button state
let newState = browserButtonStates.defaultState;
Object.keys(browserButtonStates).some(key=> {
if(key === 'defaultState') {
return false;
}
let state = browserButtonStates[key];
if(title === state.title) {
newState = state.nextState;
setBrowserActionButton(browserButtonStates[newState]);
if(typeof state.action === 'function') {
//Do the action of the matching state
state.action(tab);
}
//Stop looking
return true;
}
});
setBrowserActionButton(browserButtonStates[newState]);
});
});
function setBrowserActionButton(tabId,details){
if(typeof tabId === 'object' && tabId !== null){
//If the tabId parameter is an object, then no tabId was passed.
details = tabId;
tabId = null;
}
let icon = details.icon;
let title = details.title;
let text = details.badgeText;
let color = details.badgeColor;
//Supplying a tabId is optional. If not provided, changes are to all tabs.
let tabIdObject = {};
if(tabId !== null && typeof tabId !== 'undefined'){
tabIdObject.tabId = tabId;
}
if(typeof icon === 'string'){
//Assume a string is the path to a file
// If not a string, then it needs to be a full Object as is to be passed to
// setIcon().
icon = {path:icon};
}
if(icon) {
Object.assign(icon,tabIdObject);
chrome.browserAction.setIcon(icon);
}
if(title) {
let detailsObject = {title};
Object.assign(detailsObject,tabIdObject);
chrome.browserAction.setTitle(detailsObject);
}
if(text) {
let detailsObject = {text};
Object.assign(detailsObject,tabIdObject);
chrome.browserAction.setBadgeText(detailsObject);
}
if(color) {
let detailsObject = {color};
Object.assign(detailsObject,tabIdObject);
chrome.browserAction.setBadgeBackgroundColor(detailsObject);
}
}
//Set the starting button state to the default state
setBrowserActionButton(browserButtonStates[browserButtonStates.defaultState]);
manifest.json:
{
"description": "Demo Button toggle",
"manifest_version": 2,
"name": "Demo Button toggle",
"version": "0.1",
"background": {
"scripts": [
"background.js"
]
},
"browser_action": {
"default_icon": {
"32": "myIcon.png"
},
"default_title": "Turn On",
"browser_style": true
}
}

Prompt to save / quit before closing window

I am making a writing application. Users can open the app, write some text, save their work, etc.
I am trying to make it so that clicking the window close button will prompt the user to (a) save their work (if necessary) or (b) just quit.
I am trying to use window.beforeunload to achieve this, but find I am getting stuck in a loop, where trying to "quit" makes the same prompt appear ad infinitum.
Here's some code:
windowCloseCheck() {
window.onbeforeunload = function(e) {
e.returnValue = false;
// window.alert('try to close me');
if(file.isUnsaved() || file.hasChanged()) {
// prompt - save or just quit?
file.fileWarning('You have unsaveeed work.', 'Save', 'Quit', function(){
// OPTION A - save
file.save();
}, function() {
// OPTION B: Quit.
ipcRenderer.send('quitter')
})
}
else {
// file is saved and no new work has been done:
ipcRenderer.send('quitter')
}
windowCloseCheck is invoked when the application is setup, initiating an event listener for closing the window. My conditional is checking if the file is unsaved or has changed from the original.
fileWarning is a function that just wraps the electron dialog box, making a pop up appear with two choices and respective functions to call for each choice.
The rest of the code is available if I'm (probably) leaving out necessary information. Would be happy to clarify if I'm not being very clear.
Please add following block inside the function where you have defined browser window(In my case it's createWindow() function declared in main.js)
// Create the browser window.
mainWindow = new BrowserWindow({width: 400, height: 400})
mainWindow.on('close', function(e){
var choice = require('electron').dialog.showMessageBox(this,
{
type: 'question',
buttons: ['Yes', 'No'],
title: 'Confirm',
message: 'Are you sure you want to quit?'
});
if(choice == 1){
e.preventDefault();
}
});
Answer for Electron 7+
The following is a working solution for latest Electron, based on awijeet's answer and Sergio Mazzoleni's comment.
At the bottom of createWindow(), below your win = new BrowserWindow(...), use:
win.on('close', function(e) {
const choice = require('electron').dialog.showMessageBoxSync(this,
{
type: 'question',
buttons: ['Yes', 'No'],
title: 'Confirm',
message: 'Are you sure you want to quit?'
});
if (choice === 1) {
e.preventDefault();
}
});
I ended up going with using window.destroy() to smash the render process to bits (from the main process):
ipcMain.on('quitter', (e) => {
mainWindow.destroy(); // necessary to bypass the repeat-quit-check in the render process.
app.quit()
})
Not really sure if this is recommended as there seem to be better ways to properly quit an electron app. Still happy to get any feedback if you know a better answer!
/shrug!
// Create the browser window.
mainWindow = new BrowserWindow({width: 400, height: 400})
mainWindow.on('close', function(e){
e.preventDefault();
var choice = require('electron').dialog.showMessageBox(mainWindow,
{
type: 'question',
buttons: ['Yes', 'No'],
title: 'Confirm',
message: 'Are you sure you want to quit?'
});
choice.then(function(res){
// 0 for Yes
if(res.response== 0){
// Your Code
}
// 1 for No
if(res.response== 1){
// Your Code
}
}
});
Notice that dialog.showMessageBox Returns Promise<Object> According to Electron Doc
And change this to mainWindow
This is modified answer for original answer to Awijeet
you can add a local variable to avoid mainWindow.destroy(), like:
let showExitPrompt = true;
// ask renderer process whether should close the app (mainWindow)
mainWindow.on('close', e => {
if (showExitPrompt) {
e.preventDefault(); // Prevents the window from closing
mainWindow.webContents.send('on-app-closing');
}
});
// renderer allows the app to close
ipcMain.on('quitter', (e) => {
showExitPrompt = false;
mainWindow.close();
})
Awijeet's solution is just perfect! Bth, thx Awijeet: it saved me hours! ;-)
In addition, if you need to go further, be aware e.preventDefault() is spreading everywhere in the code. Once you managed properly the preventDefault() you need to turn the variable e.defaultPrevented = false to get back to the natural behavior of your app.
Actually, it seems e.preventDefault() function is turnind the variable e.defaultPrevented to true until you change its value.
If the user would choose the save button, then we should save the data and close the window using window.close().
But, With this approach we will get an infinite loop that asks for saving the unsaved work because window.close() will emit window's close event again.
To solve this issue, we must declare a new boolean var forceQuit that initially set to false then we set it to true after saving the data or if the user decided to just close without saving the data.
import { app, BrowserWindow, dialog } from 'electron';
let win = null;
let forceQuit = false;
app.on('ready', () => {
win = new BrowserWindow({
// Your window options..
});
mainWindow.on('close', e => {
if (!forceQuit) {
const clickedButtonId = dialog.showMessageBox(mainWindow, {
type: 'warning',
buttons: ['Save', 'Cancel', `Don't save`],
cancelId: 1,
title: 'Confirm',
message: 'You have unsaved work!'
});
if (clickedButtonId === 0) {
e.preventDefault();
console.log('Saving...');
/** Here do your data saving logic */
forceQuit = true;
win.close();
} else if (clickedButtonId === 1) {
e.preventDefault();
} else if (clickedButtonId === 2) {
forceQuit = true;
win.close();
}
}
});
});

Refresh after a timer of 5000 seconds and print the alert

I am making a chrome extension to keep refreshing a page unless stop button is chosen. But i am able to do it only once. Here is my code for background.js
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
switch(request.type) {
case "table-row-count_start":
alert("Refershing started");
RefreshAndCount();
break;
case "table-row-count_stop":
alert("Stop Refershing");
break;
}
return true;
});
var RefreshAndCount = function() {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {type: "table-row-count"});
chrome.browserAction.setBadgeText({tabId: tabs[0].id, text: "Counting!"});
});
};
In content.js I did this :
chrome.extension.onMessage.addListener(function(message, sender, sendResponse) {
alert(message.type);
switch(message.type) {
case "table-row-count":
var x = document.querySelector('table').rows.length;
chrome.storage.sync.set({'value': x}, function() {
console.log('Settings saved');
});
chrome.storage.sync.get(["value"], function(items){
console.log(items);
});
alert("Row count = " + x);
setTimeout(function(){
location.reload();
},100);
break;
}
});
chrome.storage.onChanged.addListener(function(changes, namespace) {
for (key in changes) {
if(key=='value'){
var storageChange = changes[key];
console.log('Storage key "%s" in namespace "%s" changed. ' +
'Old value was "%s", new value is "%s".',
key,
namespace,
storageChange.oldValue,
storageChange.newValue);
}
}
});
After refresh I want to print the current row count alert everytime. Please help how to do this .
This work fine, for a single refresh but after that I again had to choose the start button from popup.
I want some way that I need not click start button again and the whole process repeats, storing the previous row count in cache or something.
popup.js
window.onload = function() {
document.getElementById("mystartbutton").onclick = function() {
chrome.extension.sendMessage({
type: "table-row-count_start"
});
}
document.getElementById("mystopbutton").onclick = function() {
chrome.extension.sendMessage({
type: "table-row-count_stop"
});
}
}
Also help me How to keep on refershing that page even if I switch to other tab or minimise my chrome ?
You can use the chrome.storage.local to store data that will be saved over time and over context where you use it. You can set a boolean to true or false to enable or disable autoreload. Then you only have to set it at click on browser action and check it in the content-script to know if you have to reload.
A possible and simple implemtation should be like this : (It depends of the expected behavior)
content.js (have to be injected in the page to autoreload)
var reloadDuration = 5000;
function autoreload()
{
chrome.local.storage.get("autoreload_enabled", function(result)
{
if(result.autoreload_enabled)
{
chrome.runtime.sendMessage({type: "table-row-count"});
window.location.reload();
}
}
}
setTimeout(autoreload, reloadDuration);
This will reload your page every reloadDuration if the boolean set in chrome local storage named autoreload_enabled is true.

Hide JS Notification Object By Tag Name

I'm using the notification API for my project to show browser notifications where each notification has a unique tag (ID), but I can't seem to find a way to close or hide the notification by the tag name, without calling the close function on the object, since it might be closed with other pages than where it was originated. Is this sort of thing possible?
You could save the notifications in localStorage and then retrieve it and close.
e.g.
// on create
var n = new Notification('Notification Title', {
tag: _this.attr('data-notification-id')
});
window.localStorage.setItem('data-notification-id', n);
and
// then later
var n = window.localStorage.getItem('data-notification-id');
n.close();
I've solved this now, but my solutions seems odd, so I'm still accepting other answers that follow a more "normal" approach.
Basically, a new notification object that is created with a tag while a notification that is currently already visible already has the same tag, the original notification is removed. So by creating a new notification object with the same tag and immediately removing it, I can "remove" the old notifications.
The link to view the notification
View this notification
And the jQuery
$('a[data-notification-id]').on('click', function(){
var _this = $(this);
var n = new Notification('Notification Title', {
tag: _this.attr('data-notification-id')
});
setTimeout(n.close.bind(n), 0);
});
You could stringify the notification options and save to session (or local) storage using the tag as the storage key. Then you can use the stored notification options to re-create/replace it and then call close.
Create the notification:
if (("Notification" in window)) {
if (Notification.permission === "granted") {
var options = {
body: sBody,
icon: sIcon,
title: sTitle, //used for re-create/close
requireInteraction: true,
tag: sTag
}
var n = new Notification(sTitle, options);
n.addEventListener("click", function (event) {
this.close();
sessionStorage.removeItem('notification-' + sTag);
}, false);
sessionStorage.setItem('notification-' + sTag, JSON.stringify(options));
}
}
Clear the notification:
function notificationClear(sTag) {
var options = JSON.parse(sessionStorage.getItem('notification-' + sTag));
if (options) {
options.requireInteraction = false;
if (("Notification" in window)) {
if (Notification.permission === "granted") {
var n = new Notification(options.title, options);
setTimeout(function () {
n.close();
sessionStorage.removeItem('notification-' + sTag);
}, 500); //can't close it immediately, so setTimeout is used
}
}
}
}

FireFox Toolbar Prefwindow unload/acceptdialog Event to Update the toolbar

I'm trying to develop a firefox toolbar ;)
so my structure is
In the options.xul is an PrefWindow which i'm opening over an
<toolbarbutton oncommand="esbTb_OpenPreferences()"/>
function esbTb_OpenPreferences() {
window.openDialog("chrome://Toolbar/content/options.xul", "einstellungen", "chrome,titlebar,toolbar,centerscreen,modal", this);}
so in my preferences i can set some checkboxes which indicates what links are presented in my toolbar. So when the preferences window is Closed or the "Ok" button is hitted I want to raise an event or an function which updates via DOM my toolbar.
So this is the function which is called when the toolbar is loaded. It sets the links visibility of the toolbar.
function esbTB_LoadMenue() {
var MenuItemNews = document.getElementById("esbTb_rss_reader");
var MenuItemEservice = document.getElementById("esbTb_estv");
if (!(prefManager.getBoolPref("extensions.esbtoolbar.ShowNews"))) {
MenuItemNews.style.display = 'none';
}
if (!(prefManager.getBoolPref("extensions.esbtoolbar.ShowEservice"))) {
MenuItemEservice.style.display = 'none';
}
}
So I tried some thinks like adding an eventlistener to the dialog which doesn't work... in the way I tried...
And i also tried to hand over the window object from the root window( the toolbar) as an argument of the opendialog function changed the function to this.
function esbTB_LoadMenue(RootWindow) {
var MenuItemNews = RootWindow.getElementById("esbTb_rss_reader");
var MenuItemEservice = RootWindow.getElementById("esbTb_estv");}
And then tried to Access the elements over the handover object, but this also not changed my toolbar at runtime.
So what i'm trying to do is to change the visibile links in my toolbar during the runtime and I don't get it how I should do that...
thanks in advance
-------edit-------
var prefManager = {
prefs: null,
start: function()
{
this.prefs = Components.classes["#mozilla.org/preferences-service;1"]
.getService(Components.interfaces.nsIPrefService)
.getBranch("extensions.esbtoolbar.");
this.prefs.QueryInterface(Components.interfaces.nsIPrefBranch2);
this.prefs.addObserver("", this, false);
},
end: function()
{
this.prefs.removeObserver("", this);
},
observe: function(subject, topic, data)
{
if (topic != "nsPref:changed")
{
return;
}
//Stuff what is done when Prefs have changed
esbTB_LoadMenue();
},
SetBoolPref: function(pref,value)
{
this.prefs.setBoolPref(pref,value);
},
GetBoolPref: function(pref)
{
this.prefs.getBoolPref(pref);
}
}
So this is my implementation.
The trick is to listen to preference changes. That way your toolbar updates whenever the prefs change -- regardless if it happened through your PrefWindow, about:config or some other mechanism.
In Toolbar.js you do the following
var esbTB_observe = function(subject, topic, data) {
if (topic != "nsPref:changed") {
return;
}
// find out which pref changed and do stuff
}
var esbTB_init = function() {
prefs =
Components.classes["#mozilla.org/preferences-service;1"]
.getService(Components.interfaces.nsIPrefService)
.getBranch("extensions.esbtoolbar.");
prefs.QueryInterface(Components.interfaces.nsIPrefBranch2);
prefs.addObserver("", esbTB_observe, false);
}
// Init addin after window loaded
window.addEventListener("load", esbTB_init, false);
Now, when the window loads, the esbTB_init() function is called in which the observer to the pref branch "extensions.esbtoolbar." is added. Later, when a pref in the branch is changed, the esbTB_observe() function is automatically called.
In esbTB_observe() you have to read the values of your prefs and adjust the toolbar.

Categories

Resources