Certainly! This script is a UserScript designed to run on specific websites and provide functionality to download images from those sites as a ZIP file. It's built to work with Tampermonkey or similar UserScript managers. Below is a comprehensive breakdown of the script, explaining each part in detail.
1. UserScript Metadata Block
At the very beginning of the script, there's a metadata block that informs the UserScript manager about the script's attributes and requirements.
// ==UserScript==
// @name WebURL Image Downloader
// @namespace http://tampermonkey.net/
// @version 1.1
// @description Download images from specified WebURLs as a ZIP file.
// @author Your Name
// @match http://d15.876515.xyz/*
// @match http://98.987328.xyz/*
// @match http://97.987327.xyz/*
// @grant GM_download
// @require https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.0/jszip.min.js
// @connect *
// ==/UserScript==
Explanation of Metadata Fields:
-
@name: The name of the script as it will appear in the UserScript manager.
-
@namespace: A unique identifier to avoid conflicts with other scripts.
-
@version: Version number of the script, useful for updates.
-
@description: A short description of what the script does.
-
@author
: The author's name.
-
@match: Specifies the URLs where this script will run. In this case, it runs on any pages under the domains:
http://d15.876515.xyz/*
http://98.987328.xyz/*
http://97.987327.xyz/*
-
@grant: Permissions the script needs. GM_download allows downloading files.
-
@require: External scripts that this script depends on. Here, it includes JSZip from a CDN, which is used to create ZIP files.
-
@connect: Specifies which domains the script can make cross-origin requests to. * allows all.
2. IIFE (Immediately Invoked Function Expression)
The entire script is wrapped inside an asynchronous IIFE to avoid polluting the global namespace and to allow the use of await for asynchronous operations.
(async function() {
'use strict';
// ... rest of the code ...
})();
3. Utility Functions
a. fetchHTML(url)
Fetches and parses HTML content from a given URL.
async function fetchHTML(url) {
try {
const response = await fetch(url);
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
const text = await response.text();
const parser = new DOMParser();
return parser.parseFromString(text, 'text/html');
} catch (error) {
console.error(`Error fetching HTML from ${url}: ${error}`);
throw error;
}
}
-
Purpose: Retrieve the HTML of a page and parse it into a DOM structure for further manipulation.
-
Process:
- Make an HTTP GET request to the specified
url.
- Check if the response is successful (
response.ok).
- Extract the text content from the response.
- Parse the text into an HTML
Document using DOMParser.
- Return the parsed document.
-
Error Handling: Logs an error if fetching or parsing fails and rethrows the error for upstream handling.
b. fetchImage(url)
Fetches an image and returns it as a Blob.
async function fetchImage(url) {
try {
const response = await fetch(url);
if (!response.ok) throw new Error(`Failed to fetch image: ${url} - Status: ${response.status}`);
return await response.blob();
} catch (error) {
console.warn(`Error fetching image ${url}: ${error}`);
throw error;
}
}
c. getFileExtension(url)
Extracts the file extension from a URL.
function getFileExtension(url) {
const match = url.match(/\.([a-zA-Z0-9]+)(?:\?.*)?$/);
return match ? match[1].toLowerCase() : null;
}
d. makeAbsoluteURL(url, base)
Converts a relative URL to an absolute URL based on a base URL.
function makeAbsoluteURL(url, base) {
try {
return new URL(url, base).href;
} catch {
return url; // Return original if invalid
}
}
4. addDownloadButton(spanElement, pageUrl)
Creates and appends a "DOWNLOAD" button to a specific <span> element on the page.
function addDownloadButton(spanElement, pageUrl) {
// Create the button
const button = document.createElement('button');
button.innerText = 'DOWNLOAD';
// ... (styling omitted for brevity) ...
// Hover effect
button.addEventListener('mouseenter', () => {
button.style.backgroundColor = '#218838';
});
button.addEventListener('mouseleave', () => {
button.style.backgroundColor = '#28a745';
});
// Add click event listener
button.addEventListener('click', async () => {
// ... (button state management) ...
try {
await downloadImages(pageUrl);
// ... (success handling) ...
} catch (error) {
// ... (error handling) ...
}
});
// Append the button to the span element
spanElement.appendChild(button);
}
Detailed Steps:
-
Button Creation and Styling:
- A
<button> element is created.
- Text set to "DOWNLOAD".
- Inline styles are applied to make the button visually appealing (padding, background color, cursor, etc.).
- Hover effects are added to change the background color when the user hovers over the button.
-
Event Listeners:
- Click Event:
- Disabling: Prevents multiple clicks by disabling the button.
- State Management: Changes button text to "Processing..." during the operation.
- Download Initiation: Calls
downloadImages(pageUrl) to start the download process.
- Success: Re-enables the button, resets text, and alerts the user upon successful completion.
- Error: Re-enables the button, resets text, and alerts the user if an error occurs.
-
Appending the Button:
- The button is added as a child to the provided
spanElement.
5. downloadImages(initialPageUrl)
Handles the core functionality of downloading images from the specified URLs and packaging them into a ZIP file.
async function downloadImages(initialPageUrl) {
// Fetch the initial page
const initialDoc = await fetchHTML(initialPageUrl);
// Extract TITLE from div.jianjie
// ... (TITLE extraction code) ...
// Initialize JSZip
const zip = new JSZip();
// Extract all related PageURLs from div.page
// ... (Page URL extraction code) ...
// Limit concurrent fetches to avoid overloading
const CONCURRENT_LIMIT = 5;
let index = 0;
// Collect all image URLs
const images = [];
const workers = [];
for (let i = 0; i < CONCURRENT_LIMIT; i++) {
workers.push(processNext());
}
await Promise.all(workers);
if (images.length === 0) throw new Error('No images found.');
// Fetch all images and add to zip
let counter = 0;
const total = images.length;
for (const imgUrl of images) {
try {
const absoluteImgUrl = makeAbsoluteURL(imgUrl, initialPageUrl);
const blob = await fetchImage(absoluteImgUrl);
const extension = getFileExtension(imgUrl) || 'jpg';
const filename = `${String(counter + 1).padStart(3, '0')}.${extension}`;
zip.file(filename, blob);
counter++;
console.log(`Added ${filename} to ZIP (${counter}/${total})`);
} catch (e) {
console.warn(`Failed to fetch image ${imgUrl}: ${e.message}`);
}
}
if (counter === 0) throw new Error('No images were successfully downloaded.');
// Generate the zip file
const zipBlob = await zip.generateAsync({ type: 'blob' });
// Trigger the download using GM_download
const blobUrl = URL.createObjectURL(zipBlob);
GM_download({
url: blobUrl,
name: `${TITLE}.zip`,
saveAs: true,
onload: () => {
URL.revokeObjectURL(blobUrl);
console.log('Download completed.');
},
onerror: (error) => {
console.error('Download failed:', error);
alert('Failed to download ZIP file.');
}
});
}
Detailed Steps:
-
Fetch Initial Page:
- Uses
fetchHTML to retrieve and parse the HTML of initialPageUrl.
-
Extract Title (TITLE):
const jianjieDiv = initialDoc.querySelector('div.jianjie');
if (!jianjieDiv) throw new Error('div.jianjie not found.');
const jianjieText = jianjieDiv.textContent;
const titleMatch = jianjieText.match(/\[ (.*?)P\]/);
if (!titleMatch || !titleMatch[1]) throw new Error('TITLE not found.');
const TITLE = titleMatch[1].trim().replace(/[\\/:*?"<>|]/g, '_');
- Purpose: Extracts a title string from a
div with the class jianjie.
- Process:
- Locates the
div.jianjie element.
- Extracts its text content.
- Uses a regular expression to capture text within
[ ... P].
- Cleans the extracted title by trimming whitespace and replacing illegal filename characters with underscores (
_).
-
Initialize JSZip:
const zip = new JSZip();
- Purpose: Creates a new ZIP archive to which images will be added.
-
Extract All Related Page URLs:
const pageDiv = initialDoc.querySelector('div.page');
if (!pageDiv) throw new Error('div.page not found.');
const pageLinks = pageDiv.querySelectorAll('a[href]');
const pageUrls = Array.from(pageLinks).map(link => {
let href = link.getAttribute('href');
if (!href.startsWith('http')) {
href = new URL(href, initialPageUrl).href;
}
return href;
});
if (pageUrls.length === 0) throw new Error('No page URLs found.');
- Purpose: Retrieves all URLs of related pages that contain images.
- Process:
- Finds the
div.page element.
- Selects all
<a> tags with an href attribute within div.page.
- Converts relative URLs to absolute URLs using
initialPageUrl as the base.
- Collects all absolute page URLs into
pageUrls array.
-
Concurrent Fetching of Image URLs:
const CONCURRENT_LIMIT = 5;
let index = 0;
const images = [];
const workers = [];
for (let i = 0; i < CONCURRENT_LIMIT; i++) {
workers.push(processNext());
}
await Promise.all(workers);
6. Helper Functions
a. getFileExtension(url)
This function was explained earlier. It extracts the file extension from the image URL.
b. makeAbsoluteURL(url, base)
This function was also explained earlier. It ensures the image URLs are absolute.
7. Initialize Function
Locates the specific span elements on the page and appends the "DOWNLOAD" button to each.
function initialize() {
const spanElements = document.querySelectorAll('div.title h2 a span');
spanElements.forEach(span => {
// Avoid adding multiple buttons
if (span.querySelector('button') === null) {
const aTag = span.parentElement;
if (aTag && aTag.href) {
// Construct absolute PageURL
const pageUrl = aTag.href.startsWith('http') ? aTag.href : new URL(aTag.getAttribute('href'), window.location.origin).href;
addDownloadButton(span, pageUrl);
}
}
});
}
Detailed Steps:
-
Selecting Target Span Elements:
- The script looks for all
<span> elements that are descendants of div.title > h2 > a.
-
Avoiding Duplicate Buttons:
- Checks if a button has already been added to the span by verifying if it contains a
<button>. If a button exists, it skips adding another.
-
Extracting Page URL:
- Retrieves the parent
<a> tag of the <span>, ensuring it has an href attribute.
- Converts relative URLs to absolute URLs based on the current page's origin.
-
Adding the Download Button:
- Calls
addDownloadButton(span, pageUrl) to append the "DOWNLOAD" button to the span element.
8. DOMContentLoaded Event Listener
Ensures that the script runs after the DOM has fully loaded.
// Wait for the DOM to load before initializing
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initialize);
} else {
initialize();
}
9. Styling and User Experience Enhancements
Throughout the script, especially within the addDownloadButton function, the script applies inline styles to the "DOWNLOAD" button to make it visually appealing and user-friendly. Here's a quick summary:
10. Error Handling and Logging
The script includes comprehensive error handling and logging to ensure robustness:
-
Fetching Errors:
- If any network request fails (whether fetching HTML pages or images), the script logs a warning or error to the console and gracefully continues or alerts the user as appropriate.
-
Validation Checks:
- Ensures essential elements (
div.jianjie, div.page, images) exist and throws errors if they don't, preventing the script from proceeding with incomplete data.
-
User Feedback:
- Displays alerts to inform the user of success or failure, enhancing transparency.
-
Progress Logging:
- Logs progress in the console as images are added to the ZIP, which can help in debugging or monitoring.
11. External Dependencies
-
JSZip (3.10.0):
- Included via
@require.
- Used to create and manage ZIP archives within the browser.
-
GM_download:
- Provided via the
@grant directive.
- Facilitates the downloading of files, especially useful for downloading blobs as files in UserScripts.
12. Security Considerations
-
@connect *:
- Allows the script to make cross-origin requests to any domain.
- Potential Risks: This is broad and could be abused. Limiting connections to specific domains could enhance security.
-
@grant GM_download:
- Provides download capabilities which can be sensitive.
- Precautions: Ensure the script only operates on trusted domains (as specified in
@match) to minimize misuse.
-
User Input:
- The script does not take external input, reducing risks from injection attacks.
13. Summary of Workflow
-
Script Injection:
- When the user navigates to any of the specified URLs (matches in the metadata), the UserScript runs.
-
Initialization:
- Once the DOM is ready, the script searches for specific
<span> elements within div.title > h2 > a > span.
-
Button Addition:
- For each targeted span, it appends a styled "DOWNLOAD" button if one doesn't already exist.
-
User Interaction:
- When the user clicks the "DOWNLOAD" button:
- The button becomes disabled and shows "Processing...".
- The script begins fetching the initial page's HTML.
-
Data Extraction:
- Extracts a title from
div.jianjie for naming the ZIP file.
- Finds all related page URLs from
div.page > a.
-
Image Collection:
- Concurrently (up to 5 at a time), fetches each related page.
- Extracts all image URLs from
div.content > p > img.
-
Image Downloading:
- Fetches each image as a Blob and adds it to a ZIP file with sequentially numbered filenames.
-
ZIP Generation and Download:
- Once all images are collected, the script generates a ZIP Blob.
- Initiates a download of the ZIP file using
GM_download.
-
Completion:
- Alerts the user upon successful download or notifies them if an error occurs.
- Resets the button state to allow future downloads.
Potential Improvements and Considerations
-
Concurrency Control:
- While a concurrency limit is set, additional mechanisms like exponential backoff on failures might make the script more resilient.
-
Progress Indicators:
- Currently, progress is logged to the console. Integrating on-page progress bars or status messages could enhance user experience.
-
Error Reporting:
- Aggregating and displaying all failed image URLs to the user could help in troubleshooting.
-
Dynamic Matching:
- The script currently matches specific hard-coded domains. Making the
@match patterns more dynamic or configurable could increase flexibility.
-
File Naming Conflicts:
- If different runs of the script process images with overlapping naming schemes, consider adding timestamps or unique identifiers to ZIP filenames.
-
Resource Cleanup:
- Ensuring all object URLs are properly revoked even in error cases can prevent memory leaks.
-
User Permissions:
- Limiting
@connect to only necessary domains enhances security.
-
Localization:
- Replacing hard-coded strings like "DOWNLOAD" and alerts with localized versions could make the script more versatile for non-English users.
Conclusion
This UserScript is a powerful tool for downloading images from specific web pages and compiling them into a ZIP file for easy access. It leverages modern JavaScript features and external libraries to handle asynchronous operations, DOM manipulation, and file handling seamlessly. With thoughtful error handling and user feedback mechanisms, it ensures a smooth user experience while performing potentially complex tasks under the hood.
If you plan to modify or extend this script, consider the potential improvements mentioned above to enhance functionality, security, and usability.