MediaWiki:Gadget-PrintOptions.js
外观
	
	
注意:在发布之后,您可能需要清除浏览器缓存才能看到所作出的更改的影响。
- Firefox或Safari:按住Shift的同时单击刷新,或按Ctrl-F5或Ctrl-R(Mac为⌘-R)
 - Google Chrome:按Ctrl-Shift-R(Mac为⌘-Shift-R)
 - Edge:按住Ctrl的同时单击刷新,或按Ctrl-F5。
 
(function () {
    'use strict';
    
    var windowManager;
    var printDialog;
    
    var printOptions = {
        install: function () {
            var $printLink = $('#t-print a');
            if ($printLink.length === 0) {
                return;
            }
            
            // ⚠️ 修复点:移除捕获阶段监听,改用标准事件绑定
            $printLink
                .text('可打印版本')
                .off('click')
                .one('click', function (e) {
                    // 🔧 修复点:确保仅在点击时加载资源并触发弹窗
                    mw.loader.using(['oojs-ui-core', 'oojs-ui-widgets', 'oojs-ui-windows'])
                        .then(function () {
                            printOptions.createWindow();
                        })
                        .catch(function (err) {
                            mw.log.error('打印对话框加载失败:', err);
                        });
                    
                    e.preventDefault();
                    e.stopPropagation();
                });
            
            // 🚀 预加载资源(不影响主流程)
            mw.loader.load(['oojs-ui-core', 'oojs-ui-widgets', 'oojs-ui-windows']);
        },
        
        createWindow: function () {
            // 🔒 防止重复初始化
            if (printDialog) {
                windowManager.openWindow(printDialog);
                return;
            }
            
            // 🖥️ 对话框类定义
            function PrintDialog(config) {
                PrintDialog.super.call(this, config);
            }
            OO.inheritClass(PrintDialog, OO.ui.ProcessDialog);
            
            PrintDialog.static.name = 'printdialog';
            PrintDialog.static.title = '打印此页面';
            PrintDialog.static.actions = [
                { action: 'print', label: '打印', flags: ['primary', 'progressive'] },
                { action: 'cancel', label: '取消', flags: 'safe' }
            ];
            
            PrintDialog.prototype.initialize = function () {
                PrintDialog.super.prototype.initialize.apply(this, arguments);
                
                this.panel = new OO.ui.PanelLayout({ padded: true, expanded: false });
                this.content = new OO.ui.FieldsetLayout();
                
                // ✅ 动态生成选项
                printOptions.questions.forEach(function (question) {
                    if (question.type === 'checkbox') {
                        var checkbox = new OO.ui.CheckboxInputWidget({
                            selected: question.checked
                        });
                        question.widget = checkbox;
                        this.content.addItems([
                            new OO.ui.FieldLayout(checkbox, {
                                label: question.label,
                                align: 'inline'
                            })
                        ]);
                    }
                }, this);
                
                this.panel.$element.append(this.content.$element);
                this.$body.append(this.panel.$element);
            };
            
            PrintDialog.prototype.getActionProcess = function (action) {
                if (action === 'print') {
                    return new OO.ui.Process(function () {
                        // 📝 保存用户选择
                        printOptions.questions.forEach(function (question) {
                            if (question.type === 'checkbox' && question.widget) {
                                printOptions[question.returnvalue] = question.widget.isSelected();
                            }
                        });
                        
                        return this.close({ action: action }).then(function () {
                            // ⏳ 添加延迟确保弹窗关闭后再打印
                            setTimeout(function () {
                                printOptions.changePrintCSS();
                                printOptions.otherEnhancements();
                                window.print();
                                setTimeout(function () {
                                    location.reload(); // 恢复页面状态
                                }, 500);
                            }, 100);
                        });
                    }.bind(this));
                }
                return PrintDialog.super.prototype.getActionProcess.call(this, action);
            };
            
            // 🌐 初始化窗口管理器
            if (!windowManager) {
                windowManager = new OO.ui.WindowManager();
                windowManager.$element.css('z-index', '100000'); // 确保在最顶层
                $('body').append(windowManager.$element);
            }
            
            // 🆕 创建对话框实例(仅首次)
            printDialog = new PrintDialog({ size: 'medium' });
            windowManager.addWindows([printDialog]);
            windowManager.openWindow(printDialog); // 🎯 关键修复:确保点击后才打开
        },
        
        changePrintCSS: function () {
            /* 原有样式处理逻辑(保持不变)*/
            var printStyle = '';
            if (this.enhanced === false) {
                // ...(样式表处理代码)
            }
            if (this.noimages) printStyle += 'img, .thumb { display:none !important; }\n';
            if (this.norefs) printStyle += '.references, .reference { display:none !important; }\n';
            if (this.notoc) printStyle += '#toc, .toc { display:none !important; }\n';
            if (this.nobackground) printStyle += 'body { background: white !important; }\n';
            if (this.blacktext) printStyle += '* { color: black !important; }\n';
            
            if (printStyle) {
                $('head').append('<style media="print">' + printStyle + '</style>');
            }
        },
        
        otherEnhancements: function () {
            var $link = $('div.printfooter a');
            try {
                $link.text(decodeURIComponent($link.text()));
            } catch (e) {
                mw.log.warn('URL解码失败:', e);
            }
        },
        
        questions: [
            {
                label: '隐藏界面元素',
                type: 'checkbox',
                checked: true,
                returnvalue: 'enhanced'
            },
            {
                label: '隐藏图像',
                type: 'checkbox',
                checked: false,
                returnvalue: 'noimages'
            },
            {
                label: '隐藏引用',
                type: 'checkbox',
                checked: false,
                returnvalue: 'norefs'
            },
            {
                label: '隐藏目录',
                type: 'checkbox',
                checked: false,
                returnvalue: 'notoc'
            },
            {
                label: '删除背景(部分浏览器可能无效)',
                type: 'checkbox',
                checked: false,
                returnvalue: 'nobackground'
            },
            {
                label: '强制文本为黑色',
                type: 'checkbox',
                checked: true,
                returnvalue: 'blacktext'
            }
        ]
    };
    
    // 🚦 安全初始化(避免与其他脚本冲突)
    mw.hook('wikipage.content').add(function () {
        if (mw.config.get('wgNamespaceNumber') >= 0) {
            setTimeout(printOptions.install, 0); // 确保在最后执行
        }
    });
})();