Greasy Fork

Greasy Fork is available in English.

GM_lock

A lightweight, dependency-free mutex for Userscripts that ensures **only one tab / context** runs a critical section at a time. It coordinates through `GM.setValue` + `GM_addValueChangeListener`, so it works across multiple tabs, iframes, and even separate scripts that share the same @name/@namespace storage.

此脚本不应直接安装。它是供其他脚本使用的外部库,要使用该库请加入元指令 // @require https://update.greasyfork.icu/scripts/554436/1687660/GM_lock.js

/**
 * 
    This is free and unencumbered software released into the public domain.

    Anyone is free to copy, modify, publish, use, compile, sell, or
    distribute this software, either in source code form or as a compiled
    binary, for any purpose, commercial or non-commercial, and by any
    means.

    In jurisdictions that recognize copyright laws, the author or authors
    of this software dedicate any and all copyright interest in the
    software to the public domain. We make this dedication for the benefit
    of the public at large and to the detriment of our heirs and
    successors. We intend this dedication to be an overt act of
    relinquishment in perpetuity of all present and future rights to this
    software under copyright law.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
    IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
    OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
    ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
    OTHER DEALINGS IN THE SOFTWARE.

    For more information, please refer to <https://unlicense.org>
 * 
 */
var GM_lock = async (tag, func) => {
    GM_lock.i = (GM_lock.i & 1073741823) + 1;
    const lockId = `${Date.now() + 1000000000000000}_${GM_lock.i}_${Math.floor(Math.random() * 9000 + 1000)}`; // TS_i_R
    let resolveFn, rejectFn, cid;
    const promiseRet = new Promise((resolve, reject) => {
        resolveFn = resolve;
        rejectFn = reject;
    });
    let valids = new Set();
    let listenerId = GM_addValueChangeListener(`GM_lock_changed::${tag}`, async (_key, _oldValue, newValue, _remote) => {
        valids.add(`GM_lock::${tag}::${newValue.substring(0, 17)}`); // GM_lock::TAG::TS_
        const keys = (await GM.listValues()).filter((key) => key.startsWith(`GM_lock::${tag}::`)).sort();
        if (keys[0] === `GM_lock::${tag}::${lockId}`) {
            GM_removeValueChangeListener(listenerId);
            clearTimeout(cid);
            await GM.setValue(`GM_lock_changed::${tag}`, `${lockId}_run_${Date.now()}`); // TS_i_R_run_ts
            let res;
            let err;
            try {
                res = await func();
            } catch (e) {
                err = e;
            }
            await GM.deleteValue(`GM_lock::${tag}::${lockId}`);
            await GM.setValue(`GM_lock_changed::${tag}`, `${lockId}_del_${Date.now()}`); // TS_i_R_del_ts
            err ? rejectFn(err) : resolveFn(res);
        }
    });
    await GM.setValue(`GM_lock::${tag}::${lockId}`, "1");
    await new Promise(resolve => setTimeout(resolve, 50));  // 可选:设置 delay 确保锁不会冲突. Optional: Make delay to avoid lock conflict.
    // 0.3秒通知記錄有效,重设锁. 300ms to notify record valid and reset lock.
    cid = setTimeout(async () => {
        await GM.setValue(`GM_lock::${tag}::${lockId}`, "1");
        await new Promise(resolve => setTimeout(resolve, 50));  // 可选:设置 delay 确保锁不会冲突. Optional: Make delay to avoid lock conflict.
        await GM.setValue(`GM_lock_changed::${tag}`, `${lockId}_set_${Date.now()}`); // TS_i_R_set_ts
        // 0.6秒刪除無效記錄,重设锁. 600ms to remove invalid records and reset lock.
        cid = setTimeout(async () => {
            const keys = (await GM.listValues()).filter((key) => key.startsWith(`GM_lock::${tag}::`)).sort();
            for (const key of keys) {
                const startPart = key.substring(0, `GM_lock::${tag}::`.length + 17); // GM_lock::TAG::TS_
                if (valids.has(startPart)) break;
                await GM.deleteValue(key);
            }
            valids.clear();
            await GM.setValue(`GM_lock::${tag}::${lockId}`, "1");
            await new Promise(resolve => setTimeout(resolve, 50));  // 可选:设置 delay 确保锁不会冲突. Optional: Make delay to avoid lock conflict.
            await GM.setValue(`GM_lock_changed::${tag}`, `${lockId}_set_${Date.now()}`); // TS_R_set_ts
        }, 300);
    }, 300);
    await GM.setValue(`GM_lock_changed::${tag}`, `${lockId}_set_${Date.now()}`); // TS_R_set_ts
    return promiseRet;
};