一、Tampermonkey 數據存儲之 GM_setValue / GM_getValue
Tampermonkey 存儲臨時數據,之前只用過 cookie 的讀存方式,非常麻煩。
看一下內置的 GM_setValue / GM_getValue
GM_setValue(name, value)
Set the value of 'name' to the storage.
GM_getValue(name, defaultValue)
Get the value of 'name' from storage.
簡單測試
// ==UserScript== // @name New Userscript // @namespace http://tampermonkey.net/ // @version 0.1 // @description try to take over the world! // @author You // @match https://*/* // @grant GM_setValue // @grant GM_getValue // ==/UserScript== (function() { 'use strict'; // Your code here... var a = { 'name': '大象筆記' }; GM_setValue('zw_test', a); console.log(GM_getValue('zw_test')); console.log(GM_getValue('zw_test').name); })();
Chrome 的 console 輸出
{name: "大象筆記"}
大象筆記
說明可以方便的將對象存儲,並讀取,非常方便。
GM_setValue 將數據存儲在哪里
存儲在 Chrome 內置的 LevelDB 中。
多個 Chrome 同時開啟是否會導致 GM_setValue 對同一個 key 相互覆蓋
測試
在 Chrome A 實例下 set value A, 然后在 Chrome B 實例下 get value A。
會發現 Chrome B 讀出來的結果是 undefined。
可以放心使用了。
注意事項⚠️
需要在頭部加上授權才能正常使用
// @grant GM_getValue // @grant GM_setValue
參考:
https://www.sunzhongwei.com/tampermonkey-gm_setvaluegm_getvalue-of-data-storage