You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Tampermonkey中使用SweetAlert2提示Swal未定义的问题

解决Tampermonkey中SweetAlert2「Swal is undefined」的问题

针对你遇到的Swal未定义问题,可尝试以下几种解决方案:

方案1:直接访问全局window对象上的Swal

有时候即使通过@require引入了SweetAlert2,页面作用域的隔离或变量冲突可能导致脚本无法直接读取Swal变量,此时直接调用window.Swal可确保访问全局环境中的实例:

// ==UserScript==
// @name         Quizlet Explanations Get Answer
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        https://quizlet.com/explanations/questions/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=quizlet.com
// @require      https://cdn.jsdelivr.net/npm/sweetalert2@11.6.16/dist/sweetalert2.all.min.js
// @grant        none
// ==/UserScript==

/* global Swal */

window.onload = function() {
    window.Swal.fire(
        'Good job!',
        'You clicked the button!',
        'success'
    );
}

方案2:动态注入SweetAlert2脚本

如果@require的加载机制存在异常,可改用动态创建script标签的方式手动加载依赖,绕过Tampermonkey的加载流程:

// ==UserScript==
// @name         Quizlet Explanations Get Answer
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        https://quizlet.com/explanations/questions/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=quizlet.com
// @grant        none
// ==/UserScript==

function loadSweetAlert2(callback) {
    const script = document.createElement('script');
    script.src = 'https://cdn.jsdelivr.net/npm/sweetalert2@11.6.16/dist/sweetalert2.all.min.js';
    script.onload = callback;
    document.head.appendChild(script);
}

// 加载完成后调用SweetAlert2
loadSweetAlert2(function() {
    window.Swal.fire(
        'Good job!',
        'You clicked the button!',
        'success'
    );
});

额外检查项

  • 确认Tampermonkey脚本已正确启用,且@match规则与当前访问的Quizlet页面URL完全匹配
  • 清除浏览器缓存后重新加载页面,避免旧的缓存资源干扰
  • 检查浏览器控制台是否有其他加载错误,确认SweetAlert2的CDN链接可正常访问

内容的提问来源于stack exchange,提问作者Moist Nugget

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 19:35:26