0

I'm trying to follow along with this question, but my code is not working and I cannot figure out why. I'm passing a variable to my content script from a script controlling an iFrame (popup.js), and having the content script respond with the data I need to work with in popup.js. The problem is, I need to be able to work with the data throughout popup.js, and the message passing scope doesn't allow for that, so I am trying to use the bind method as follows:

var currentSite;
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    let bindSite = function(response){
        console.log(response);
        this.currentSite = response.Site;
    };
    chrome.tabs.sendMessage(tabs[0].id, {type: "getSite"}, bindSite.bind(this));
});
console.log("Since I bound it, currentSite should be in the scope here " + currentSite);

The site prints in the console.log() that is inside the function, but it prints undefined in the console.log() statement outside the function. What am I missing?

MRB
  • 221
  • 2
  • 12
  • _“\[`tabs.query`\] is an asynchronous function that returns a `Promise`.”_ — from the [documentation](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/query). – Sebastian Simon Oct 02 '20 at 04:23
  • To use Promise in Chrome you would need a polyfill like https://github.com/mozilla/webextension-polyfill – wOxxOm Oct 02 '20 at 04:24
  • @wOxxOm Why do I need to use a polyfill? Right now it's just a chrome extension, and promises have been supported in Chrome since 2014, as far as I understand. I use promises in my code in multiple other areas and they all work fine, granted I'm testing on Chrome 85. – MRB Oct 02 '20 at 17:48
  • Chrome extensions are callback-based so if you want to use promises you'll need a polyfill for the API. There are several. I've linked the most popular one. BTW here's the [correct documentation link](https://developer.chrome.com/extensions/tabs). – wOxxOm Oct 02 '20 at 17:56

0 Answers0