Rewrite examples to use browser.* and promises (#138)

This commit is contained in:
wbamberg
2016-11-15 10:12:55 -08:00
committed by GitHub
parent 664239dac0
commit c5d69d15d6
33 changed files with 290 additions and 244 deletions

View File

@@ -11,17 +11,18 @@ function toggleCSS(tab) {
function gotTitle(title) {
if (title === TITLE_APPLY) {
chrome.pageAction.setIcon({tabId: tab.id, path: "icons/on.svg"});
chrome.pageAction.setTitle({tabId: tab.id, title: TITLE_REMOVE});
chrome.tabs.insertCSS({code: CSS});
browser.pageAction.setIcon({tabId: tab.id, path: "icons/on.svg"});
browser.pageAction.setTitle({tabId: tab.id, title: TITLE_REMOVE});
browser.tabs.insertCSS({code: CSS});
} else {
chrome.pageAction.setIcon({tabId: tab.id, path: "icons/off.svg"});
chrome.pageAction.setTitle({tabId: tab.id, title: TITLE_APPLY});
chrome.tabs.removeCSS({code: CSS});
browser.pageAction.setIcon({tabId: tab.id, path: "icons/off.svg"});
browser.pageAction.setTitle({tabId: tab.id, title: TITLE_APPLY});
browser.tabs.removeCSS({code: CSS});
}
}
chrome.pageAction.getTitle({tabId: tab.id}, gotTitle)
var gettingTitle = browser.pageAction.getTitle({tabId: tab.id});
gettingTitle.then(gotTitle);
}
/*
@@ -39,16 +40,17 @@ Only operates on tabs whose URL's protocol is applicable.
*/
function initializePageAction(tab) {
if (protocolIsApplicable(tab.url)) {
chrome.pageAction.setIcon({tabId: tab.id, path: "icons/off.svg"});
chrome.pageAction.setTitle({tabId: tab.id, title: TITLE_APPLY});
chrome.pageAction.show(tab.id);
browser.pageAction.setIcon({tabId: tab.id, path: "icons/off.svg"});
browser.pageAction.setTitle({tabId: tab.id, title: TITLE_APPLY});
browser.pageAction.show(tab.id);
}
}
/*
When first loaded, initialize the page action for all tabs.
*/
chrome.tabs.query({}, (tabs) => {
var gettingAllTabs = browser.tabs.query({});
gettingAllTabs.then((tabs) => {
for (tab of tabs) {
initializePageAction(tab);
}
@@ -57,11 +59,11 @@ chrome.tabs.query({}, (tabs) => {
/*
Each time a tab is updated, reset the page action for that tab.
*/
chrome.tabs.onUpdated.addListener((id, changeInfo, tab) => {
browser.tabs.onUpdated.addListener((id, changeInfo, tab) => {
initializePageAction(tab);
});
/*
Toggle CSS when the page action is clicked.
*/
chrome.pageAction.onClicked.addListener(toggleCSS);
browser.pageAction.onClicked.addListener(toggleCSS);

View File

@@ -7,7 +7,7 @@ beastify():
function beastify(request, sender, sendResponse) {
removeEverything();
insertBeast(request.beastURL);
chrome.runtime.onMessage.removeListener(beastify);
browser.runtime.onMessage.removeListener(beastify);
}
/*
@@ -34,4 +34,4 @@ function insertBeast(beastURL) {
/*
Assign beastify() as a listener for messages from the extension.
*/
chrome.runtime.onMessage.addListener(beastify);
browser.runtime.onMessage.addListener(beastify);

View File

@@ -4,11 +4,11 @@ Given the name of a beast, get the URL to the corresponding image.
function beastNameToURL(beastName) {
switch (beastName) {
case "Frog":
return chrome.extension.getURL("beasts/frog.jpg");
return browser.extension.getURL("beasts/frog.jpg");
case "Snake":
return chrome.extension.getURL("beasts/snake.jpg");
return browser.extension.getURL("beasts/snake.jpg");
case "Turtle":
return chrome.extension.getURL("beasts/turtle.jpg");
return browser.extension.getURL("beasts/turtle.jpg");
}
}
@@ -25,23 +25,22 @@ If it's on a button wich contains class "clear":
Reload the page.
Close the popup. This is needed, as the content script malfunctions after page reloads.
*/
document.addEventListener("click", function(e) {
document.addEventListener("click", (e) => {
if (e.target.classList.contains("beast")) {
var chosenBeast = e.target.textContent;
var chosenBeastURL = beastNameToURL(chosenBeast);
chrome.tabs.executeScript(null, {
browser.tabs.executeScript(null, {
file: "/content_scripts/beastify.js"
});
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {beastURL: chosenBeastURL});
var gettingActiveTab = browser.tabs.query({active: true, currentWindow: true});
gettingActiveTab.then((tabs) => {
browser.tabs.sendMessage(tabs[0].id, {beastURL: chosenBeastURL});
});
return;
}
else if (e.target.classList.contains("clear")) {
chrome.tabs.reload();
browser.tabs.reload();
window.close();
return;

View File

@@ -6,7 +6,7 @@ var currentBookmark;
* is already bookmarked.
*/
function updateIcon() {
chrome.browserAction.setIcon({
browser.browserAction.setIcon({
path: currentBookmark ? {
19: "icons/star-filled-19.png",
38: "icons/star-filled-38.png"
@@ -23,42 +23,47 @@ function updateIcon() {
*/
function toggleBookmark() {
if (currentBookmark) {
chrome.bookmarks.remove(currentBookmark.id);
browser.bookmarks.remove(currentBookmark.id);
currentBookmark = null;
updateIcon();
} else {
chrome.bookmarks.create({title: currentTab.title, url: currentTab.url}, function(bookmark) {
var creating = browser.bookmarks.create({title: currentTab.title, url: currentTab.url});
creating.then(function(bookmark) {
currentBookmark = bookmark;
updateIcon();
});
}
}
chrome.browserAction.onClicked.addListener(toggleBookmark);
browser.browserAction.onClicked.addListener(toggleBookmark);
/*
* Switches currentTab and currentBookmark to reflect the currently active tab
*/
function updateTab() {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
function updateActiveTab(tabs) {
function updateTab(tabs) {
if (tabs[0]) {
currentTab = tabs[0];
chrome.bookmarks.search({url: currentTab.url}, (bookmarks) => {
var searching = browser.bookmarks.search({url: currentTab.url});
searching.then((bookmarks) => {
currentBookmark = bookmarks[0];
updateIcon();
});
}
});
}
var gettingActiveTab = browser.tabs.query({active: true, currentWindow: true});
gettingActiveTab.then(updateTab);
}
// TODO listen for bookmarks.onCreated and bookmarks.onRemoved once Bug 1221764 lands
// listen to tab URL changes
chrome.tabs.onUpdated.addListener(updateTab);
browser.tabs.onUpdated.addListener(updateActiveTab);
// listen to tab switching
chrome.tabs.onActivated.addListener(updateTab);
browser.tabs.onActivated.addListener(updateActiveTab);
// update when the extension loads initially
updateTab();
updateActiveTab();

View File

@@ -14,18 +14,20 @@ var CATGIFS = "http://chilloutandwatchsomecatgifs.com/";
/*
Restart alarm for the currently active tab, whenever background.js is run.
*/
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
var gettingActiveTab = browser.tabs.query({active: true, currentWindow: true});
gettingActiveTab.then((tabs) => {
restartAlarm(tabs[0].id);
});
/*
Restart alarm for the currently active tab, whenever the user navigates.
*/
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
browser.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
if (!changeInfo.url) {
return;
}
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
var gettingActiveTab = browser.tabs.query({active: true, currentWindow: true});
gettingActiveTab.then((tabs) => {
if (tabId == tabs[0].id) {
restartAlarm(tabId);
}
@@ -35,7 +37,7 @@ chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
/*
Restart alarm for the currently active tab, whenever a new tab becomes active.
*/
chrome.tabs.onActivated.addListener(function (activeInfo) {
browser.tabs.onActivated.addListener((activeInfo) => {
restartAlarm(activeInfo.tabId);
});
@@ -44,11 +46,12 @@ restartAlarm: clear all alarms,
then set a new alarm for the given tab.
*/
function restartAlarm(tabId) {
chrome.pageAction.hide(tabId);
chrome.alarms.clearAll();
chrome.tabs.get(tabId, function(tab) {
browser.pageAction.hide(tabId);
browser.alarms.clearAll();
var gettingTab = browser.tabs.get(tabId);
gettingTab.then((tab) => {
if (tab.url != CATGIFS) {
chrome.alarms.create("", {delayInMinutes: DELAY});
browser.alarms.create("", {delayInMinutes: DELAY});
}
});
}
@@ -56,15 +59,16 @@ function restartAlarm(tabId) {
/*
On alarm, show the page action.
*/
chrome.alarms.onAlarm.addListener(function(alarm) {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.pageAction.show(tabs[0].id);
browser.alarms.onAlarm.addListener((alarm) => {
var gettingActiveTab = browser.tabs.query({active: true, currentWindow: true});
gettingActiveTab.then((tabs) => {
browser.pageAction.show(tabs[0].id);
});
});
/*
On page action click, navigate the corresponding tab to the cat gifs.
*/
chrome.pageAction.onClicked.addListener(function () {
chrome.tabs.update({url: CATGIFS});
browser.pageAction.onClicked.addListener(function () {
browser.tabs.update({url: CATGIFS});
});

View File

@@ -10,10 +10,11 @@
* shortcut: "Ctrl+Shift+U"
* }]
*/
chrome.commands.getAll(function(commands) {
commands.forEach(function(command) {
var gettingAllCommands = browser.commands.getAll();
gettingAllCommands.then((commands) => {
for (command of commands) {
console.log(command);
});
}
});
/**
@@ -22,6 +23,6 @@ chrome.commands.getAll(function(commands) {
* In this sample extension, there is only one registered command: "Ctrl+Shift+U".
* On Mac, this command will automatically be converted to "Command+Shift+U".
*/
chrome.commands.onCommand.addListener(function(command) {
browser.commands.onCommand.addListener((command) => {
console.log("onCommand event received for message: ", command);
});

View File

@@ -3,63 +3,67 @@ Called when the item has been created, or when creation failed due to an error.
We'll just log success/failure here.
*/
function onCreated(n) {
if (chrome.runtime.lastError) {
console.log("error creating item:" + chrome.runtime.lastError);
if (browser.runtime.lastError) {
console.log(`Error: ${browser.runtime.lastError}`);
} else {
console.log("item created successfully");
console.log("Item created successfully");
}
}
/*
Called when the item has been removed, or when there was an error.
We'll just log success or failure here.
Called when the item has been removed.
We'll just log success here.
*/
function onRemoved() {
if (chrome.runtime.lastError) {
console.log("error removing item:" + chrome.runtime.lastError);
} else {
console.log("item removed successfully");
console.log("Item removed successfully");
}
/*
Called when there was an error.
We'll just log the error here.
*/
function onError(error) {
console.log(`Error: ${error}`);
}
/*
Create all the context menu items.
*/
chrome.contextMenus.create({
browser.contextMenus.create({
id: "log-selection",
title: chrome.i18n.getMessage("contextMenuItemSelectionLogger"),
title: browser.i18n.getMessage("contextMenuItemSelectionLogger"),
contexts: ["selection"]
}, onCreated);
chrome.contextMenus.create({
browser.contextMenus.create({
id: "remove-me",
title: chrome.i18n.getMessage("contextMenuItemRemoveMe"),
title: browser.i18n.getMessage("contextMenuItemRemoveMe"),
contexts: ["all"]
}, onCreated);
chrome.contextMenus.create({
browser.contextMenus.create({
id: "separator-1",
type: "separator",
contexts: ["all"]
}, onCreated);
chrome.contextMenus.create({
browser.contextMenus.create({
id: "greenify",
type: "radio",
title: chrome.i18n.getMessage("contextMenuItemGreenify"),
title: browser.i18n.getMessage("contextMenuItemGreenify"),
contexts: ["all"],
checked: true
}, onCreated);
chrome.contextMenus.create({
browser.contextMenus.create({
id: "bluify",
type: "radio",
title: chrome.i18n.getMessage("contextMenuItemBluify"),
title: browser.i18n.getMessage("contextMenuItemBluify"),
contexts: ["all"],
checked: false
}, onCreated);
chrome.contextMenus.create({
browser.contextMenus.create({
id: "separator-2",
type: "separator",
contexts: ["all"]
@@ -67,10 +71,10 @@ chrome.contextMenus.create({
var checkedState = true;
chrome.contextMenus.create({
browser.contextMenus.create({
id: "check-uncheck",
type: "checkbox",
title: chrome.i18n.getMessage("contextMenuItemUncheckMe"),
title: browser.i18n.getMessage("contextMenuItemUncheckMe"),
contexts: ["all"],
checked: checkedState
}, onCreated);
@@ -85,7 +89,7 @@ var blue = 'document.body.style.border = "5px solid blue"';
var green = 'document.body.style.border = "5px solid green"';
function borderify(tabId, color) {
chrome.tabs.executeScript(tabId, {
browser.tabs.executeScript(tabId, {
code: color
});
}
@@ -101,12 +105,12 @@ property into the event listener.
function updateCheckUncheck() {
checkedState = !checkedState;
if (checkedState) {
chrome.contextMenus.update("check-uncheck", {
title: chrome.i18n.getMessage("contextMenuItemUncheckMe"),
browser.contextMenus.update("check-uncheck", {
title: browser.i18n.getMessage("contextMenuItemUncheckMe"),
});
} else {
chrome.contextMenus.update("check-uncheck", {
title: chrome.i18n.getMessage("contextMenuItemCheckMe"),
browser.contextMenus.update("check-uncheck", {
title: browser.i18n.getMessage("contextMenuItemCheckMe"),
});
}
}
@@ -115,13 +119,14 @@ function updateCheckUncheck() {
The click event listener, where we perform the appropriate action given the
ID of the menu item that was clicked.
*/
chrome.contextMenus.onClicked.addListener(function(info, tab) {
browser.contextMenus.onClicked.addListener(function(info, tab) {
switch (info.menuItemId) {
case "log-selection":
console.log(info.selectionText);
break;
case "remove-me":
chrome.contextMenus.remove(info.menuItemId, onRemoved);
var removing = browser.contextMenus.remove(info.menuItemId);
removing.then(onRemoved, onError);
break;
case "bluify":
borderify(tab.id, blue);

View File

@@ -1,25 +1,29 @@
/* Retrieve any previously set cookie and send to content script */
chrome.tabs.onUpdated.addListener(cookieUpdate);
browser.tabs.onUpdated.addListener(cookieUpdate);
function getActiveTab() {
return browser.tabs.query({active: true, currentWindow: true});
}
function cookieUpdate(tabId, changeInfo, tab) {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
getActiveTab().then((tabs) => {
/* inject content script into current tab */
chrome.tabs.executeScript(null, {
browser.tabs.executeScript(null, {
file: "/content_scripts/updatebg.js"
});
// get any previously set cookie for the current tab
chrome.cookies.get({
var gettingCookies = browser.cookies.get({
url: tabs[0].url,
name: "bgpicker"
}, function(cookie) {
});
gettingCookies.then((cookie) => {
if(cookie) {
var cookieVal = JSON.parse(cookie.value);
chrome.tabs.sendMessage(tabs[0].id, {image: cookieVal.image});
chrome.tabs.sendMessage(tabs[0].id, {color: cookieVal.color});
browser.tabs.sendMessage(tabs[0].id, {image: cookieVal.image});
browser.tabs.sendMessage(tabs[0].id, {color: cookieVal.color});
}
});
});

View File

@@ -1,7 +1,7 @@
var html = document.querySelector('html');
var body = document.querySelector('body');
chrome.runtime.onMessage.addListener(updateBg);
browser.runtime.onMessage.addListener(updateBg);
function updateBg(request, sender, sendResponse) {
if(request.image) {

View File

@@ -6,6 +6,10 @@ var reset = document.querySelector('.color-reset button');
var cookieVal = { image : '',
color : '' };
function getActiveTab() {
return browser.tabs.query({active: true, currentWindow: true});
}
/* apply backgrounds to buttons */
/* add listener so that when clicked, button applies background to page HTML */
@@ -15,13 +19,13 @@ for(var i = 0; i < bgBtns.length; i++) {
bgBtns[i].style.backgroundImage = bgImg;
bgBtns[i].onclick = function(e) {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
getActiveTab().then((tabs) => {
var imgName = e.target.getAttribute('class');
var fullURL = chrome.extension.getURL('popup/images/'+ imgName + '.png');
chrome.tabs.sendMessage(tabs[0].id, {image: fullURL});
var fullURL = browser.extension.getURL('popup/images/'+ imgName + '.png');
browser.tabs.sendMessage(tabs[0].id, {image: fullURL});
cookieVal.image = fullURL;
chrome.cookies.set({
browser.cookies.set({
url: tabs[0].url,
name: "bgpicker",
value: JSON.stringify(cookieVal)
@@ -33,12 +37,12 @@ for(var i = 0; i < bgBtns.length; i++) {
/* apply chosen color to HTML background */
colorPick.onchange = function(e) {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
getActiveTab().then((tabs) => {
var currColor = e.target.value;
chrome.tabs.sendMessage(tabs[0].id, {color: currColor});
browser.tabs.sendMessage(tabs[0].id, {color: currColor});
cookieVal.color = currColor;
chrome.cookies.set({
browser.cookies.set({
url: tabs[0].url,
name: "bgpicker",
value: JSON.stringify(cookieVal)
@@ -49,12 +53,12 @@ colorPick.onchange = function(e) {
/* reset background */
reset.onclick = function() {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {reset: true});
getActiveTab().then((tabs) => {
browser.tabs.sendMessage(tabs[0].id, {reset: true});
cookieVal = { image : '',
color : '' };
chrome.cookies.remove({
browser.cookies.remove({
url: tabs[0].url,
name: "bgpicker"
})
@@ -63,6 +67,9 @@ reset.onclick = function() {
/* Report cookie changes to the console */
chrome.cookies.onChanged.addListener(function(changeInfo) {
console.log('Cookie changed:\n* Cookie: ' + JSON.stringify(changeInfo.cookie) + '\n* Cause: ' + changeInfo.cause + '\n* Removed: ' + changeInfo.removed);
})
browser.cookies.onChanged.addListener((changeInfo) => {
console.log(`Cookie changed:\n
* Cookie: ${JSON.stringify(changeInfo.cookie)}\n
* Cause: ${changeInfo.cause}\n
* Removed: ${changeInfo.removed}`);
});

View File

@@ -1,7 +1,7 @@
"use strict";
browser.storage.local.get("super-important-user-setting", results => {
var gettingItem = browser.storage.local.get("super-important-user-setting");
gettingItem.then(results => {
const panelContent = results["super-important-user-setting"] || "No settings saved.";
document.querySelector("#panel-content").textContent = panelContent;
});

View File

@@ -1,7 +1,7 @@
"use strict";
browser.storage.local.set("super-important-user-setting", results => {
var gettingItem = browser.storage.local.get("super-important-user-setting");
gettingItem.then(results => {
const panelContent = results["super-important-user-setting"] || "No settings saved.";
document.querySelector("#panel-content").textContent = panelContent;
});

View File

@@ -1,3 +1,4 @@
browser.storage.local.get((results) => {
const gettingItem = browser.storage.local.get();
gettingItem.then((results) => {
document.querySelector("#panel-content").textContent = JSON.stringify(results, null, 2);
});

View File

@@ -1,4 +1,5 @@
browser.storage.local.get("prefs", results => {
const gettingItem = browser.storage.local.get("prefs");
gettingItem.then(results => {
const {prefs} = results || {
prefs: {
superImportantUserPref: "default value"

View File

@@ -1,3 +1,4 @@
browser.storage.local.get((results) => {
const gettingItem = browser.storage.local.get();
gettingItem.then((results) => {
document.querySelector("#panel-content").textContent = JSON.stringify(results, null, 2);
});

View File

@@ -1,5 +1,5 @@
function handleClick() {
chrome.runtime.openOptionsPage();
browser.runtime.openOptionsPage();
}
chrome.browserAction.onClicked.addListener(handleClick);
browser.browserAction.onClicked.addListener(handleClick);

View File

@@ -1,11 +1,12 @@
function saveOptions(e) {
chrome.storage.local.set({
browser.storage.local.set({
colour: document.querySelector("#colour").value
});
}
function restoreOptions() {
chrome.storage.local.get('colour', (res) => {
var gettingItem = browser.storage.local.get('colour');
gettingItem.then((res) => {
document.querySelector("#colour").value = res.colour || 'Firefox red';
});
}

View File

@@ -1,5 +1,5 @@
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
browser.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
if (!tab.url.match(/^about:/)) {
chrome.pageAction.show(tab.id);
browser.pageAction.show(tab.id);
}
});

View File

@@ -8,7 +8,7 @@ function get_hostname(url) {
function set_domain(domain) {
spans = document.getElementsByClassName('domain');
[].slice.call(spans).forEach(function(span) {
[].slice.call(spans).forEach((span) => {
span.textContent = domain;
});
}
@@ -20,17 +20,20 @@ function no_history(hostname) {
history_text.textContent = `No history for ${hostname}.`;
}
function getActiveTab() {
return browser.tabs.query({active: true, currentWindow: true});
}
// When the page is loaded find the current tab and then use that to query
// the history.
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
getActiveTab().then((tabs) => {
var list = document.getElementById('history');
var hostname = get_hostname(tabs[0].url);
chrome.history.search(
// Search for all history entries for the current windows domain.
// Because this could be a lot of entries, lets limit it to 5.
{text: hostname, maxResults: 5},
function(results) {
var searchingHistory = browser.history.search({text: hostname, maxResults: 5});
searchingHistory.then((results) => {
// What to show if there are no results.
if (results.length < 1) {
no_history(hostname);
@@ -47,25 +50,23 @@ chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
list.appendChild(li);
}
}
}
);
});
});
function clearAll(e) {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
getActiveTab().then((tabs) => {
var hostname = get_hostname(tabs[0].url);
if (!hostname) {
// Don't try and delete history when there's no hostname.
return;
}
chrome.history.search(
{text: hostname},
// Search will return us a list of histories for this domain.
// Loop through them and delete them one by one.
function(results) {
var searchingHistory = browser.history.search({text: hostname})
searchingHistory.then((results) => {
for (k = 0; k < results.length; k++) {
chrome.history.deleteUrl({url: results[k].url});
browser.history.deleteUrl({url: results[k].url});
}
// Clear out the UI.
no_history(hostname);

View File

@@ -3,22 +3,17 @@ var latestDownloadId;
/*
Callback from getFileIcon.
Log an error, or initialize the displayed icon.
Initialize the displayed icon.
*/
function updateIconUrl(iconUrl) {
/*
If there was an error getting the icon URL,
then lastError will be set. So check lastError
and handle it.
*/
if (chrome.runtime.lastError) {
console.error(chrome.runtime.lastError);
iconUrl = "";
}
var downloadIcon = document.querySelector("#icon");
downloadIcon.setAttribute("src", iconUrl);
}
function onError(error) {
console.log(`Error: ${error}`);
}
/*
If there was a download item,
- remember its ID as latestDownloadId
@@ -30,7 +25,8 @@ function initializeLatestDownload(downloadItems) {
var downloadUrl = document.querySelector("#url");
if (downloadItems.length > 0) {
latestDownloadId = downloadItems[0].id;
chrome.downloads.getFileIcon(latestDownloadId, updateIconUrl);
var gettingIconUrl = browser.downloads.getFileIcon(latestDownloadId);
gettingIconUrl.then(updateIconUrl, onError);
downloadUrl.textContent = downloadItems[0].url;
document.querySelector("#open").classList.remove("disabled");
document.querySelector("#remove").classList.remove("disabled");
@@ -44,17 +40,18 @@ function initializeLatestDownload(downloadItems) {
/*
Search for the most recent download, and pass it to initializeLatestDownload()
*/
chrome.downloads.search({
var searching = browser.downloads.search({
limit: 1,
orderBy: ["-startTime"]
}, initializeLatestDownload);
});
searching.then(initializeLatestDownload);
/*
Open the item using the associated application.
*/
function openItem() {
if (!document.querySelector("#open").classList.contains("disabled")) {
chrome.downloads.open(latestDownloadId);
browser.downloads.open(latestDownloadId);
}
}
@@ -63,8 +60,8 @@ Remove item from disk (removeFile) and from the download history (erase)
*/
function removeItem() {
if (!document.querySelector("#remove").classList.contains("disabled")) {
chrome.downloads.removeFile(latestDownloadId);
chrome.downloads.erase({id: latestDownloadId});
browser.downloads.removeFile(latestDownloadId);
browser.downloads.erase({id: latestDownloadId});
window.close();
}
}

View File

@@ -3,7 +3,8 @@ function showCookiesForTab(tabs) {
tab = tabs.pop();
//get all cookies in the domain
chrome.cookies.getAll({url: tab.url}, (cookies) => {
var gettingAllCookies = browser.cookies.getAll({url: tab.url});
gettingAllCookies.then((cookies) => {
//set the header of the panel
var activeTabUrl = document.getElementById('header-title');
@@ -32,4 +33,7 @@ function showCookiesForTab(tabs) {
//get active tab to run an callback function.
//it sends to our callback an array of tab objects
chrome.tabs.query({currentWindow: true, active: true}, showCookiesForTab);
function getActiveTab() {
return browser.tabs.query({currentWindow: true, active: true});
}
getActiveTab().then(showCookiesForTab);

View File

@@ -1,5 +1,6 @@
// Load existent stats with the storage API.
chrome.storage.local.get("hostNavigationStats", results => {
var gettingStoredStats = browser.storage.local.get("hostNavigationStats");
gettingStoredStats.then(results => {
// Initialize the saved stats if not yet initialized.
if (!results.hostNavigationStats) {
results = {
@@ -11,7 +12,7 @@ chrome.storage.local.get("hostNavigationStats", results => {
// Monitor completed navigation events and update
// stats accordingly.
chrome.webNavigation.onCompleted.addListener(evt => {
browser.webNavigation.onCompleted.addListener(evt => {
// Filter out any sub-frame related navigation event
if (evt.frameId !== 0) {
return;
@@ -23,6 +24,7 @@ chrome.storage.local.get("hostNavigationStats", results => {
hostNavigationStats[url.hostname]++;
// Persist the updated stats.
chrome.storage.local.set(results);
}, { url: [{schemes: ["http", "https"]}]});
browser.storage.local.set(results);
}, {
url: [{schemes: ["http", "https"]}]});
});

View File

@@ -1,5 +1,6 @@
// Get the saved stats and render the data in the popup window.
chrome.storage.local.get("hostNavigationStats", results => {
var gettingStoredStats = browser.storage.local.get("hostNavigationStats");
gettingStoredStats.then(results => {
if (!results.hostNavigationStats) {
return;
}

View File

@@ -5,11 +5,11 @@ which we read from the message.
*/
function notify(message) {
console.log("background script received message");
var title = chrome.i18n.getMessage("notificationTitle");
var content = chrome.i18n.getMessage("notificationContent", message.url);
chrome.notifications.create({
var title = browser.i18n.getMessage("notificationTitle");
var content = browser.i18n.getMessage("notificationContent", message.url);
browser.notifications.create({
"type": "basic",
"iconUrl": chrome.extension.getURL("icons/link-48.png"),
"iconUrl": browser.extension.getURL("icons/link-48.png"),
"title": title,
"message": content
});
@@ -18,4 +18,4 @@ function notify(message) {
/*
Assign `notify()` as a listener to messages from the content script.
*/
chrome.runtime.onMessage.addListener(notify);
browser.runtime.onMessage.addListener(notify);

View File

@@ -11,7 +11,7 @@ function notifyExtension(e) {
return;
console.log("content script sending message");
chrome.runtime.sendMessage({"url": target.href});
browser.runtime.sendMessage({"url": target.href});
}
/*

View File

@@ -3,7 +3,7 @@ Open a new tab, and load "my-page.html" into it.
*/
function openMyPage() {
console.log("injecting");
chrome.tabs.create({
browser.tabs.create({
"url": chrome.extension.getURL("my-page.html")
});
}
@@ -12,5 +12,5 @@ function openMyPage() {
/*
Add openMyPage() as a listener to clicks on the browser action.
*/
chrome.browserAction.onClicked.addListener(openMyPage);
browser.browserAction.onClicked.addListener(openMyPage);

View File

@@ -14,23 +14,24 @@ var addBtn = document.querySelector('.add');
addBtn.addEventListener('click', addNote);
clearBtn.addEventListener('click', clearAll);
/* generic error handler */
function onError(error) {
console.log(error);
}
/* display previously-saved stored notes on startup */
initialize();
function initialize() {
chrome.storage.local.get(null,function(results) {
if(chrome.runtime.lastError) {
console.log(chrome.runtime.lastError);
} else {
var gettingAllStorageItems = browser.storage.local.get(null);
gettingAllStorageItems.then((results) => {
var noteKeys = Object.keys(results);
for(i = 0; i < noteKeys.length; i++) {
var curKey = noteKeys[i];
var curValue = results[curKey];
displayNote(curKey,curValue);
for(noteKey of noteKeys) {
var curValue = results[noteKey];
displayNote(noteKey,curValue);
}
}
});
}, onError);
}
/* Add a note to the display, and storage */
@@ -38,26 +39,24 @@ function initialize() {
function addNote() {
var noteTitle = inputTitle.value;
var noteBody = inputBody.value;
chrome.storage.local.get(noteTitle, function(result) {
var gettingItem = browser.storage.local.get(noteTitle);
gettingItem.then((result) => {
var objTest = Object.keys(result);
if(objTest.length < 1 && noteTitle !== '' && noteBody !== '') {
inputTitle.value = '';
inputBody.value = '';
storeNote(noteTitle,noteBody);
}
})
}, onError);
}
/* function to store a new note in storage */
function storeNote(title, body) {
chrome.storage.local.set({ [title] : body }, function() {
if(chrome.runtime.lastError) {
console.log(chrome.runtime.lastError);
} else {
var storingNote = browser.storage.local.set({ [title] : body });
storingNote.then(() => {
displayNote(title,body);
}
});
}, onError);
}
/* function to display a note in the note box */
@@ -92,7 +91,7 @@ function displayNote(title, body) {
deleteBtn.addEventListener('click',function(e){
evtTgt = e.target;
evtTgt.parentNode.parentNode.parentNode.removeChild(evtTgt.parentNode.parentNode);
chrome.storage.local.remove(title);
browser.storage.local.remove(title);
})
/* create note edit box */
@@ -155,15 +154,17 @@ function displayNote(title, body) {
/* function to update notes */
function updateNote(delNote,newTitle,newBody) {
chrome.storage.local.set({ [newTitle] : newBody }, function() {
var storingNote = browser.storage.local.set({ [newTitle] : newBody });
storingNote.then(() => {
if(delNote !== newTitle) {
chrome.storage.local.remove(delNote, function() {
var removingNote = browser.storage.local.remove(delNote);
removingNote.then(() => {
displayNote(newTitle, newBody);
});
}, onError);
} else {
displayNote(newTitle, newBody);
}
});
}, onError);
}
/* Clear all notes from the display/storage */
@@ -172,5 +173,5 @@ function clearAll() {
while (noteContainer.firstChild) {
noteContainer.removeChild(noteContainer.firstChild);
}
chrome.storage.local.clear();
browser.storage.local.clear();
}

View File

@@ -12,9 +12,13 @@ function firstUnpinnedTab(tabs) {
}
}
function getCurrentWindowTabs() {
return browser.tabs.query({currentWindow: true});
}
document.addEventListener("click", function(e) {
function callOnActiveTab(callback) {
chrome.tabs.query({currentWindow: true}, function(tabs) {
getCurrentWindowTabs().then((tabs) => {
for (var tab of tabs) {
if (tab.active) {
callback(tab, tabs);
@@ -29,7 +33,8 @@ document.addEventListener("click", function(e) {
if (!tab.pinned) {
index = firstUnpinnedTab(tabs);
}
chrome.tabs.move([tab.id], {index});
console.log(`moving ${tab.id} to ${index}`)
browser.tabs.move([tab.id], {index});
});
}
@@ -40,30 +45,30 @@ document.addEventListener("click", function(e) {
var lastPinnedTab = Math.max(0, firstUnpinnedTab(tabs) - 1);
index = lastPinnedTab;
}
chrome.tabs.move([tab.id], {index});
browser.tabs.move([tab.id], {index});
});
}
else if (e.target.id === "tabs-duplicate") {
callOnActiveTab((tab) => {
chrome.tabs.duplicate(tab.id);
browser.tabs.duplicate(tab.id);
});
}
else if (e.target.id === "tabs-reload") {
callOnActiveTab((tab) => {
chrome.tabs.reload(tab.id);
browser.tabs.reload(tab.id);
});
}
else if (e.target.id === "tabs-remove") {
callOnActiveTab((tab) => {
chrome.tabs.remove(tab.id);
browser.tabs.remove(tab.id);
});
}
else if (e.target.id === "tabs-create") {
chrome.tabs.create({url: "https://developer.mozilla.org/en-US/Add-ons/WebExtensions"});
browser.tabs.create({url: "https://developer.mozilla.org/en-US/Add-ons/WebExtensions"});
}
else if (e.target.id === "tabs-alertinfo") {
@@ -78,7 +83,8 @@ document.addEventListener("click", function(e) {
else if (e.target.id === "tabs-add-zoom") {
callOnActiveTab((tab) => {
chrome.tabs.getZoom(tab.id, function(zoomFactor){
var gettingZoom = browser.tabs.getZoom(tab.id);
gettingZoom.then((zoomFactor) => {
//the maximum zoomFactor is 3, it can't go higher
if (zoomFactor >= MAX_ZOOM) {
alert("Tab zoom factor is already at max!");
@@ -87,7 +93,7 @@ document.addEventListener("click", function(e) {
//if the newZoomFactor is set to higher than the max accepted
//it won't change, and will never alert that it's at maximum
newZoomFactor = newZoomFactor > MAX_ZOOM ? MAX_ZOOM : newZoomFactor;
chrome.tabs.setZoom(tab.id, newZoomFactor);
browser.tabs.setZoom(tab.id, newZoomFactor);
}
});
});
@@ -95,7 +101,8 @@ document.addEventListener("click", function(e) {
else if (e.target.id === "tabs-decrease-zoom") {
callOnActiveTab((tab) => {
chrome.tabs.getZoom(tab.id, function(zoomFactor){
var gettingZoom = browser.tabs.getZoom(tab.id);
gettingZoom.then((zoomFactor) => {
//the minimum zoomFactor is 0.3, it can't go lower
if (zoomFactor <= MIN_ZOOM) {
alert("Tab zoom factor is already at minimum!");
@@ -104,7 +111,7 @@ document.addEventListener("click", function(e) {
//if the newZoomFactor is set to lower than the min accepted
//it won't change, and will never alert that it's at minimum
newZoomFactor = newZoomFactor < MIN_ZOOM ? MIN_ZOOM : newZoomFactor;
chrome.tabs.setZoom(tab.id, newZoomFactor);
browser.tabs.setZoom(tab.id, newZoomFactor);
}
});
});
@@ -112,11 +119,12 @@ document.addEventListener("click", function(e) {
else if (e.target.id === "tabs-default-zoom") {
callOnActiveTab((tab) => {
chrome.tabs.getZoom(tab.id, function(zoomFactor){
var gettingZoom = browser.tabs.getZoom(tab.id);
gettingZoom.then((zoomFactor) => {
if (zoomFactor == DEFAULT_ZOOM) {
alert("Tab zoom is already at the default zoom factor");
} else {
chrome.tabs.setZoom(tab.id, DEFAULT_ZOOM);
browser.tabs.setZoom(tab.id, DEFAULT_ZOOM);
}
});
});
@@ -125,7 +133,7 @@ document.addEventListener("click", function(e) {
else if (e.target.id === "tabs-highlight") { // highlights current tab and next tab (cycles back to first tab if current tab is the last one)
callOnActiveTab((tab, tabs) => {
next = (tab.index+1) % tabs.length;
chrome.tabs.highlight({tabs:[tab.index, next]});
browser.tabs.highlight({tabs:[tab.index, next]});
});
}
@@ -133,7 +141,7 @@ document.addEventListener("click", function(e) {
});
//onRemoved listener. fired when tab is removed
chrome.tabs.onRemoved.addListener(function(tabId, removeInfo){
browser.tabs.onRemoved.addListener(function(tabId, removeInfo){
console.log(`The tab with id: ${tabId}, is closing`);
if(removeInfo.isWindowClosing) {
@@ -144,7 +152,7 @@ chrome.tabs.onRemoved.addListener(function(tabId, removeInfo){
});
//onMoved listener. fired when tab is moved into the same window
chrome.tabs.onMoved.addListener(function(tabId, moveInfo){
browser.tabs.onMoved.addListener(function(tabId, moveInfo){
var startIndex = moveInfo.fromIndex;
var endIndex = moveInfo.toIndex;
console.log(`Tab with id: ${tabId} moved from index: ${startIndex} to index: ${endIndex}`);

View File

@@ -37,7 +37,7 @@ only for the target page.
Make it "blocking" so we can modify the headers.
*/
chrome.webRequest.onBeforeSendHeaders.addListener(rewriteUserAgentHeader,
browser.webRequest.onBeforeSendHeaders.addListener(rewriteUserAgentHeader,
{urls: [targetPage]},
["blocking", "requestHeaders"]);

View File

@@ -10,6 +10,6 @@ document.addEventListener("click", function(e) {
}
var chosenUa = e.target.textContent;
var backgroundPage = chrome.extension.getBackgroundPage();
var backgroundPage = browser.extension.getBackgroundPage();
backgroundPage.setUaString(chosenUa);
});

View File

@@ -1,6 +1,6 @@
const leftPad = require("left-pad");
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
browser.runtime.onMessage.addListener((message, sender, sendResponse) => {
const result = leftPad(message.text, message.amount, message.with);
sendResponse(result);
});

View File

@@ -13,11 +13,12 @@ document.getElementById("leftpad-form").addEventListener("submit", (e) => {
}, false);
document.getElementById("pad-bg").addEventListener("click", (e) => {
chrome.runtime.sendMessage({
var sendingMessage = browser.runtime.sendMessage({
text: textNode.value,
amount: amountNode.valueAsNumber,
with: withNode.value
}, (result) => {
});
sendingMessage.then((result) => {
resultNode.value = result;
});
});

View File

@@ -1,29 +1,27 @@
document.addEventListener("click", (e) => {
function callOnCurrentWindow(callback){
chrome.windows.getCurrent((currentWindow) => {
callback(currentWindow);
});
function getCurrentWindow() {
return browser.windows.getCurrent();
}
if (e.target.id === "window-update-size_768") {
callOnCurrentWindow((currentWindow) => {
getCurrentWindow().then((currentWindow) => {
var updateInfo = {
width: 768,
height: 1024
};
chrome.windows.update(currentWindow.id, updateInfo);
browser.windows.update(currentWindow.id, updateInfo);
});
}
if (e.target.id === "window-update-minimize") {
callOnCurrentWindow((currentWindow) => {
getCurrentWindow().then((currentWindow) => {
var updateInfo = {
state: "minimized"
};
chrome.windows.update(currentWindow.id, updateInfo);
browser.windows.update(currentWindow.id, updateInfo);
});
}
@@ -31,25 +29,27 @@ document.addEventListener("click", (e) => {
var createData = {
incognito: true,
};
chrome.windows.create(createData, () => {
var creating = browser.windows.create(createData);
creating.then(() => {
console.log("The incognito window has been created");
});
}
else if (e.target.id === "window-remove") {
callOnCurrentWindow((currentWindow) => {
chrome.windows.remove(currentWindow.id);
getCurrentWindow().then((currentWindow) => {
browser.windows.remove(currentWindow.id);
});
}
else if (e.target.id === "window-resize-all") {
chrome.windows.getAll((windows) => {
var gettingAll = browser.windows.getAll();
gettingAll.then((windows) => {
var updateInfo = {
width: 1024,
height: 768
};
for (var item of windows) {
chrome.windows.update(item.id, updateInfo);
browser.windows.update(item.id, updateInfo);
}
});
}