I am developing a web extension that is to read and parse an uploaded epub file. Since the Content Security Policy for Chrome extensions restricts external javascript files from being linked to an extension, I have had to download the entire required epub.js
, jszip.js
and jszip-utils.min.js
files and include them in my project. I also updated the "web_accessible_resources" with these files.
The issue I have now is that my code indicates that the above-mentioned javascript files fail to load when I upload an epub file. Following is my code. Focus on the loadBook()
function that always gets stuck in a loop and logs out: 'Error: JSZip library not loaded, trying again'
repeatedly.
function loadBook() {
if (typeof JSZip === 'undefined' || typeof JSZip.utils === 'undefined') {
console.log('Error: JSZip library not loaded, trying again');
setTimeout(loadBook, 1000);
return;
}
Find below the entire code which runs when I upload an epub file:
function handleFileSelection(event) {
const file = event.target.files[0]; // Get the selected file
const reader = new FileReader();
reader.onload = function (event) {
// File reading completed
const fileData = event.target.result; // Get the file data
console.log('fileData: ', fileData);
// Create a script element for EPUB.js
const epubScript = document.createElement('script');
epubScript.src = chrome.runtime.getURL('epub.js');
document.head.appendChild(epubScript);
// Create a script element for JSZip
const jszipScript = document.createElement('script');
jszipScript.src = chrome.runtime.getURL('jszip.min.js');
document.head.appendChild(jszipScript);
// Create a script element for JSZip Utils
const jszipUtilsScript = document.createElement('script');
jszipUtilsScript.src = chrome.runtime.getURL('jszip-utils.min.js');
document.head.appendChild(jszipUtilsScript);
// Wait for all scripts to load
Promise.all([
new Promise((resolve) => {
epubScript.onload = resolve;
}),
new Promise((resolve) => {
jszipScript.onload = resolve;
}),
new Promise((resolve) => {
jszipUtilsScript.onload = resolve;
}),
])
.then(() => {
// Both scripts are loaded, you can start using them here
console.log('EPUB.js and JSZip libraries are loaded');
// Create a new book instance
const book = ePub();
// Proceed with the book logic
loadBook();
function loadBook() {
if (typeof JSZip === 'undefined' || typeof JSZip.utils === 'undefined') {
console.log('Error: JSZip library not loaded, trying again');
setTimeout(loadBook, 1000);
return;
}
}
})
.catch((error) => {
console.error('Failed to load EPUB.js or JSZip:', error);
});
};
}
How can I resolve this or is there a better solution to this?