0

I am new with javascript and chrome extensions, but I'm trying to create an HTML button into a web page, for example, let's consider the page https://www.mypage.com/first/second/10/

When I click the button, I would like to store the value "10" in "array_number" that I already have. So, I used chrome.storage.sync.set to store the array, then I pushed the value and then I used to chrome.storage.sync.get to verify my data. This is the code:

var array_number = ['1', '2', '3', '4', '5', '6', '7', '8', '9'];
var url = document.URL;
var splitUrl = url.split('/');

function test() {
    chrome.storage.sync.set({list:array_number}, function() {
        array_number.push(splitUrl[5]);
        console.log(splitUrl[5] + ' added to list with new values');
    });
    chrome.storage.sync.get({ list: [] }, function (items) {
        for (var i = 0; i < items.list.length; i++) {
            console.log(items.list[i]);
        }
    });
}


var el = document.getElementById('clickMe');
if(el){
  el.addEventListener('click', test);
}


document.getElementById('second_id').insertAdjacentHTML('beforebegin', '<li style=\'color: green; position: relative; bottom: 12px;\'>None</li>');
document.getElementById('third_id').insertAdjacentHTML('beforebegin', '<input id="clickMe" type="button" class="first_class" value="Delete"/>');

document.getElementById('clickMe').addEventListener('click', test);

I get in my console:

10
10 added to list with new values
1
2
3
4
5
6
7
8
9

And the "10" is not there... how can I fix that? I would like that these numbers are stored forever in my browser. I also would like to know if chrome.storage is a good solution because when my extension will be ready I will have around 5000 numbers. Thank you!

Jourasky
  • 53
  • 5
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – wOxxOm Jun 25 '18 at 18:16
  • Callbacks in Chrome API are invoked asynchronously so you have to `get` the value inside the callback of `set`. See the linked topic for more info and details. – wOxxOm Jun 25 '18 at 18:17
  • As for the limits, storage.sync is VERY limited as you can see in the documentation: only 512 items can be saved. You'll have to combine the values or switch to a 3rd-party server like dropbox. – wOxxOm Jun 26 '18 at 07:47

0 Answers0