How to keep a variable in the background

I am developing a google chrome extension. I want to maintain user state. if any user is logged in, then after refreshing the page, he should log in. How can I maintain this type of state.

+3


source to share


3 answers


Background pages retain value until browser session, if you are looking for stable storage use Chrome.storage. You can use the following code as a reference.

Demonstration

manifest.json

Registered background page with chrome extension

{
    "name": "Persist Value",
    "description": "http://stackoverflow.com/questions/14744916/how-to-store-variable-in-background-page",
    "manifest_version": 2,
    "version": "1",
    "permissions": [
        "storage"
    ],
    "background": {
        "scripts": [
            "background.js"
        ]
    }
}

      



background.js

Some trivial implementation.

//You can use Storage API
chrome.storage.local.set({
    "Name": "Your_variable",
    "Value": "Some Value"
}, function () {
    console.log("Storage Succesful");
});

      

Links

+3


source


In your case, it sounds like you want to store user state on the server side, which is a big difference from saving the state of the extension itself. For example, you might have some server-side code (written in PHP or any other server-side language) that keeps track of your Chrome extension users every time they log in. For this - "sessions" are very common and good and implemented and probably all server-side languages. If this is what you are looking for, it is best to read about server programming and ajax before delving into the extension.



However, if you want to store state in your chrome extension "locally" (without involving a server), then html5 localStorage is a good option http://diveintohtml5.info/storage.html .

0


source


You can store variables in localStorage

the following methods: localStorage.setItem()

, localStorage.getItem()

but has limitations localStorage

If you have used big data, use chrome.storage.local

orchrome.storage.sync

localStorage works, then chrome.storage and chrome.storage are asynchronous

0


source







All Articles