chrome.action.setIcon failureCallback is not a function - javascript

I'm trying to change the extension icon depending on what is found in the URL, the below works but i get an error:
Uncaught (in promise) TypeError: failureCallback is not a function
Context
extensions::setIcon
Stack Trace
I feel sure this is a woods for the trees thing. Can anyone help?
//get url of the page we are on in the tab
async function getTab() {
let queryOptions = { active: true, currentWindow: true };
let tabs = await chrome.tabs.query(queryOptions);
return tabs[0];
};
var tab;
//listen for the following two events - when they happen run the colourIcon function
chrome.tabs.onActivated.addListener(colourIcon);
chrome.tabs.onUpdated.addListener(colourIcon);
async function colourIcon(){
let urlCol = await getTab()
let url = urlCol.url
tab = urlCol.id
if (url.indexOf("d") > -1) {
changeIconColour("purple");
} else if (url.indexOf("b") > -1) {
changeIconColour("purple");
} else if (url.indexOf("a") > -1) {
changeIconColour("purple");
} else { // if there is no match, you can't get the data
changeIconColour("grey");
};
}
function changeIconColour(colour) {
let pathToIcons;
//change the path to the icon folder depending on what colour is sent to the function
if (colour == "purple") {
pathToIcons = "/";
} else {
pathToIcons = "grey/";
}
// and set the icon
chrome.action.setIcon({
path: {
"16": "/assets/icons" + pathToIcons + "extension_toolbar_icon16.png",
"32": "/assets/icons" + pathToIcons + "extension_toolbar_icon32.png",
"48": "/assets/icons" + pathToIcons + "extension_toolbar_icon48.png",
"128": "/assets/icons" + pathToIcons + "extension_toolbar_icon128.png"
},
tabId: tab
})
};
The error is at extensions::setIcon:35, which is the line starting "failure", here:
$Promise.catch(imageDataPromise, function(error) {
failureCallback(exceptionHandler.safeErrorToString(error, true));
});

It's a bug in Chromium.
Suggests an invalid filepath. But it works.

Related

Office.js outlook add-in issue

