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。

    可以放心使用了。

    关于作者 🌱

    我是来自山东烟台的一名开发者,有感兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊,或者关注我的个人公众号“大象工具”, 查看更多联系方式