Passing Parsed Data to Callback in Order to Use Freely

I want to know if there is anyway to pass the value of coins or, more ideally, currency to my callback function at the end so i can use the parsed JSON data freely in other functions.

function loadJSON(path, callback) {
  var json = new XMLHttpRequest();
  json.onreadystatechange = function () {
    if (json.readyState == 4) {
      if (json.status == 200) {
          var coins = JSON.parse(json.responseText);
          setTimeout(function(){
          coins.forEach(function(currency){
         //console.log(currency.name + "x09x09x09" + currency.price_usd + " USD");
       }, 5000);
       });
      }
      // else {
      //   error(json);
      // }
    }
  };

  json.open("GET", path, true);
  json.send();
  callback();
}

I’m new to JS so any advice is greatly appreciated!

send message and callback/promise

I got a problem and can`t handle with it for a lot of time.

  1. callback

background script:

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.event === 'login') {
    socket.emit('login', request.data, (res, reply) => {
        console.log(sendResponse);
        sendResponse(1);
    });
}
return true;
});

view script:

chrome.runtime.sendMessage({
            event: 'login',
            data: hash.toString()
        }, (res) => {
            alert(1);
        });
  1. with promise

background script:

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
   if (request.event === 'login') {
      socket.emit('login', request.data, (res, reply) => {
         return new Promise((res,rej)=>{console.log(123);res(213);});
      });
   }
});

view script:

chrome.runtime.sendMessage({
            event: 'login',
            data: hash.toString()
        }).then((res)=>{alert(res)});

Problem: with callback i can`t get any parameter through response and promise just not working (btw tryed it first time).

Can anyone please tell me what’s wrong with callback or promise.

UPD 1:
I mean with sendResponse(1) i`ll get res = undefined in callback.
UPD 2:
also tryed to put return true in if statement.

How to implement message passing callbacks in an all-in-one (Edge/Firefox/Chrome) browser extension’s content script?

Development Environment OS: Windows 7 Enterprise LTS
Browser compatibility minimum requirements: Should support all Edge, Firefox, Chrome browsers, as of 2018.
Current ongoing issue: Unable to run VM on dev workstation; Cannot run Windows 10 VMs to debug Microsoft Edge extensions.

To explain:

  • An “all-in-one browser extension” refers to a browser extension code that uses the same code with minor differences to work on various WebExtensions / Chrome Extensions supported browsers. At bare minimum, the same codebase should work and run on Edge, Firefox, and Chrome with very minor changes.
  • Callbacks on the content scripts for Edge/Firefox/Chrome extensions are handled differently.
  • For unknown reasons, I cannot run VM on my workstation machine. When VM is running, VM client is black. This is a localized issue on my end that I cannot resolve, so I’m forced to find a different solution/alternative.

How are they handled differently on the content scripts:

  • Edge: browser.runtime.sendMessage uses callbacks, and returns undefined.
  • Firefox: browser.runtime.sendMessage uses Promises, and returns a Promise.
  • Chrome: chrome.runtime.sendMessage uses callbacks, and returns undefined.

According to various references:

Firefox / Chrome / MS Edge extensions using chrome.* or browser.*

https://www.smashingmagazine.com/2017/04/browser-extension-edge-chrome-firefox-opera-brave-vivaldi/

On the content scripts, you can declare the following JavaScript snippet at the top in order to create a global variable that can be referenced everywhere else:

//Global "browser" namespace definition.
window.browser = (function() {
    return window.msBrowser || window.browser || window.chrome;
})();

Unfortunately, because of the issue I’m experiencing (VM not running), I cannot tell if window.msBrowser is still being used. And this solution is not helpful for me when handling message callbacks when using namespace.runtime.sendMessage.


With all that said, my main question is: How to write a message passing function that can handle callbacks properly?

Currently, I’m using the following code:

function sendGlobalMessage(messageRequest, callback) {
    if (chrome && window.openDatabase) {
        //This is Chrome browser
        chrome.runtime.sendMessage(messageRequest, callback);
    }
    else if (browser) {
        try {
            //Edge will error out because of a quirk in Edge IndexedDB implementation.
            //See https://gist.github.com/nolanlawson/a841ee23436410f37168
            let db = window.indexedDB.open("edge", (Math.pow(2, 30) + 1));
            db.onerror = function(e) {
                throw new Error("edge is found");
            };
            db.onsuccess = function(e) {
                //This is Firefox browser.
                browser.runtime.sendMessage(messageRequest).then(callback);
            };
        }
        catch (e) {
            //This is Edge browser
            browser.runtime.sendMessage(messageRequest, callback);
        }
    }
}

I truly felt this is a hacky solution, because the code is based off of browser platform exclusive quirks in order to separate chrome.runtime.sendMessage and browser.runtime.sendMessage API calls, so as to handle callbacks in their respective platforms. I really wanted to change this.

So I’m asking what better ways are there, out there, that is useful to detect the different platforms, and handle message passing callbacks properly at the same time?

Thanks in advance.

google chrome extension: get cookies in background.js and sendResponse to content.js

My extension adds notify to third-party websites. From this notify I should check if user is logged on our website. I want to check userId from cookies in background.js and send message to content.js. Where I need to know if cookies not empty ( chrome.cookies.get doesn’t available from content.js).

Simple response from https://developer.chrome.com/extensions/messaging works perfectly. And chrome.cookies.get works fine separetaly. But when I try to add condition with get.cookies there is a problem. I guess it because scoupe/context or callbacks trouble.

Background.js

Chrome.runtime.onMessage.addListener(
    function (request, sender, sendResponse) {
        if (request.greeting == "hello") {
            var ID;

            function getCookies(domain, name) {
                chrome.cookies.get({"url": domain, "name": name}, function (cookie) {
                    ID = cookie.value;
                    showId();
                });
            }

            function showId() {
                if (ID) {
                    sendResponse({farewell: "logged"});
                }
                ;
            }

            getCookies(baseUrl, COOKIE_KEY_USER_ID);
        }
    }
);

content.js

$(notify).find('[data-act]').on('click', function (e) {
    e.preventDefault();

    chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
        if (response && response.farewell == "logged") {
            activateFromNotify();
        } else {
            // 'not logged'
            $('.wrapper').html(showlogin);
        };
    });

});

Looks like in background.js it doesnt see sendResponse inside another function or Callback. Is there any way to resolve it ? Thanks in advance

variable reassignment inside callback scope [duplicate]

I am trying to assign a preassigned variable to equal to another array inside a callback function.
My description might not be giving you the proper understanding, so here’
s my code:

var extensionListArray = [];

chrome.management.getAll(function(extensionList) {
  extensionListArray = extensionList;
  console.log(extensionList); // logs the expected array contents [{}, {} ...]
});

console.log(extensionListArray); // logs "[]"

The problem is that it should log the contents of extensionList array but it instead logs []


Edit: The parameter extensionList when console.log(extensionList) does log the array contents, only inside the callback scope though