Greasy Fork is available in English.

有章PDF下载

下载有章文档

// ==UserScript==
// @name         有章PDF下载
// @namespace    http://tampermonkey.net/
// @version      0.0.1
// @description  下载有章文档
// @author       2690874578@qq.com
// @match        https://www.ilawpress.com/assets/plugin/pdfviewer/web/viewer.html
// @icon         https://www.google.com/s2/favicons?sz=64&domain=ilawpress.com
// @grant        none
// @run-at       document-start
// @license      GPL-3.0-only
// ==/UserScript==


(function() {
    'use strict';


    // 全局常量
    const DL_PDF_API = "download_pdf";
    const DL_BTN = `<button id="dl-pdf" class="extend-navbar-btn fa fa-download" title="下载PDF" style="margin-right:1.1em;color:red" onclick="${DL_PDF_API}()"><span>下载PDF</span></button>`


    function print(...args) {
        const time = new Date().toTimeString().slice(0, 8);
        console.info(`[wk ${time}]`, ...args);
    }


    /**
     * @param {string} selectors 
     * @returns {HTMLElement}
     */
    function $(selectors) {
        return document.querySelector(selectors);
    }


    /**
     * @param {PDFDocumentProxy} doc 
     */
    async function save_pdf(doc) {
        const data = await doc.getData();
        const a = document.createElement("a");
        const title = top.document.title;
        a.download = `${title}.pdf`;
        const blob = new Blob([data], { type: "application/pdf" });
        const url = URL.createObjectURL(blob);
        a.href = url;
        a.click();
        URL.revokeObjectURL(url);
    }


    function add_dl_btn() {
        $("#toolbarViewerRight").insertAdjacentHTML("afterbegin", DL_BTN);
    }


    function hook_then() {
        print("entered hook_then");

        const then = Promise.prototype.then;
        Promise.prototype.then = function(...args) {
            for (const [i, arg] of args.entries()) {
                if (String(arg).includes("(pdfDocument) {")) {
                    print(...args);

                    args[i] = function(doc) {
                        print("doc:", doc);
                        window[DL_PDF_API] = () => save_pdf(doc);
                        add_dl_btn();
                        return arg.call(this, doc);
                    };
                    break;
                }
            }
            return then.apply(this, args);
        };
    }


    function main() {
        print("entered main");
        hook_then();
    }


    main();
})();