【问题标题】:External dependency not defined, even though it was loaded with @require外部依赖未定义,即使它是用 @require 加载的
【发布时间】:2023-02-02 09:14:49
【问题描述】:

我正在尝试在 Tampermonkey 中安装和使用 sweetalert2,但我得到:

Swal 未定义

在控制台中。

我尝试使用@require/* globals 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() {
    Swal.fire(
        'Good job!',
        'You clicked the button!',
        'success'
    );
}

【问题讨论】:

    标签: javascript tampermonkey userscripts


    【解决方案1】:

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>sweetalert2 example</title>
    </head>
    
    <body>
    
      <script>
        window.onload = function() {
          Swal.fire({
            title: 'Good job!',
            text: 'You clicked the button!',
            type: 'success',
          });
        }
      </script>
      <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    </body>
    
    </html>

    将其链接到此 URL 而不是 https://cdn.jsdelivr.net/npm/sweetalert2@11

    这样该行将如下所示:

    // @require      https://cdn.jsdelivr.net/npm/sweetalert2@11
    

    在您的标签中添加 // @unwrap 标签并将其留空

    // @unwrap
    

    那么您的脚本将如下所示:

    /* global Swal */
    
    window.onload = function() {
                    Swal.fire({
                    title: 'Good job!',
                    text: 'You clicked the button!',
                    type: 'success',
                });
    }
    

    我希望这有帮助!

    【讨论】:

    • 您是否使用用户脚本管理器对其进行了测试?
    【解决方案2】:

    请注意来自the lib's source on GitHub 的这些代码行:

    if (typeof this !== 'undefined' && this.Sweetalert2) {
        this.swal = this.sweetAlert = this.Swal = this.SweetAlert = this.Sweetalert2
    }
    

    有两种解决方案:

    1. 使用Sweetalert2在任何情况下都由 JavaScript 文件公开。

    2. 启用沙盒模式通过将 // @unwrap 添加到标题中。当加载程序将脚本注入页面时,脚本存在于沙箱中,如果 @grantnone,沙箱将被禁用。使用// @unwrap,您可以实现所需的this行为并使用任何公开的swalsweetAlertSwalSweetAlert名称。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-02
      • 1970-01-01
      • 2012-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-10
      相关资源
      最近更新 更多