Initialize Intersection Observer for Infinite Scroll using Sentinel Element
*/
const setupSentinelObserver = () => {
const sentinel = document.getElementById('sentinel');
if (!('IntersectionObserver' in window)) {
// Fallback if IntersectionObserver is not supported
window.addEventListener('scroll', onScrollLoadNextPage);
return;
}
code
const sentinelObserver = new IntersectionObserver((entries) => {
const content = document.getElementById('content');
content.innerHTML = ''; // Clear existing content
// Reload the first page with the new search term
await loadNextPage();
Refresh Data Functionality
*/
const refreshButton = document.getElementById('refresh-button');
refreshButton.addEventListener('click', async () => {
showConfirmationModal('Are you sure you want to refresh the data? This may take a few moments.', async () => {
isLoading = true;
showLoader();
hasMore = true;
currentPage = 0;
refreshButton.disabled = true;
try {
// Clear existing data
await clearNovels();
// Fetch and parse fresh data
await fetchAndStoreNovels();
// Reload the first page of novels
document.getElementById('content').innerHTML = ''; // Clear existing content
await loadNextPage();
// Show success toast
showToast('Data refreshed successfully!', 'success');
} catch (error) {
console.error('Error refreshing data:', error);
showTemporaryError('Failed to refresh data. Please try again later.', 5000);
// Show error toast
showToast('Failed to refresh data.', 'error');
} finally {
hideLoader();
isLoading = false;
refreshButton.disabled = false;
}
});
});
Initialize Application
*/
const initializeApp = async () => {
try {
// Open the database
await openDatabase();
// Check if any novels are already stored in IndexedDB
const count = await countNovels();
if (count === 0) {
// Fetch and store data from the external website
await fetchAndStoreNovels();
} else {
// Validate existing data
const novels = await getAllNovels();
if (!validateNovels(novels)) {
await clearNovels();
await fetchAndStoreNovels();
}
}
// Load the first page of novels
await loadNextPage();
// Edge case: Load more if content doesn't fill viewport
if (document.body.scrollHeight <= window.innerHeight && hasMore && !isLoading) {
loadNextPageWrapper();
}
} catch (error) {
console.error('Error initializing application:', error);
showTemporaryError('Failed to load novels. Please try refreshing the page.', 5000);
// Show error toast
showToast('Failed to load novels.', 'error');
}
};
/**
Fetch and Store Novels
*/
const fetchAndStoreNovels = async () => {
try {
const html = await retryOperation(() => fetchHTML('https://jnovels.com/top-light-novels-to-read/'));
let novels = parseHTML(html);
if (novels.length === 0) {
throw new Error('No novels found on the target page.');
}
console.log('Novels fetched and stored successfully:', novelsToAdd.length);
// Show success toast
showToast('Novels fetched and stored successfully.', 'success');
code
} catch (error) {
code
console.error('Error fetching or storing novels:', error);
showTemporaryError('Failed to fetch and store novels. Please try again later.', 5000);
// Show error toast
showToast('Failed to fetch and store novels.', 'error');
} finally {
hideProgress();
}
};
const bulkAddNovelsWithProgress = async (novels, progressCallback) => {
const total = novels.length;
let completed = 0;
// Select all h3 tags as they contain the novel names and links
code
const h3Elements = doc.querySelectorAll('h3');
h3Elements.forEach((h3Element) => {
try {
const aTag = h3Element.querySelector('a');
const spanTag = h3Element.querySelector('span');
if (!aTag || !spanTag) return; // Skip if either tag is missing
const name = spanTag.textContent.trim();
const pdfLink = aTag.getAttribute('href').trim();
// The cover image is inside the following p tag
let pElement = h3Element.nextElementSibling;
while (pElement && pElement.tagName.toLowerCase() !== 'p') {
pElement = pElement.nextElementSibling;
}
if (!pElement) return; // Skip if p tag is missing
const imgTag = pElement.querySelector('img');
if (!imgTag) return; // Skip if img tag is missing
let coverUrl = imgTag.getAttribute('src') || imgTag.getAttribute('data-src');
if (!coverUrl) return; // Skip if cover URL is missing
// Handle different URL formats
if (coverUrl.startsWith('//')) {
coverUrl = `https:${coverUrl}`;
} else if (coverUrl.startsWith('/')) {
coverUrl = `https://jnovels.com${coverUrl}`;
} else if (!coverUrl.startsWith('http')) {
// Handle relative URLs without leading '/'
coverUrl = `https://jnovels.com/${coverUrl}`;
}
// Validate extracted data
if (name && pdfLink && coverUrl) {
const novelKey = `${name}-${coverUrl}-${pdfLink}`;
if (!uniqueNovels.has(novelKey)) {
uniqueNovels.add(novelKey);
novels.push({
name,
coverUrl,
pdfUrl: pdfLink
});
}
} else {
console.warn('Incomplete novel data found and skipped:', { name, pdfLink, coverUrl });
}
} catch (error) {
// Skip any malformed entries
console.error('Error parsing a novel entry:', error);
}
});
return novels;
Show Progress Bar and Text
*/
const showProgress = () => {
document.getElementById('progress-container').style.display = 'block';
document.getElementById('progress-text').style.display = 'block';
};
/**
Hide Progress Bar and Text
*/
const hideProgress = () => {
document.getElementById('progress-container').style.display = 'none';
document.getElementById('progress-text').style.display = 'none';
};
Initialize AOS and Start the Application once the DOM is fully loaded
*/
document.addEventListener('DOMContentLoaded', () => {
// Initialize AOS if available
if (window.AOS) {
AOS.init({
duration: 800,
easing: 'ease-in-out',
once: true,
});
}
The errors you're encountering indicate that your application is experiencing issues with initializing and interacting with IndexedDB. Let's break down each error and provide a comprehensive guide to diagnose and resolve them.
Error Overview:
Database open request error: [object DOMException]
These errors collectively suggest that the IndexedDB (db) is not being successfully initialized, leading to failures when attempting to perform transactions.
Step-by-Step Diagnosis and Solutions:
1. Enhance Error Logging for Better Insights
Before diving deep into solutions, it's crucial to understand the exact nature of the DOMException. Currently, the errors are being logged as [object DOMException], which isn't very informative.
Modify Your Error Logging:
Locate the error handlers related to IndexedDB operations and enhance them to provide more detailed information.
Logging both error.name and error.message will give you specific information about what went wrong (e.g., QuotaExceededError, InvalidStateError, etc.).
2. Verify Browser Compatibility and Support
Ensure that the browser you're using supports IndexedDB. Most modern browsers do, but it's worth verifying.
Check Compatibility: Refer to Can I Use IndexedDB to verify if your browser version supports IndexedDB.
Test in Multiple Browsers: Sometimes, the issue might be browser-specific. Try running your application in another browser to see if the problem persists.
3. Ensure Secure Contexts (HTTPS or localhost)
IndexedDB requires secure contexts to function correctly. Serving your application over HTTP or directly via the file:// protocol can lead to failures.
Solution: Serve via a Local Server
Using Python (if Python is installed):
bash
# For Python 3.x
python -m http.server 8000
Navigate to http://localhost:8000 in your browser.
Using Node.js (if Node is installed):
Install a simple server:
bash
npm install -g http-server
Start the server:
bash
http-server -p 8000
Access via http://localhost:8000.
Why?
Running your application from a local server ensures it's served over HTTP, satisfying IndexedDB's secure context requirements.
4. Clear or Reset Existing IndexedDB Data
Old or corrupted IndexedDB data can prevent your application from initializing correctly, especially if there have been changes to the database schema.
Steps to Clear IndexedDB:
Open Developer Tools:
Right-click on your webpage and select Inspect or press F12.
Navigate to Application Tab:
In Chrome: Go to the Application tab.
In Firefox: Go to Storage or similar sections.
Locate IndexedDB:
Find MonochromeNovelsDB under the IndexedDB section.
Delete the Database:
Right-click on MonochromeNovelsDB and select Delete.
Refresh Your Application:
Reload your webpage to let the application recreate the database fresh.
Why?
Removing existing data ensures that any potential schema mismatches or corrupted data are eliminated, allowing your upgrade logic to execute without hindrance.
5. Review and Refine Database Upgrade Logic
Your onupgradeneeded function manages schema upgrades. It's essential to ensure that this logic is robust and handles all necessary cases.
Potential Issues in Current Code:
Redundant Index Creation:
In version 1, you're already creating the nameLower index:
Then, in version 2, you're checking if it exists and creating it if it doesn't:
javascript
if (!novelsStore.indexNames.contains('nameLower')) {
novelsStore.createIndex('nameLower', 'nameLower', { unique: false });
}
Since nameLower is already created in version 1, this may be unnecessary unless there's a specific reason to recreate it.
Recommendation:
Simplify your upgrade logic to avoid redundant operations. Ensure that each upgrade step is necessary and doesn't conflict with existing schemas.
Example Simplified onupgradeneeded:
javascript
request.onupgradeneeded = function(event) {
const db = request.result;
switch (event.oldVersion) {
case 0:
// Initial creation of object stores
const novelsStore = db.createObjectStore('novels', { keyPath: 'id', autoIncrement: true });
novelsStore.createIndex('name', 'name', { unique: true });
novelsStore.createIndex('coverUrl', 'coverUrl', { unique: true });
novelsStore.createIndex('pdfUrl', 'pdfUrl', { unique: true });
novelsStore.createIndex('timestamp', 'timestamp', { unique: false });
const settingsStore = db.createObjectStore('settings', { keyPath: 'key' });
settingsStore.createIndex('key', 'key', { unique: true });
break;
case 1:
// Upgrade to version 2: Add nameLower index if not present
const transaction = event.target.transaction;
const novelsStoreV2 = transaction.objectStore('novels');
if (!novelsStoreV2.indexNames.contains('nameLower')) {
novelsStoreV2.createIndex('nameLower', 'nameLower', { unique: false });
}
break;
// Handle future upgrades here
default:
break;
}
};
Why?
Using a switch statement based on oldVersion provides a clear and scalable way to handle multiple upgrade scenarios.
6. Address Unique Index Constraints
Your object stores have unique indexes on several fields (name, coverUrl, pdfUrl). If the data you're inserting contains duplicates for these fields, put operations will fail.
Potential Issue:
Duplicate Entries:
If two novels share the same name, coverUrl, or pdfUrl, attempting to put them into the IndexedDB will violate the unique constraints, causing errors.
Solution:
Ensure Data Uniqueness:
Before inserting data, ensure that these fields are indeed unique across all entries.
Handle Errors Gracefully:
Modify your bulkAddNovels function to handle duplicate errors without stopping the entire operation.
// Add a novel
const addNovel = async (novel) => {
const db = await dbPromise;
await db.put('novels', novel);
};
// Get all novels
const getAllNovels = async () => {
const db = await dbPromise;
return await db.getAll('novels');
};
Why?
Using a library like idb streamlines your interactions with IndexedDB, making your code cleaner and reducing the likelihood of errors.
Final Recommendations:
Implement Enhanced Error Logging:
Detailed error messages will provide clarity on what exactly is failing, enabling targeted fixes.
Ensure a Secure and Compatible Environment:
Serving your application via a local server and verifying browser support are foundational steps to ensure IndexedDB functions correctly.
Refine Database Schema and Operations:
Carefully manage your database's schema, handle unique constraints properly, and ensure that your upgrade logic is error-free.
Optimize Data Storage:
Be mindful of storage quotas and implement data management strategies to prevent exceeding limits.
Consider Using IndexedDB Wrapper Libraries:
Leveraging existing libraries can simplify your codebase and improve reliability.
Test Thoroughly After Each Change:
After implementing each recommended change, test your application to see if the issue persists or if new issues arise.
Conclusion
The primary issue centers around the failure to open the IndexedDB database, leading to cascading errors in your application. By enhancing error logging, ensuring a proper serving environment, refining your database interactions, and possibly leveraging dedicated libraries, you can resolve these errors and stabilize your application's data layer.
If after following these steps you still encounter issues, please provide the updated error logs with detailed error.name and error.message to facilitate more precise assistance.