I am building a chrome extension where I need to use data storage. The operation of the extension is as below:
- The extension captures the url of any get or post request
- If the URL is already present in the storage key:value pair as key then I retrieve the value and show it somehow in the browser
- If the URL is not present in the storage then I call an API that does some operation on the URL and returns a response. Then I store the URL-response pair as key:value in the storage. The reason I am doing this, so that I don't have to call the API next time the same URL appears. I will just check my storage then.
I have written the following code for setting the values in storage.
chrome.storage.sync.set({user_url: show_action}, function() {
console.log('Key is ' + user_url);
console.log('Value is set to ' + show_action);
});
The user_url
variable has the captured URL from a request. show_action
variable holds the response from the API call.
I am trying to retrieve the value using the following code:
chrome.storage.sync.get([user_url], function(result) {
console.log(result);
console.log('Value currently is ' + result.user_url);
if(result.user_url == null || result.user_url == undefined)
call_api = true;
else
show_action = result.user_url;
});
This is not working as expected. I am getting a blank result
with no key-value pairs with user_url
as key. Although it must be there because I am setting the value before retrieval. Then I tried to put user_url
as a string literal in the get call like this:
chrome.storage.sync.get(["user_url"], function(result) {
console.log(result);
console.log('Value currently is ' + result.user_url);
});
When this is done the result is something like this in console log:
{user_url: true}
user_url: true
Value currently is true
So, the user_url
itself is being set as key instead of the value in it.
My question is how do I set the URL as key and when I call by the URL I get the desired output? And also how to handle the situation when I call by the URL but that is not present in the storage?