I made a userscript for Google where I click "Do something", it prints out the webpage, in a PDF.
However, when I click on it, it gives an error: ReferenceError: jsPDF is not defined.
I have the jspdf file located with:
// 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);
Can you explain why it is raising this error?
Code:
// ==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);
})
When you wrote:
script.src = `https://unpkg.com/jspdf@latest/dist/jspdf.umd.min.js`;
you are using the grave accent instead of proper quotes:
https://en.wikipedia.org/wiki/Grave_accent
Once you fixed that, see if there is still an error.