使用 Chrome 存储的快速入门
简介
Chrome 存储是扩展中持久化数据的强大机制。在 MV3 中尤为重要,因为曾经开发者用来存储持久化数据的持久化后台页面已不复存在。
Plasmo 存储
我们基于 chrome.storage
API 构建了一个 库,使其更易于使用,尤其是当你编写 React 应用时。
存储 Hooks
我们的库提供了用于读取和写入存储的 React Hooks。
以下是一些示例用法:
popup.tsx
import { useStorage } from "@plasmohq/storage/hook"
function IndexPopup() {
const [openCount] = useStorage<number>("open-count", (storedCount) =>
typeof storedCount === "undefined" ? 0 : storedCount + 1
)
const [checked, setChecked] = useStorage("checked", true)
return (
<div
style={{
display: "flex",
flexDirection: "column",
padding: 16
}}>
<p>打开次数: {openCount}</p>
<input
type={"checkbox"}
checked={checked}
onChange={(e) => setChecked(e.target.checked)}
/>
</div>
)
}
export default IndexPopup
options.tsx
import { useStorage } from "@plasmohq/storage/hook"
function IndexOptions() {
const [openCount] = useStorage<number>("open-count")
const [checked] = useStorage("checked")
return (
<div
style={{
display: "flex",
flexDirection: "column",
padding: 16
}}>
<p>打开次数: {openCount}</p>
<input type={"checkbox"} readOnly checked={checked} />
</div>
)
}
export default IndexOptions
完整示例
完整的示例,请查看 with-storage (opens in a new tab) 在 GitHub 示例仓库中。