0

EDIT: I found my solution here: Returning Chrome storage API value without function

I am building a chrome extension at the moment, and want to use the storage data. I managed to save it, and even the next day it's still there. So that portion of the work works. But I want to display the data I saved in the popup.
Let's say I want the user to enter their name and store that name. Then I want the popup to update and show "Welcome {name}". How should I do that?

I wrote this code, but it does nothing.

popup.js

const generateLinks = document.getElementById("generate-links");
const data = document.getElementById("data-token");
const form = document.getElementById("data-form");
const content = document.getElementById("content");
const textData = document.getElementById("saved-data-token");

let token = "";
let savedData = "";

function hasData() {
  if (savedData !== "") {
    textData.innerHTML = "Your data is: " + savedData;
  }
}

hasData();

form.addEventListener("submit", (e) => {
  e.preventDefault();
  console.log(data.value);
  token = data.value;
  chrome.runtime.sendMessage(token, (response) => {
    savedData = response;
  });

  content.classList.add("accepted");
});

I obviously must have done something wrong, can someone direct me to the correct solution?

I updated the code with the following and now get undefined, but when I console.log it instead of return, I do get the data.

let savedData = chrome.storage.sync.get(["data"], (res) => {
  return res.data;
});

Console

Mähnenwolf
  • 720
  • 10
  • 30
  • The code you've posted has no relation to storage. Show us how and when you assign to `savedData`. See also [saving and retrieving from chrome.storage.sync](https://stackoverflow.com/q/14531102) and note that the popup is a separate window so it has its own separate devtools: right-click inside the popup and select "inspect" in the menu. – wOxxOm Nov 18 '20 at 08:58
  • The data is store inside ``savedData``. As I send, the storage bit works, I checked the console of the popup, and it is there. But I will update the post with the whole code. – Mähnenwolf Nov 18 '20 at 09:01
  • So `savedData` is assigned a value inside an event listener, which happens asynchronously long long time after hasData() is called. You need to call hasData() after saveData is actually assigned. For example, move hasData() call right after `savedData = response;` Also note that the popup is like any page which runs each time it's shown so none of its variables survive after the popup is closed. – wOxxOm Nov 18 '20 at 11:01

0 Answers0