How can I transfer data from a Google extension popup window to a database?

I need help with a Google extension. It records how long you are at a website and displays it in a popup. I would like to take that information and store it so that users can review their browsing habits. I read that connecting it to a database is too risky for a man-in-the-middle attack. What would be the best method to do this? I read that using IndexedDB would be a good alternative but I cannot find much information on how to specifically modify my code to connect to that. I am new at this, so I know that this question may be a bit simplistic.

Javascript promises not acting synchronously

I am attempting to use JavaScript promises so that the rest of my code waits for my asynchronous ‘chrome.storage.local.get’ call. However, it seems that the code is still acting asynchronously, and as a result sending undefined data out.

JavaScript code:

else if( request.message === "fetch-local-storage" ){//if popup request local data
        var responseData;

        let store = new Promise(function(resolve, reject){
            chrome.storage.local.get('localSearchList', function(query){
                responseData = query.localSearchList;
                console.log("asynch data: " + JSON.stringify(responseData));
            }); //fetch the local storage data 
            resolve('done');
        });

        store.then(function(res){ //do this only after above code runs
            console.log("The data being sent to popup (via content.js pipeline): " + JSON.stringify(responseData));
            sendResponse({message: "local-storage-data", data: JSON.stringify(responseData)});
        });

}

The console shows the following output:

The data being sent to popup (via content.js pipeline): undefined
asynch data: "[{"word":"mo","color":"rgb(128,0,128)","id":"0"}]"

If you look back at the code, this display shows that it is not working synchronously…

Variable being assigned within google chrome method not keeping its value

I am assigning the variable ‘responseData’ to the value of a variable in chrome local storage. When I console.log the value of response data right after assigning it, it prints out the value perfectly fine, however, if i do the exact same console.log statement a couple lines below it it says the value is undefined?

The JS code:

 else if( request.message === "fetch-local-storage" ){ //popup is reopening and fetching data cached in local storage
    console.log('Booting up popup....');
    var responseData;

    chrome.storage.local.get('localSearchList', function(query){
        responseData = query.localSearchList;
        console.log("responseData within conditional: " + JSON.stringify(responseData));
    }); //fetch the local storage data 

    console.log("Actual value being sent out:" + JSON.stringify(responseData));

    sendResponse({message: "local-storage-data", data: JSON.stringify(responseData)}); //send it as a JSON-ifiable object
}

Console.log output:

Booting up popup....
Actual output of content.js:undefined
responseData within conditional: "[{"word":"q","color":"rgb(0,128,0)","id":"0"}]"

Does this have to do with synchronality of the ‘get’ method, where sendResponse is executing before the get can finish so its left undefined?

will chrome extension update clear local storage?

I am developing chrome extension and want to keep some configs. I am using chrome.storage.sync API.

I am using this code for generating values once.

chrome.runtime.onInstalled.addListener(() => {
    chrome.storage.sync.get(['value'], data => {
        if (!data.userId) {
            chrome.storage.sync.set({ value: getRandomValue() }, () => {
                console.log('Settings saved');
            });
        }
    });
});

I want to be sure, that my data will keep when user

1: Updates the extension

2: Removes the extension and installs it again.

Which of these cases will keep my values ?

Chrome Storage API – GET call

I am unable to understand Google chromes get and set functions.

Please refer the below code snippet.

    var v1 = 'l1';
    var v2 = 'l2';

    storage.set({v1:'s1'});

    storage.get('v1',function(result){
        console.log(v1,result.v1);
    });

    storage.get('v2',function(result){
        console.log(v2,result.v2);
    });

I got the following output.
l1 s1
l2 s1

I am purposely not setting v2 as I would like to understand what the result is when the variable hasn’t been set yet.

I am not able to follow why get with key v2 returns s1.

Can you somebody pplease let me know where I am going wrong.

Regards,
Farhan

How do I use Promise.all() with chrome.storage()?

I have several async functions running. I want to wait for them all to finish before taking the next steps. Here’s my code that I’m using to get all of the key/values from chrome.storage and the Promise.all() implementation.

var promise1 = Promise.resolve(3);
var promise2 = 42;
var promise3 = new Promise(function(resolve, reject) {
  setTimeout(resolve, 100, 'foo');
});

var getAll = chrome.storage.sync.get(function(result) {
  console.log(result)
});

Promise.all([promise1, promise2, promise3, getAll]).then(function(values) {
  console.log(values); // [3, 42, "foo", undefined]
});

