1

I'm working on Chrome extension. I'm listening for requests with chrome.webRequest.onCompleted.addListener. After I catch request I want to put request.url into impresses in chrome.storage

chrome.webRequest.onCompleted.addListener((wr) => {    
  let wurl = wr.url;
   
  if (wurl.includes('impress')) {
    console.log(wr.url);
  chrome.storage.local.get({impresses: []}, function (result) {
  var impresses = result.impresses;
  impresses.push({url: wr.url});
  chrome.storage.local.set({impresses: impresses}, function () {
      chrome.storage.local.get('impresses', function (result) {
          console.log(result.impresses)
      });
  });
});
  }
}, {
  urls: ["<all_urls>"] },
[]);

Key impresses from chrome.storage has value [] on call

My problem is that console.log(wr.url); gives me 10 results but console.log(result.impresses) gives me only 10, sometimes less.. It should be the same.

I tried is as @wOxxOm commented but it's not working properly for me..

let queue = [];

function updateStorage() {
  if (!queue.length || updateStorage.running) {
      return;
  }
  updateStorage.running = true;
  chrome.storage.local.get('impresses', data => {
      data.impresses = [].concat(data.impresses || [], queue);
      queue = [];
      chrome.storage.local.set(data, () => {
        updateStorage.running = false;
        if (queue.length) updateStorage();
      });
  });
}

chrome.webRequest.onCompleted.addListener((wr) => {    
  let wurl = wr.url;
   
  if (wurl.includes('impress')) {
    console.log(wr.url);

    queue.push(wr.url);
    updateStorage();
  }
}, {
  urls: ["<all_urls>"] },
[]);
Jakub
  • 11
  • 3
  • Your webRequest listener may run for another request while the previous one is still updating storage so this is a classic race condition problem. One of the solutions is to maintain a global mutex or a queue, see [Update object stored in chrome extension's local storage](https://stackoverflow.com/a/38906083). – wOxxOm Oct 27 '20 at 10:06
  • Also note that devtools reads the arrays/objects in console only when you click them so it won't be the contents at the time console.log was called, see [Weird behavior with objects & console.log](https://stackoverflow.com/q/23429203) – wOxxOm Oct 27 '20 at 10:07
  • Ok I tried.. still not working :( I don't know what I'm doing wrong.. – Jakub Oct 27 '20 at 10:31
  • I don't see where you have console.log for the result now. Do you also remove from the array or storage anywhere else? See also [Inspect extension's chrome.storage in devtools](https://stackoverflow.com/q/32435399) – wOxxOm Oct 27 '20 at 15:13

0 Answers0