简体   繁体   中英

chrome.storage.local.get causes exception

I'm trying to save pair pageUrl:imageUrl into chrom local storage. Here is the code:

    function saveImage (href, urlImage)
    {
        var dataObj = {href:urlImage};
        dataObj[href] = urlImage;
        chrome.storage.local.set(dataObj);
        console.log("Image url has been saved into storage "+href);

    }

    function tryLoadCachedImageUrl(hrefObj)
    {
        console.log("Trying to load image from storage: "+hrefObj.href);
        chrome.storage.local.get(hrefObj.href, 
        function(result){   
                loadImages(result,hrefObj);
        });

    }

chrome.storage.local.get causes exception:

Error in response to storage.get: ReferenceError: obj is not defined

hrefObj.href contains string, equal to pageUrl which was saved in saveImage

What am I doing wrong?

[ For anyone landing on this page facing a similar situation ]

The error is in loadImages . It seems to be trying to access an undefined obj variable.


BTW, this line of code: var dataObj = {href:urlImage};
is not equivalent to: dataObj[href] = urlImage;
but to: dataObj["href"] = urlImage; (which is clearly not what you want)

The intended way is:

var dataObj = {};   // <-- create an empty object
dataObj[href] = urlImage;   // <-- the value of the `href` variable
                            //     is used as the key (not the string "href")

[ Note : This is not causing the problem, it is just bad practice - if nothing else it "hurts" code clarity. ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM