Change value in popup.html using chrome.storage.sync.get (building chrome extension)

Hi everyone,

As a hobby, I am writing an extension for chrome.

I want to load the storage (chrome.storage.sync) and set the value that is there on an element in my popup.html

The screen you see now is the popup (popup.html) screen from the extension. My goal is to fetch data from a page, and show it below Laatste :netherlands:. But since we have to work with a worker I have to use the chrome.storage.sync method using a Promise method.

image

In my popup.html I have the next html code:

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="styling.css">
</head>
<body>
<div class="extension">
    <div class="main">
        <h2>Bot</h2>
        
    </div>
    <div class="huidige-status">Huidige status: {{status}}</div>

    <div class="buttons">
        <button id="lastBiddings">Get offer info</button>

    </div>

    <div class="last-bids">
        <h4>Laatste</h4>
        <div id="bids">
            <div id="lastbids">dsassa</div>
            <p>sdaksd</p>
            <p>sdaksd</p>
        </div>
    </div>
</div>
<script src="popup.js"></script>

</body>
</html>

With this popup.js

// When the button is clicked, inject setPageBackgroundColor into current page
startBidding.addEventListener("click", async () => {
    let [tab] = await chrome.tabs.query({active: true, currentWindow: true});
    chrome.scripting.executeScript({
        target: {tabId: tab.id},
        function: setPageBackgroundColor,
    });

    const result = await getLocalStorageValue("lastBit");

    document.getElementById('lastbitss').innerText = result;
});

async function getLocalStorageValue(key) {
    return new Promise((resolve, reject) => {
        try {
            chrome.storage.sync.get(key, function (value) {
                resolve(value);
            })
        }
        catch (ex) {
            reject(ex);
        }
    });
}

function setPageBackgroundColor(e) {
    lastBit = document.getElementById("lastbit");
    chrome.storage.sync.set('lastBit', lastBit);

    chrome.storage.sync.get("color", ({color}) => {
        document.body.style.backgroundColor = color;
    });
}

The problem is when

    const result = await getLocalStorageValue("lastBit");

    document.getElementById('lastbitss').innerText = result;

is called in the popup.js I never get the value back. And it wil set [object Object] on the lastbitss element from the popup.html. It does not matter when I set default data in the storage.sync example:
chrome.storage.sync.set('lastBit', 1111);


Did I do the saving/loading wrong to chrome’s API?

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.