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:
JavaScript
x
9
1
// Create the element
2
var script = document.createElement("script");
3
4
// Add script content
5
script.src = `https://unpkg.com/jspdf@latest/dist/jspdf.umd.min.js`;
6
7
// Append
8
document.head.appendChild(script);
9
Can you explain why it is raising this error?
Code:
JavaScript
1
52
52
1
// ==UserScript==
2
// @name PDF Google
3
// @namespace http://tampermonkey.net/
4
// @version 0.1
5
// @description try to take over the world!
6
// @author You
7
// @match https://www.google.com/*
8
// @grant none
9
// ==/UserScript==
10
11
12
window.addEventListener('load', function () {
13
console.log('Running jsPDF')
14
15
// Create the element
16
var script = document.createElement("script");
17
18
// Add script content
19
script.src = `https://unpkg.com/jspdf@latest/dist/jspdf.umd.min.js`;
20
21
// Append
22
document.head.appendChild(script);
23
24
25
var button = document.createElement("button");
26
button.innerHTML = "Do Something";
27
button.onclick = function () {
28
29
var doc = new jsPDF();
30
var specialElementHandlers = {
31
'#editor': function (element, renderer) {
32
return true;
33
}
34
};
35
36
doc.fromHTML($('#content').html(), 15, 15, {
37
'width': 170,
38
'elementHandlers': specialElementHandlers
39
});
40
doc.save('sample-file.pdf');
41
}
42
43
var newLine = document.createElement("div");
44
newLine.innerHTML = "<br>";
45
46
var body = document.getElementsByClassName("FPdoLc tfB0Bf")[0];
47
body.append(newLine);
48
body.appendChild(button);
49
50
51
})
52
Advertisement
Answer
When you wrote:
JavaScript
1
2
1
script.src = `https://unpkg.com/jspdf@latest/dist/jspdf.umd.min.js`;
2
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.