This doesn’t work unfortunately. It returns undefined.

Most of the code above is taken from MDN here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

How should I get a large list of options that are saved to chrome.storage in my Chrome extensions’ content script?

I have an options page in my Chrome extension with a very large list of values that get saved to chrome.storage. These options get used across several different websites. In order to use the options I have to retrieve them in my content scripts that load on these websites.

I’m trying to figure out the best way to handle this. I’m fairly confident that once I get my options loaded during a session on a website that I would want to save them to sessionstorage or localStorage so that I can have quick synchronous access to them on subsequent page loads of that same site.

But the initial retrieval of those options is where I’m wondering what’s the best method. My gut says to just make all of the asynchronous calls for each individual option from my content script at document_start and return a promise once I’ve retrieved them all using Promise.all().

My other idea was using message passing to talk to the background page where all of my options can already be available because I will have done the async calls when Chrome started or because I could just skip chrome.storage and store them in the background pages’ localStorage. In this case, each different website that needs the options is just sending one message to the background page instead of making 40+ async calls to chrome.storage.

How do I delete one item from an array with chrome.storage.sync.remove?

I’m building a Chrome browser extension which includes a feature that lets users save urls. I used chrome.storage.sync to create this feature and didn’t encounter any issues.

However, I also need to let users delete urls they’ve already saved. I created a text input box where they can enter a single url they want to delete (i.e. “www.url.com”). I want to convert this input into a string and use it to remove a matching string from Chrome storage when the user presses a button.

I thought the chrome.storage documentation specifies that chrome.storage.sync.remove can be used to remove a string from a stored array, but I can’t get it to work. Here’s my code:

function removeUrl() {
    var theUrl = document.getElementById('url-input').value;
    chrome.storage.sync.get(null, function(result, error) {

        // Checks if the array (urlList) exists:
        if ('urlList' in result) {
            var theList = result['urlList'];

            // Checks if the url that will be deleted is in the array:
            if (theList.includes(theUrl)) {
                chrome.storage.sync.remove(theUrl);
                chrome.runtime.reload();
            }
        }
        // Error handling goes here
    });
}

This code doesn’t throw any errors, but it doesn’t remove the url from the array either.

Please note that I only want to delete 1 url at a time, there are no duplicate urls in the array, and I am not using any libraries like jQuery. What am I doing wrong?

Calling objects in chrome storage api

I am having trouble making a chrome extension that needs to keep track of the user’s total searches. My code creates an object in the content script and then adds to the object and stores it in chrome storage, however every time the content script runs again, I am pretty sure my object is being reset to an empty object. One idea I had was creating the object inside a background script and putting it in the storage then adding to the object in my content scripts, but I ran into issues with the object not being defined in my content script and went back to what I had originally.

Here is the important my content script:

var dataObject = {
    "searches": [],
    "links": [],
    "time": []
};

var key = 'myKey';

    chrome.storage.sync.set({
        key: dataObject
    }, function() {
        console.log('Value is set to:');
        console.log(dataObject);
    });

    chrome.storage.sync.get(['key'], function(result) {
        console.log("Value is:");
        console.log(result.key);
    });

Chrome.storage.sync.set from JSON Object

I am trying to save to Chrome’s synced storage, a dynamically generated JSON object.

Essentially, I am running a query to get all the open tabs:

function getTabs(){
  var activeSession = [];
  //Tab query with no parameters, returns all open tabs. 
  chrome.tabs.query({}, function(tabs){
    //For each tab push to active session array     
    tabs.forEach(function(tab){
      activeSession.push({'title': tab.title, 'url': tab.url});
    });
  });
  return activeSession;
}

I then get a name for this group of tabs from user-input, build a JSON object and save this to Chrome’s synced storage:

//Retrieve group name from input field
    var group_name = document.getElementById('file_name').value;

    //Call function to retrieve tabs and build JSON object.
    var returned_tabs = getTabs(); 
    var obj = {[group_name]: returned_tabs};
    console.log(obj);

    chrome.storage.sync.set(obj, function() { 
        chrome.storage.sync.get(function (data) {
            console.log(data);
        });        
    });

The obj variable is essentially the structure I am looking for, and works as expected, as indicated by the console.log(obj). Which outputs like this:

Desired Output

However, when I try to store this in Chrome – it simply saves as the group_name with an empty array. So, if I pull this info back out of storage and log it out, I get:

Actual Output