Tampermonkey 脚本开发入门

一、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

原文地址:https://www.cnblogs.com/poterliu/p/14416630.html