How can I save information locally in my chrome extension?

前端 未结 2 1194
梦如初夏
梦如初夏 2020-11-27 12:11

I want my chrome extension to save some information, and I\'m not sure how to start the code... I need it to save strings. For example - The user inputs a string (In a text

相关标签:
2条回答
  • 2020-11-27 12:21

    There is a specific API now, check this here: https://developer.chrome.com/extensions/storage

    Note that it is only available on your background page and works in an isolated world (you don't access the values contained in the HTML5 localStorage of the web site).

    0 讨论(0)
  • 2020-11-27 12:29

    You can now leverage Google Chrome's storage API to do this as well. Unlike localStorage, this is accessible from content scripts as well.

    //  Somewhere in your manifest...
    
    {
        "permissions": [
            "storage"
        ]
    }
    
    //  Usage:
    
    //  PERSISTENT Storage - Globally
    //  Save data to storage across their browsers...
    
    chrome.storage.sync.set({ "yourBody": "myBody" }, function(){
        //  A data saved callback omg so fancy
    });
    
    chrome.storage.sync.get(/* String or Array */["yourBody"], function(items){
        //  items = [ { "yourBody": "myBody" } ]
    });
    
    //  LOCAL Storage
    
    // Save data to storage locally, in just this browser...
    
    chrome.storage.local.set({ "phasersTo": "awesome" }, function(){
        //  Data's been saved boys and girls, go on home
    });
    
    chrome.storage.local.get(/* String or Array */["phasersTo"], function(items){
        //  items = [ { "phasersTo": "awesome" } ]
    });
    

    More info on how these shenanigans work here: https://developer.chrome.com/extensions/storage#type-StorageArea

    Former answer:

    Use localStorage. Google Chrome implements some features of HTML5, and it is one of them.

    //Pull text from user inputbox
    var data = document.getElementById("this_input").value;
    //Save it to the localStorage variable which will always remember what you store in it
    localStorage["inputText"] = data; 
    

    You should note you can only access your storage from the background page (no content scripts) so you'll have to use messaging for that.

    0 讨论(0)
提交回复
热议问题