ReferenceError: jsPDF is not defined (with access to the package)

ReferenceError: jsPDF is not defined (with access to the package)

我为 Google 创建了一个用户脚本,点击“做某事”,它以 PDF 格式打印网页。

但是,当我点击它时,它给出了一个错误:ReferenceError: jsPDF is not defined.

我的 jspdf 文件位于:

// Create the element
var script = document.createElement("script");
 
// Add script content
script.src = `https://unpkg.com/jspdf@latest/dist/jspdf.umd.min.js`;
 
// Append
document.head.appendChild(script);

你能解释一下为什么会出现这个错误吗?

代码:

// ==UserScript==
// @name         PDF Google
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        https://www.google.com/*
// @grant        none
// ==/UserScript==
 
 
window.addEventListener('load', function () {
    console.log('Running jsPDF')
 
    // Create the element
    var script = document.createElement("script");
 
    // Add script content
    script.src = `https://unpkg.com/jspdf@latest/dist/jspdf.umd.min.js`;
 
    // Append
    document.head.appendChild(script);
 
 
    var button = document.createElement("button");
    button.innerHTML = "Do Something";
    button.onclick = function () {
 
        var doc = new jsPDF();
        var specialElementHandlers = {
            '#editor': function (element, renderer) {
                return true;
            }
        };
 
        doc.fromHTML($('#content').html(), 15, 15, {
            'width': 170,
            'elementHandlers': specialElementHandlers
        });
        doc.save('sample-file.pdf');
    }
 
    var newLine = document.createElement("div");
    newLine.innerHTML = "<br>";
 
    var body = document.getElementsByClassName("FPdoLc tfB0Bf")[0];
    body.append(newLine);
    body.appendChild(button);
 
 
})

当你写道:

script.src = `https://unpkg.com/jspdf@latest/dist/jspdf.umd.min.js`;

您使用的是 重音符号 而不是正确的引号:

https://en.wikipedia.org/wiki/Grave_accent

修复后,查看是否仍然存在错误。