Add 'export to lichess' link to chessgames.com pages

Allows a user to quickly export a PGN to lichess for analysis

目前為 2021-11-19 提交的版本,檢視 最新版本

// ==UserScript==
// @name         Add 'export to lichess' link to chessgames.com pages
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  Allows a user to quickly export a PGN to lichess for analysis
// @author       UncleVinny
// @include      https://www.chessgames.com/perl/chessgame?gid=*
// @grant        none
// @license      MIT
// ==/UserScript==

// Note: this script tweaks the original by bfishbaum, found here:
// https://greasyfork.org/en/scripts/389928-lichess-analysis-link-on-chessbase

(function() {
    'use strict';
    const LICHESS_ANALYSIS = "https://lichess.org/paste";
    
    function getElementByXpath(path) {
        return document.evaluate(path, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
    }

    function buildPGNLink() {
        var url = new URL(window.location.href);
        var gid = url.searchParams.get("gid");
        var link = "https://www.chessgames.com/perl/nph-chesspgn?text=1&gid=" + gid;
        return link;
    }

    function buildLichessLink(callback) {
        var pgnLink = buildPGNLink();
        fetch(pgnLink).then(function(response) {
            response.text().then(function(body){
                var lichessLink = document.createElement("a");
                lichessLink.href = LICHESS_ANALYSIS + "?pgn="+cleanPGN(body);
                lichessLink.target = "_blank";
                lichessLink.text = "export to lichess.org";
                lichessLink.style.font = 'bold 12px verdana,arial,helvetica';
                lichessLink.style.color = '#4D4D4D'; // lichess grey!
                callback(lichessLink);
            });
        });
    }

    function cleanPGN(pgn) {
        var newPGN = pgn.split("\n");
        newPGN = newPGN.join(" ");
        return newPGN;
    }

    function addLichessLink(link) {
        // link is added below the "Get this game explained" advertisement
        var block = getElementByXpath("//html/body/center[2]/div");
        block.parentNode.insertBefore(link, block.nextSibling);
    }

    buildLichessLink(addLichessLink);

})();