0

I am creating chrome extension using angular & trying to use chrome.storage to set & get random generated id but at the time of "get" not getting that id, below is my code:

angular.module('chromeExtension')
.service('customService', ['$window', '$timeout', function ($window, $timeout) {
    this.getUniqueId = function() {
        return chrome.storage.sync.get('unique_app_id', function(data) {
            console.log(data.unique_app_id); // Here I am getting the id
            if(data.unique_app_id) {
                return data.unique_app_id;
            } else {
                uniqueId = Math.round((Math.pow(36, 20 + 1) - Math.random() * Math.pow(36, 20))).toString(36).slice(1);
                chrome.storage.sync.set({'unique_app_id': uniqueId});
                return uniqueId;
            }
        });
    }
}]);

So when I call this getUniqueId in my controller I am getting undefined, I also used timeout thought since chrome.storage.sync is async call so that could be the reason but no luck. Below is my controller where I am calling that function:

angular.module('chromeExtension')
.controller('sampleController',['$scope', 'customService', function ($scope, customService) {
    $scope.uniqueId = customService.getUniqueid();
    console.log("Unique: ", $scope.uniqueId); // this is giving me undefined or null
}]);
Dheeraj Agrawal
  • 2,347
  • 11
  • 46
  • 63

1 Answers1

1

chrome.storage.sync.get is an async call, you can't directly get the results.

One workaround would be adding a callback and call console.log in the callback, I'm not familiar with angular.js but sample code would be:

angular.module('chromeExtension')
.service('customService', ['$window', '$timeout', function ($window, $timeout) {
    this.getUniqueId = function(callback) {
        return chrome.storage.sync.get('unique_app_id', function(data) {
            console.log(data.unique_app_id); // Here I am getting the id
            if(data.unique_app_id) {
                callback(data.unique_app_id);
            } else {
                uniqueId = Math.round((Math.pow(36, 20 + 1) - Math.random() * Math.pow(36, 20))).toString(36).slice(1);
                chrome.storage.sync.set({'unique_app_id': uniqueId});
                callback(uniqueId);
            }
        });
    }
}]);


angular.module('chromeExtension')
.controller('sampleController',['$scope', 'customService', function ($scope, customService) {
    customService.getUniqueId(function(uniqueId) {
        console.log("Unique: ", uniqueId);
    });
}]);
Haibara Ai
  • 10,703
  • 2
  • 31
  • 47