Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

StorageArea.set()

我们的志愿者还没有将这篇文章翻译为 中文 (简体)加入我们帮助完成翻译!

Stores one or more items in the storage area, or update existing items.

When you store or update a value using this API, the storage.onChanged event will fire.

Syntax

chrome.storage.<storageType>.set(
  keys,             // object
  function(){...}   // function
)

This API is also available as browser.storage.<storageType>.set() in a version that returns a promise.

<storageType> will be one of the writable storage types — storage.sync or storage.local.

Parameters

keys
An object containing one or more key/value pairs to be stored in storage. If an item already exists, its value will be updated.
  • Primitive values (such as numbers) and arrays will serialize as expected.
  • Functions will be omitted.
  • Dates, and Regexes will serialize using their String representation.
callback Optional
A callback function that is run when the operation completes. The callback takes no arguments. If the operation failed, runtime.lastError is set.

Browser compatibility

Chrome Edge Firefox Firefox for Android Opera
Basic support Yes Yes 45.0 48.0 33

Compatibility notes

Edge

  • storage is limited to 1MB per value.

Examples

// callback to set() just checks for errors
function onSet() {
  if (chrome.runtime.lastError) {
    console.log(chrome.runtime.lastError);
  } else {
    console.log("OK");
  }
}

// define 2 objects, that contain:
// a string, a function, a Date
var monster = {
  name: "Kraken",
  speak: function() {console.log("ROARR!!!")},
  birthday: new Date(2012, 11, 17)
}

var kitten = {
  name: "Moggy",
  speak: function() {console.log("Miaow")},
  birthday: new Date(2006, 7, 12)
}

// store the objects
chrome.storage.local.set({kitten, monster}, onSet);

function gotItem(item) {
  if (chrome.runtime.lastError) {
    console.log(chrome.runtime.lastError);
  } else {
    console.log(item);
  }
}

chrome.storage.local.get("kitten", gotItem);
// the function is omitted
// the Date is stored as a string
// -> {birthday: "2006-08-12T07:00:00.000Z", name: "Moggy"}

Example add-ons

Acknowledgements

This API is based on Chromium's chrome.storage API. This documentation is derived from storage.json in the Chromium code.

Microsoft Edge compatibility data is supplied by Microsoft Corporation and is included here under the Creative Commons Attribution 3.0 United States License.

文档标签和贡献者

 此页面的贡献者: Makyen, wbamberg, chrisdavidmills
 最后编辑者: Makyen,