I'm trying to get the Body in Outlook and then update/set it with categories. My issue is this - when I debug it - it works fine. But when I don't debug from function to function - it gets all the way to the last function and just stops - updateBody(). What's really strang is if I remove the breakpoints on each function and just set a breakpoint on last function - never gets hit, but console will write out "Starting update body". All the console.logs are writing out data as expected. Not sure what is going on. Appreciate any help! Thanks.
"use strict";
var item;
var response;
var tags;
var updatedBody;
Office.initialize = function () {
$(document).ready(function () {
// The document is ready
item = Office.context.mailbox.item;
debugger;
getBodyType();
});
}
function getBodyType() {
item.body.getTypeAsync(
function (resultBody) {
if (resultBody.status == Office.AsyncResultStatus.Failed) {
write(resultBody.error.message);
} else {
response = resultBody;
console.log('Successfully got BodyType');
console.log(response.value);
getCategories();
}
});
}
function getCategories() {
tags = "";
// Successfully got the type of item body.
// Set data of the appropriate type in body.
item.categories.getAsync(function (asyncResult) {
if (asyncResult.status === Office.AsyncResultStatus.Failed) {
console.log("Action failed with error: " + asyncResult.error.message);
} else {
var categories = asyncResult.value;
console.log("Categories:");
categories.forEach(function (item) {
var tag = item.displayName;
tags += '#' + tag.replace(/\s/g, "") + ' ';
});
console.log('Successfully got tags');
console.log(tags);
getBody();
}
});
}
function getBody() {
var body = "";
updatedBody = "";
console.log("Starting get body");
if (response.value == Office.MailboxEnums.BodyType.Html) {
item.body.getAsync(
Office.CoercionType.Html,
{ asyncContext: "This is passed to the callback" },
function (result) {
//Replace all the # tags and update again.
body = result.value.replaceAll(/#(\w)+/g, "").trimEnd();
var domParser = new DOMParser();
var parsedHtml = domParser.parseFromString(body, "text/html");
$("body", parsedHtml).append("<div>" + tags + "</div>");
var changedString = (new XMLSerializer()).serializeToString(parsedHtml);
if (changedString != "") {
updatedBody = changedString;
}
console.log(updatedBody);
updateBody();
});
}
}
function updateBody() {
console.log("Starting update body");
item.body.setAsync(
updatedBody,
{ coercionType: Office.CoercionType.Html },
function (result2) {
console.log("Body updated");
});
}
Image - With breakpoints on each function - works as expected
Image - Without breakpoints - gets to updateBody() function.
But the string updatedBody isn't logged. It somehow skips over that
even though it's called before updateBody() on getBody()
Image - Same code run via Script Lab - works just fine as well.

How can i excute script New page in chrome extension?

I make chrome extension.
this program read now page and anlysis it, go to next page.
I already made read and goto next page. but there a problem.
read now page and move next page is perfect. but next page, read function isn't work.
I click read button on first page, read it. but move next and read, not work.
i see callback function get undefined data.
below is my code.
function matching(user) {
JustFIDsFromPage();
}
function JustFindIDsFromPage() {
//read and find Data
chrome.tabs.executeScript({
code: "var ids = [];var names = document.querySelector('.gallery').children;for(var i=0;i<names.length;i++){var tmp = names[i].innerHTML;var id = tmp.substring(11+tmp.search('/galleries/'),tmp.search('.html'));ids.push(id)} ids"
}, callbackJustFindIDsFromPage);
}
function callbackJustFindIDsFromPage(count) {
//save get datas.
var idList = count.toString().split(',');
for (var i = 0; i < idList.length; i++) {
document.querySelector('#result').innerText += idList[i] + "\n";
}
//go to next page.
chrome.tabs.executeScript({
code: "var page = document.querySelector('.page').firstElementChild.children; var end=0; var inhtml = page[1].innerHTML;var intext = page[1].innerText; if(inhtml == intext){var link = page[2].innerHTML; var url = link.substring(9, 20); end=1; window.location.href = url; } end;"
}, callbackGoNextPage);
}
function callbackGoNextPage(nextFlag) {
if (nextFlag == 1) {
JustFindIDsFromPage();
}
}
I guess this.
chrome.tabs.executeScript just excute on 'first' open page.
I don't know what is real. please help me!
this code will work for you.
chrome.tabs.getSelected(null, function (tabss) {
tabid = tabss.TAB_ID_NONE;
});
chrome.tabs.update(tabid, { url: url, active: true }, function (tab1) {
var listener = function (tabId, changeInfo, tab) {
if (tabId == tab1.id && changeInfo.status === 'complete') {
chrome.tabs.onUpdated.removeListener(listener);
//your code
}
}
chrome.tabs.onUpdated.addListener(listener);
});

chrome.storage.sync.get Error

I've been trying to use chrome.storage.sync.get for the options part of my program but I've hit a snag.
document.addEventListener('DOMContentLoaded', function() {
document.getElementById("save").addEventListener("click", save_options);
});
function save_options() {
var priceNotif = document.getElementById('pricealert').value;
chrome.storage.sync.set({
priceAlert: priceNotif
}, function() {
// Update status to let user know options were saved.
console.log("price set: " + priceNotif);
setTimeout(function() {
status.textContent = '';
}, 750);
});
}
var test = chrome.storage.sync.get('priceAlert', function(data) {
test = data.priceAlert;
});
console.log("test price get: " + test);
The test variable is returning undefined, and how do I fix that?
if you are creating chrome extension then you can use Please confirm that you need to add needfull permission in manifest.JSON file. please refer below document.
https://developer.chrome.com/extensions/storage

How to display the body of an email with a thunderbird-addon?

This is my code :
var newMailListener = {
msgAdded: function(aMsgHdr) {
if(!aMsgHdr.isRead) {
gFolderDisplay.selectMessage(aMsgHdr);
var uri = gFolderDisplay.selectedMessageUris;
alert(uri);
msgHdr = messenger.messageServiceFromURI(uri).messageURIToMsgHdr(uri);
alert(getMessageBody(msgHdr,uri));
goDoCommand("cmd_markAsRead");
}
}
};
function init() {
var ancienmsg = null;
var notificationService = Components.classes["#mozilla.org/messenger/msgnotificationservice;1"]
.getService(Components.interfaces.nsIMsgFolderNotificationService);
notificationService.addListener(newMailListener, notificationService.msgAdded);
}
addEventListener("load", init, true);
function getMessageBody(aMessageHeader, uri)
{
let messenger = Components.classes["#mozilla.org/messenger;1"] .createInstance(Components.interfaces.nsIMessenger);
alert("charge messenger");
let listener = Components.classes["#mozilla.org/network/sync-stream-listener;1"].createInstance(Components.interfaces.nsISyncStreamListener);
alert("charge listener");
messenger.messageServiceFromURI(uri)
.streamMessage(uri, listener, null, null, false, "");
let folder = aMessageHeader.folder;
alert("initialise messenger");
return folder.getMsgTextFromStream(listener.inputStream,
aMessageHeader.Charset,
65536,
32768,
false,
true,
{ });
}
It is supposed, according to the mozilla's documentation, to display, in an alert, the body of the mail received. But, every time during the return of the getMessageBody method, thunderbird crash and I need to restart it. Does anybody have an idea of why and how to display it ?
In another Stackoverflow question, I find this and it works for me.
Components.utils.import("resource:///modules/gloda/mimemsg.js");
var newMailListener = {
msgAdded: function(aMsgHdr) {
if( !aMsgHdr.isRead ){
MsgHdrToMimeMessage(aMsgHdr, null, function (aMsgHdr, aMimeMessage) {
// do something with aMimeMessage:
alert("the message body : " + aMimeMessage.coerceBodyToPlaintext());
//alert(aMimeMessage.allUserAttachments.length);
//alert(aMimeMessage.size);
}, true);
}
}
};
But you only get the text and not the HTML.

Saving in local storage not working

I'm building on top of an existing chrome extension, and I'm trying to maintain a consistent style. I need add a new feature, and I use the following script to save a user's choice from the popup selection, and then set a new popup going forward based on the saved choice.
userchoices.js:
require.scopes["userchoices"] = (function() {
var exports = {};
var userChoices = exports.userChoices = {
userchoices: {},
updateChoice: function(){
self = this;
chrome.storage.local.get('userchoices', function(items){
if(!items.userchoices){
chrome.storage.local.set({userchoices: self.userchoices});
return;
}
self.userchoices = items.userchoices;
});
},
getChoice: function(url){
if(this.userchoices[url]){
return this.userchoices[url][choice];
} else {
return {};
}
},
setChoice: function(url, newChoice){
if(!this.userchoices[url]){
this.userchoices[url] = {};
}
this.userchoices[url][choice] = newChoice;
chrome.storage.local.set({userchoices: this.userchoices});
},
removeChoice: function(url){
if(!this.userchoices[url]){
return;
} else {
delete this.userchoices[url]
}
chrome.storage.local.set({userchoices: this.userchoices});
}
}
return exports;
})();
background.js:
var userChoices= require("userchoices").userChoices;
chrome.windows.onCreated.addListener(function(){
CookieBlockList.updateDomains();
BlockedDomainList.updateDomains();
FakeCookieStore.updateCookies();
userChoices.updateChoice();
});
function refreshIconAndContextMenu(tab)
{
// The tab could have been closed by the time this function is called
if(!tab)
return;
var choice = userChoices.getChoice(tab.url);
if(choice) {
if (choice == "one"){
chrome.browserAction.setPopup({tabId: tab.id, popup: "skin/popupDontCare.html"});
} else if(choice=="two"){
chrome.browserAction.setPopup({tabId: tab.id, popup: "skin/popupSortofCare.html"});
} else if(choice=="three") {
chrome.browserAction.setPopup({tabId: tab.id, popup: "skin/popupCare.html"});
} else if(choice=="four") {
chrome.browserAction.setPopup({tabId: tab.id, popup: "skin/popupReallyCare.html"});
} else {
chrome.browserAction.setPopup({tabId: tab.id, popup: "skin/popup.html"});
}}
}
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if(changeInfo.status == "loading")
refreshIconAndContextMenu(tab);
});
// Update icon if a tab is replaced or loaded from cache
chrome.tabs.onReplaced.addListener(function(addedTabId, removedTabId){
chrome.tabs.get(addedTabId, function(tab){
refreshIconAndContextMenu(tab);
});
});
popup.js:
var userChoices = require("userchoices").userChoices;
function init()
{
console.log("Initializing popup.js");
// Attach event listeners
$("#Dont_Care_btn").click(doNothing);
$("#Sort_of_Care_btn").click(doBadger);
$("#Care_btn").click(giveSecrecyBadger);
$("#Really_Care_btn").click(giveAdvice);
$("#Nuance_btn").click(addNuance);
}
function doNothing() {
$("#startingQuestion").hide();
$("#DontCareResponse").show();
$("#siteControls").hide();
userChoices.setChoice(tab.url, "one");
refreshIconAndContextMenu(tab);
}
function doBadger() {
$("#startingQuestion").hide();
$("#SortofCareResponse").show();
$("#siteControls").hide();
$("#blockedResourcesContainer").hide();
$("#Nuance_btn").show();
userChoices.setChoice(tab.url, "two");
refreshIconAndContextMenu(tab);
}
function giveSecrecyBadger() {
$("#startingQuestion").hide();
$("#siteControls").hide();
$("#CareResponse").show();
$("#siteControls").hide();
$("#blockedResourcesContainer").hide();
$("#Nuance_btn").show();
userChoices.setChoice(tab.url, "three");
refreshIconAndContextMenu(tab);
}
function giveAdvice() {
$("#startingQuestion").hide();
$("#siteControls").hide();
$("#ReallyCareResponse").show();
userChoices.setChoice(tab.url, "four");
refreshIconAndContextMenu(tab);
}
The popup is currently not being set, and I'm not even sure that the selection is saved successfully. Anyone see a problem?
Ha! In the middle of trying to create a minimal example, I figured out the problem. Turns out the problem was the now-deprecated chrome.tabs.getSelected method when it should have been chrome.tabs.query()
Thanks Xan!

Categories