Greasy Fork

打开选中的pixiv id

help you to open pixiv works by id

目前为 2023-08-05 提交的版本。查看 最新版本

// ==UserScript==
// @name         打开选中的pixiv id
// @namespace    https://greasyfork.org/zh-CN/scripts/469561-%E6%89%93%E5%BC%80%E9%80%89%E4%B8%AD%E7%9A%84pixiv-id
// @version      0.3
// @description  help you to open pixiv works by id
// @match        *://*/*
// @grant        GM_openInTab
// ==/UserScript==

(function() {
    'use strict';

    var lastTime = 0; // the last time the confirm dialog was shown
    var interval = 3000; // the minimum interval between two confirm dialogs (in milliseconds)

    // get the selected text
    function getSelectionText() {
        var text = "";
        if (window.getSelection) {
            text = window.getSelection().toString();
        } else if (document.selection && document.selection.type != "Control") {
            text = document.selection.createRange().text;
        }
        return text;
    }

    // check if the text is a valid pixiv id
    function isValidPixivId(text) {
        text = text.replace(/\s/g, ''); // remove all whitespace characters
        var regex = /^\d{5,12}$/; // a number between 5 and 12 digits
        return regex.test(text);
    }

    // generate the pixiv url by id
    function getPixivUrl(id) {
        var baseUrl = "https://www.pixiv.net/member_illust.php?illust_id=";
        return baseUrl + id + "&mode=medium";
    }

    // open the pixiv url in a new tab
    function openPixivUrl(url) {
        GM_openInTab(url, {active: true, insert: true});
    }

    // handle the mouseup event
    function handleMouseUp(event) {
        var currentTime = new Date().getTime(); // get the current time
        if (currentTime - lastTime < interval) { // if the interval is too short
            return; // do nothing
        }
        lastTime = currentTime; // update the last time

        var text = getSelectionText(); // get the selected text
        if (isValidPixivId(text)) { // check if it is a valid pixiv id
            var url = getPixivUrl(text); // generate the pixiv url
            var confirm = window.confirm("Do you want to open this pixiv work: " + url + "?"); // ask for confirmation
            if (confirm) { // if confirmed
                openPixivUrl(url); // open the url in a new tab
            }
        }
    }

    // add the event listener to the document
    document.addEventListener("mouseup", handleMouseUp, false);
})();