Certainly! It looks like you're aiming to create a comprehensive and feature-rich bookmarklet that extracts images from the current webpage and displays them in an enhanced viewer with functionalities like slideshow, zoom, panning, and more. However, combining large scripts into a bookmarklet can lead to issues such as syntax errors, improper encapsulation, and exceeding URL length limits.
Below, I'll guide you through refining your bookmarklet script to ensure it's fully functional. I'll address potential issues, optimize the script, and provide a minified version suitable for use as a bookmarklet.
Issues Identified
-
Concatenated Scripts: It appears that both your main script and a reference script were combined into a single block, separated by --- for functionalities, reference code: .... This can cause syntax errors and functional conflicts.
-
Window Reference in Viewer: Inside the viewer's embedded script, the unload event incorrectly references window.ultimateImageViewerInstance. It should reference the opener window to correctly reset the instance.
-
Bookmarklet Length: Bookmarklets have a length limitation (typically around 2,083 characters for maximum compatibility across browsers). Your script exceeds this, making it impractical as a traditional bookmarklet.
Recommendations
-
Separate Concerns: Keep the main script and the viewer's script separate to avoid conflicts.
-
Use External Hosting: Given the length and complexity of your script, it's advisable to host the viewer's code externally (e.g., on GitHub Pages or your server) and have the bookmarklet load it. This approach circumvents URL length limitations and makes maintenance easier.
-
Fix Window References: Ensure that the unload event in the viewer correctly references the opener window.
-
Minify the Script: Reduce the script size by minifying it to fit within bookmarklet constraints, if you choose to keep it self-contained.
Step-by-Step Guide
1. Host the Viewer Externally
To manage the complexity and size, host the viewer's HTML and JavaScript on an external server. Here's a simplified approach:
-
Create a Viewer Page: Develop a separate HTML page (viewer.html) containing all the necessary styles and scripts for the image viewer.
-
Host the Page: Upload viewer.html to a publicly accessible location (e.g., GitHub Pages, your own web server).
2. Modify the Main Bookmarklet Script
Update your main bookmarklet to open the external viewer.html and pass the image URLs via query parameters or other methods (like localStorage or postMessage). Here's how you can adjust your main script:
javascript:(function(){
'use strict';
// Configuration with optimized settings
const CONFIG = {
MAX_IMAGES: 500,
CHUNK_SIZE: 50,
CORS_PROXIES: [
'https://corsproxy.io/?',
'https://api.allorigins.win/raw?url=',
'https://api.codetabs.com/v1/proxy?quest='
],
VIEWER: {
MIN_WIDTH: 800,
MIN_HEIGHT: 600,
PREFERRED_WIDTH: 1200,
PREFERRED_HEIGHT: 800
},
SLIDESHOW: {
MIN_INTERVAL: 1,
MAX_INTERVAL: 10,
DEFAULT_INTERVAL: 3
},
PRELOAD: {
ADJACENT: 3,
BATCH_SIZE: 5,
TIMEOUT: 5000
},
ANIMATION: {
DURATION: 300,
EASING: 'cubic-bezier(0.4, 0, 0.2, 1)'
},
ZOOM: {
MIN: 1,
MAX: 5,
STEP: 0.1
},
GESTURE: {
SWIPE_THRESHOLD: 50,
PINCH_THRESHOLD: 0.1
},
CACHE: {
MAX_SIZE: 100,
EXPIRE_TIME: 3600000 // 1 hour
}
};
// Prevent multiple instances and handle cleanup
if (window.ultimateImageViewerInstance) {
try {
window.ultimateImageViewerInstance.focus();
return;
} catch (e) {
window.ultimateImageViewerInstance = null;
}
}
// Enhanced URL sanitization with additional security checks
function sanitizeURL(url) {
try {
const sanitized = new URL(url, window.location.href);
// Strict protocol check
if (!['http:', 'https:'].includes(sanitized.protocol)) {
return null;
}
// Exclude potentially dangerous file types
const dangerous = /\.(svg|svgz|html|htm|php|asp|aspx|jsp|cgi)$/i;
if (dangerous.test(sanitized.pathname)) {
return null;
}
// Check for common image extensions
const validExtension = /\.(jpe?g|png|gif|webp|avif|bmp|ico)$/i;
if (!validExtension.test(sanitized.pathname)) {
// Additional check for images without extensions
const contentType = url.match(/^data:image\/(jpeg|png|gif|webp|avif|bmp|ico)/i);
if (!contentType) {
return null;
}
}
// Remove hash and search parameters for cache consistency
sanitized.hash = '';
sanitized.search = '';
return sanitized.href;
} catch (e) {
return null;
}
}
// Advanced image source gathering with lazy-loading support
async function gatherImageSources() {
const sources = new Set();
const seenUrls = new Set();
let processedCount = 0;
// Process elements in chunks to avoid blocking
async function processElements(elements, attributeGetter) {
for (let i = 0; i < elements.length; i += CONFIG.CHUNK_SIZE) {
const chunk = Array.from(elements).slice(i, i + CONFIG.CHUNK_SIZE);
await new Promise(resolve => {
setTimeout(() => {
chunk.forEach(element => {
const urls = attributeGetter(element);
urls.forEach(url => {
if (!seenUrls.has(url)) {
seenUrls.add(url);
const sanitized = sanitizeURL(url);
if (sanitized) {
sources.add(sanitized);
processedCount++;
if (processedCount >= CONFIG.MAX_IMAGES) {
return Array.from(sources);
}
}
}
});
});
resolve();
}, 0);
});
if (processedCount >= CONFIG.MAX_IMAGES) break;
}
}
// Image tag sources
await processElements(
document.querySelectorAll('img'),
img => {
const urls = [];
['src', 'data-src', 'data-original', 'data-lazy', 'data-lazy-src'].forEach(attr => {
const value = img.getAttribute(attr);
if (value) urls.push(value);
});
const srcset = img.srcset;
if (srcset) {
srcset.split(',').forEach(src => {
const url = src.trim().split(' ')[0];
if (url) urls.push(url);
});
}
return urls;
}
);
// Background images
const styleObserver = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
if (mutation.type === 'attributes' && mutation.attributeName === 'style') {
const element = mutation.target;
const computed = window.getComputedStyle(element);
const background = computed.backgroundImage;
if (background && background !== 'none') {
const matches = background.match(/url\(['"]?([^'"]+)['"]?\)/g);
if (matches) {
matches.forEach(match => {
const url = match.slice(4, -1).replace(/['"]/g, '');
if (!seenUrls.has(url)) {
seenUrls.add(url);
const sanitized = sanitizeURL(url);
if (sanitized) sources.add(sanitized);
}
});
}
}
}
});
});
// Observe dynamic style changes
document.querySelectorAll('*').forEach(element => {
styleObserver.observe(element, {
attributes: true,
attributeFilter: ['style']
});
});
// Process link tags that might contain images
await processElements(
document.querySelectorAll('a[href]'),
link => {
const href = link.getAttribute('href');
return href ? [href] : [];
}
);
// Cleanup
styleObserver.disconnect();
return Array.from(sources).slice(0, CONFIG.MAX_IMAGES);
}
// Initialize viewer with advanced error handling
async function initializeViewer() {
try {
const imageUrls = await gatherImageSources();
if (imageUrls.length === 0) {
throw new Error('No valid images found on this page.');
}
// Calculate optimal window size
const screenWidth = window.screen.availWidth;
const screenHeight = window.screen.availHeight;
const width = Math.min(CONFIG.VIEWER.PREFERRED_WIDTH, screenWidth * 0.9);
const height = Math.min(CONFIG.VIEWER.PREFERRED_HEIGHT, screenHeight * 0.9);
// Open viewer window with position calculation
const left = (screenWidth - width) / 2;
const top = (screenHeight - height) / 2;
const viewer = window.open(
'',
'_blank',
`width=${width},height=${height},left=${left},top=${top},scrollbars=no,resizable=yes`
);
if (!viewer) {
throw new Error('Unable to open image viewer. Please allow popups for this website.');
}
window.ultimateImageViewerInstance = viewer;
// Generate viewer HTML
const viewerHTML = generateViewerHTML(imageUrls);
// Write content safely
viewer.document.open();
viewer.document.write(viewerHTML);
viewer.document.close();
// Add unload handler to reset the instance in the opener window
viewer.addEventListener('unload', () => {
window.ultimateImageViewerInstance = null;
});
} catch (error) {
console.error('Image Viewer Initialization Error:', error);
alert(error.message || 'An error occurred while initializing the image viewer.');
}
}
// Generate viewer HTML with modern UI
function generateViewerHTML(imageUrls) {
return `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="color-scheme" content="dark">
<title>Enhanced Image Viewer</title>
<style>
/* Modern CSS Reset */
*, *::before, *::after {
box-sizing: border-box;
margin: 0;
padding: 0;
}
/* Custom Properties */
:root {
--primary-bg: #1a1a1a;
--secondary-bg: #2a2a2a;
--primary-text: #ffffff;
--secondary-text: #cccccc;
--accent-color: #3498db;
--danger-color: #e74c3c;
--success-color: #2ecc71;
--border-radius: 8px;
--transition-duration: ${CONFIG.ANIMATION.DURATION}ms;
--transition-timing: ${CONFIG.ANIMATION.EASING};
}
/* Base Styles */
html {
font-size: 16px;
line-height: 1.5;
-webkit-text-size-adjust: 100%;
}
body {
font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
background-color: var(--primary-bg);
color: var(--primary-text);
overflow: hidden;
height: 100vh;
width: 100vw;
}
/* Container Layout */
.viewer-container {
position: relative;
width: 100%;
height: 100%;
display: grid;
grid-template-rows: auto 1fr auto;
gap: 1rem;
padding: 1rem;
}
/* Header Styles */
.viewer-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 0.5rem 1rem;
background-color: var(--secondary-bg);
border-radius: var(--border-radius);
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}
/* Main Content Area */
.viewer-main {
position: relative;
display: flex;
align-items: center;
justify-content: center;
overflow: hidden;
border-radius: var(--border-radius);
background-color: var(--secondary-bg);
}
/* Image Styles */
.main-image {
max-width: 100%;
max-height: 100%;
object-fit: contain;
transition: transform var(--transition-duration) var(--transition-timing),
opacity var(--transition-duration) var(--transition-timing);
opacity: 0;
cursor: grab;
touch-action: none;
will-change: transform, opacity;
}
.main-image.visible {
opacity: 1;
}
.main-image.panning {
cursor: grabbing;
}
/* Controls */
.controls {
display: flex;
gap: 0.5rem;
flex-wrap: wrap;
}
.controls button {
background-color: var(--secondary-bg);
color: var(--primary-text);
border: none;
padding: 0.5rem 1rem;
border-radius: var(--border-radius);
cursor: pointer;
transition: background-color var(--transition-duration) var(--transition-timing);
display: flex;
align-items: center;
gap: 0.5rem;
font-size: 0.875rem;
white-space: nowrap;
}
.controls button:hover {
background-color: var(--accent-color);
}
.controls button:active {
transform: translateY(1px);
}
/* Navigation Buttons */
.nav-button {
position: absolute;
top: 50%;
transform: translateY(-50%);
background-color: rgba(0, 0, 0, 0.5);
color: var(--primary-text);
border: none;
width: 48px;
height: 48px;
border-radius: 50%;
cursor: pointer;
opacity: 0;
transition: opacity var(--transition-duration) var(--transition-timing),
background-color var(--transition-duration) var(--transition-timing);
display: flex;
align-items: center;
justify-content: center;
font-size: 1.5rem;
}
.viewer-main:hover .nav-button {
opacity: 1;
}
.nav-button:hover {
background-color: rgba(0, 0, 0, 0.8);
}
.prev-button { left: 1rem; }
.next-button { right: 1rem; }
/* Thumbnails */
.thumbnails {
display: flex;
gap: 0.5rem;
padding: 0.5rem;
overflow-x: auto;
scrollbar-width: thin;
scrollbar-color: var(--accent-color) var(--secondary-bg);
background-color: var(--secondary-bg);
border-radius: var(--border-radius);
scroll-behavior: smooth;
}
.thumbnails::-webkit-scrollbar {
height: 6px;
}
.thumbnails::-webkit-scrollbar-track {
background: var(--secondary-bg);
border-radius: var(--border-radius);
}
.thumbnails::-webkit-scrollbar-thumb {
background-color: var(--accent-color);
border-radius: var(--border-radius);
}
.thumbnail {
width: 60px;
height: 60px;
object-fit: cover;
border-radius: 4px;
cursor: pointer;
transition: transform var(--transition-duration) var(--transition-timing),
box-shadow var(--transition-duration) var(--transition-timing);
flex-shrink: 0;
}
.thumbnail:hover {
transform: translateY(-2px);
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
}
.thumbnail.active {
border: 2px solid var(--accent-color);
transform: scale(1.1);
}
/* Loading Indicator */
.loader {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 40px;
height: 40px;
display: none;
}
.loader::after {
content: '';
width: 100%;
height: 100%;
border: 4px solid var(--secondary-bg);
border-top-color: var(--accent-color);
border-radius: 50%;
animation: spin 1s linear infinite;
display: block;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
/* Error Message */
.error-message {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: var(--danger-color);
color: white;
padding: 1rem;
border-radius: var(--border-radius);
text-align: center;
max-width: 80%;
display: none;
}
/* Responsive Design */
@media (max-width: 768px) {
.viewer-container {
padding: 0.5rem;
gap: 0.5rem;
}
.viewer-header {
padding: 0.25rem 0.5rem;
}
.controls button {
padding: 0.35rem 0.7rem;
font-size: 0.75rem;
}
.nav-button {
width: 36px;
height: 36px;
font-size: 1.25rem;
}
.thumbnail {
width: 48px;
height: 48px;
}
}
/* Touch Device Optimizations */
@media (hover: none) {
.nav-button {
opacity: 1;
background-color: rgba(0, 0, 0, 0.3);
}
}
</style>
</head>
<body>
<div class="viewer-container">
<div class="viewer-header">
<div class="controls">
<button id="playPauseBtn" aria-label="Toggle Slideshow">
<span class="icon">▶</span>
<span class="text">Slideshow</span>
</button>
<button id="downloadBtn" aria-label="Download Image">
<span class="icon">⬇</span>
<span class="text">Download</span>
</button>
<button id="zoomInBtn" aria-label="Zoom In">
<span class="icon">+</span>
<span class="text">Zoom In</span>
</button>
<button id="zoomOutBtn" aria-label="Zoom Out">
<span class="icon">-</span>
<span class="text">Zoom Out</span>
</button>
<button id="resetBtn" aria-label="Reset Zoom">
<span class="icon">↺</span>
<span class="text">Reset</span>
</button>
</div>
<button id="fullscreenBtn" class="fullscreen-btn" aria-label="Toggle Fullscreen">⛶</button>
</div>
<div class="viewer-main">
<img src="" alt="Main Image" class="main-image" id="mainImage">
<div class="loader" id="loader"></div>
<div class="error-message" id="errorMessage"></div>
<button class="nav-button prev-button" id="prevBtn" aria-label="Previous Image">❮</button>
<button class="nav-button next-button" id="nextBtn" aria-label="Next Image">❯</button>
</div>
<div class="thumbnails" id="thumbnails"></div>
</div>
<script>
(function() {
'use strict';
// Configuration
const CONFIG = ${JSON.stringify(CONFIG)};
const imageUrls = ${JSON.stringify(imageUrls)};
// State Management using Proxy for reactivity
const state = new Proxy({
currentIndex: 0,
isFullscreen: false,
isSlideshow: false,
slideshowInterval: null,
zoom: 1,
translateX: 0,
translateY: 0,
isPanning: false,
startX: 0,
startY: 0,
initialX: 0,
initialY: 0,
loadedImages: new Set(),
errorRetries: new Map(),
touchStartTime: 0,
touchStartX: 0,
lastTapTime: 0
}, {
set(target, property, value) {
const oldValue = target[property];
target[property] = value;
// React to state changes
switch(property) {
case 'currentIndex':
handleIndexChange(oldValue, value);
break;
case 'zoom':
handleZoomChange(value);
break;
case 'isSlideshow':
updateSlideshowUI(value);
break;
}
return true;
}
});
// Cache Management
const imageCache = {
cache: new Map(),
maxSize: CONFIG.CACHE.MAX_SIZE,
expireTime: CONFIG.CACHE.EXPIRE_TIME,
set(key, value) {
if (this.cache.size >= this.maxSize) {
const oldestKey = this.cache.keys().next().value;
this.cache.delete(oldestKey);
}
this.cache.set(key, {
value,
timestamp: Date.now()
});
},
get(key) {
const entry = this.cache.get(key);
if (!entry) return null;
if (Date.now() - entry.timestamp > this.expireTime) {
this.cache.delete(key);
return null;
}
return entry.value;
},
clear() {
this.cache.clear();
}
};
// Element References
const elements = {
mainImage: document.getElementById('mainImage'),
loader: document.getElementById('loader'),
errorMessage: document.getElementById('errorMessage'),
playPauseBtn: document.getElementById('playPauseBtn'),
downloadBtn: document.getElementById('downloadBtn'),
zoomInBtn: document.getElementById('zoomInBtn'),
zoomOutBtn: document.getElementById('zoomOutBtn'),
resetBtn: document.getElementById('resetBtn'),
fullscreenBtn: document.getElementById('fullscreenBtn'),
prevBtn: document.getElementById('prevBtn'),
nextBtn: document.getElementById('nextBtn'),
thumbnails: document.getElementById('thumbnails'),
container: document.querySelector('.viewer-container')
};
// Utility Functions
const utils = {
debounce(func, wait) {
let timeout;
return function executedFunction(...args) {
const later = () => {
clearTimeout(timeout);
func(...args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
},
throttle(func, limit) {
let inThrottle;
return function executedFunction(...args) {
if (!inThrottle) {
func(...args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
},
clamp(value, min, max) {
return Math.min(Math.max(value, min), max);
},
getDistance(touch1, touch2) {
return Math.hypot(
touch2.clientX - touch1.clientX,
touch2.clientY - touch1.clientY
);
},
getMidpoint(touch1, touch2) {
return {
x: (touch1.clientX + touch2.clientX) / 2,
y: (touch1.clientY + touch2.clientY) / 2
};
}
};
// Image Loading and Management
async function loadImage(url, retryCount = 0) {
const cachedUrl = imageCache.get(url);
if (cachedUrl) return cachedUrl;
const maxRetries = 3;
try {
if (retryCount >= maxRetries) {
throw new Error('Max retries exceeded');
}
// Try different CORS proxies
for (const proxy of CONFIG.CORS_PROXIES) {
try {
const proxiedUrl = proxy + encodeURIComponent(url);
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), CONFIG.PRELOAD.TIMEOUT);
const response = await fetch(proxiedUrl, {
method: 'HEAD',
signal: controller.signal
});
clearTimeout(timeoutId);
if (response.ok) {
imageCache.set(url, proxiedUrl);
return proxiedUrl;
}
} catch (e) {
continue;
}
}
// If all proxies fail, retry with exponential backoff
const backoffDelay = Math.pow(2, retryCount) * 1000;
await new Promise(resolve => setTimeout(resolve, backoffDelay));
return loadImage(url, retryCount + 1);
} catch (error) {
console.error(\`Failed to load image: \${url}\`, error);
throw error;
}
}
// Image Display and Navigation
async function showImage(index, useTransition = true) {
if (index < 0 || index >= imageUrls.length) return;
state.currentIndex = index;
updateThumbnails();
resetZoomAndPan();
elements.loader.style.display = 'block';
elements.errorMessage.style.display = 'none';
elements.mainImage.classList.remove('visible');
try {
const url = imageUrls[index];
const imgUrl = await loadImage(url);
await new Promise((resolve, reject) => {
const img = new Image();
img.onload = resolve;
img.onerror = reject;
img.src = imgUrl;
});
elements.mainImage.src = imgUrl;
if (useTransition) {
requestAnimationFrame(() => {
elements.mainImage.classList.add('visible');
});
} else {
elements.mainImage.classList.add('visible');
}
preloadAdjacentImages();
updateNavButtons();
} catch (error) {
showError('Failed to load image. Please try again.');
} finally {
elements.loader.style.display = 'none';
}
}
// Handle index changes
function handleIndexChange(oldValue, newValue) {
showImage(newValue);
}
// Handle zoom changes
function handleZoomChange(value) {
updateTransform();
}
// Update slideshow UI based on state
function updateSlideshowUI(isSlideshow) {
elements.playPauseBtn.querySelector('.icon').textContent = isSlideshow ? '⏸' : '▶';
elements.playPauseBtn.querySelector('.text').textContent = isSlideshow ? 'Pause' : 'Slideshow';
}
// Error Handling
function showError(message) {
elements.errorMessage.textContent = message;
elements.errorMessage.style.display = 'block';
elements.loader.style.display = 'none';
}
// Navigation and Controls
function updateNavButtons() {
elements.prevBtn.style.display = state.currentIndex > 0 ? 'flex' : 'none';
elements.nextBtn.style.display = state.currentIndex < imageUrls.length - 1 ? 'flex' : 'none';
}
// Zoom and Pan Controls
function setZoom(newZoom, centerX = null, centerY = null) {
const oldZoom = state.zoom;
state.zoom = utils.clamp(newZoom, CONFIG.ZOOM.MIN, CONFIG.ZOOM.MAX);
if (centerX !== null && centerY !== null) {
// Adjust pan to keep the zoom centered on the mouse position
const rect = elements.mainImage.getBoundingClientRect();
const offsetX = (centerX - rect.left) / rect.width;
const offsetY = (centerY - rect.top) / rect.height;
state.translateX = (state.translateX * state.zoom / oldZoom) +
(1 - state.zoom / oldZoom) * offsetX * rect.width;
state.translateY = (state.translateY * state.zoom / oldZoom) +
(1 - state.zoom / oldZoom) * offsetY * rect.height;
}
updateTransform();
}
function updateTransform() {
elements.mainImage.style.transform =
\`scale(\${state.zoom}) translate(\${state.translateX}px, \${state.translateY}px)\`;
}
function resetZoomAndPan() {
state.zoom = 1;
state.translateX = 0;
state.translateY = 0;
updateTransform();
}
// Preload adjacent images
function preloadAdjacentImages() {
const start = Math.max(state.currentIndex - CONFIG.PRELOAD.ADJACENT, 0);
const end = Math.min(state.currentIndex + CONFIG.PRELOAD.ADJACENT, imageUrls.length - 1);
for (let i = start; i <= end; i++) {
loadImage(imageUrls[i]).catch(() => {});
}
}
// Update Thumbnails
function updateThumbnails() {
const thumbnails = elements.thumbnails.querySelectorAll('.thumbnail');
thumbnails.forEach((thumb, index) => {
thumb.classList.toggle('active', index === state.currentIndex);
});
}
// Initialize Thumbnails with Lazy Loading
function initThumbnails() {
imageUrls.forEach((url, index) => {
const thumb = document.createElement('img');
thumb.dataset.src = url;
thumb.classList.add('thumbnail');
thumb.setAttribute('alt', \`Thumbnail \${index + 1}\`);
thumb.setAttribute('loading', 'lazy');
thumb.addEventListener('click', () => {
showImage(index);
});
// Lazy-load thumbnails
const observer = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
thumb.src = thumb.dataset.src;
observer.unobserve(thumb);
}
});
}, { root: elements.thumbnails, threshold: 0.1 });
observer.observe(thumb);
elements.thumbnails.appendChild(thumb);
});
}
// Initialize Event Listeners
function bindEvents() {
// Play/Pause Slideshow
elements.playPauseBtn.addEventListener('click', toggleSlideshow);
// Download Image
elements.downloadBtn.addEventListener('click', downloadCurrentImage);
// Zoom In
elements.zoomInBtn.addEventListener('click', () => {
setZoom(state.zoom + CONFIG.ZOOM.STEP);
});
// Zoom Out
elements.zoomOutBtn.addEventListener('click', () => {
setZoom(state.zoom - CONFIG.ZOOM.STEP);
});
// Reset Zoom and Pan
elements.resetBtn.addEventListener('click', resetZoomAndPan);
// Fullscreen
elements.fullscreenBtn.addEventListener('click', toggleFullscreen);
// Next Image
elements.nextBtn.addEventListener('click', () => {
if (state.currentIndex < imageUrls.length - 1) {
showImage(state.currentIndex + 1);
}
});
// Previous Image
elements.prevBtn.addEventListener('click', () => {
if (state.currentIndex > 0) {
showImage(state.currentIndex - 1);
}
});
// Keyboard Events
window.addEventListener('keydown', handleKeyboardEvents);
// Mouse Events for Panning
elements.mainImage.addEventListener('mousedown', startPan);
window.addEventListener('mousemove', pan);
window.addEventListener('mouseup', endPan);
// Touch Events
elements.mainImage.addEventListener('touchstart', handleTouchStart, { passive: false });
elements.mainImage.addEventListener('touchmove', handleTouchMove, { passive: false });
elements.mainImage.addEventListener('touchend', handleTouchEnd);
// Prevent image dragging
elements.mainImage.addEventListener('dragstart', (e) => e.preventDefault());
}
// Toggle Fullscreen
function toggleFullscreen() {
if (!state.isFullscreen) {
if (document.documentElement.requestFullscreen) {
document.documentElement.requestFullscreen().catch(() => {});
} else if (document.documentElement.webkitRequestFullscreen) { /* Safari */
document.documentElement.webkitRequestFullscreen();
} else if (document.documentElement.msRequestFullscreen) { /* IE11 */
document.documentElement.msRequestFullscreen();
}
state.isFullscreen = true;
elements.fullscreenBtn.textContent = '🡽';
} else {
if (document.fullscreenElement || document.webkitFullscreenElement || document.msFullscreenElement) {
if (document.exitFullscreen) {
document.exitFullscreen().catch(() => {});
} else if (document.webkitExitFullscreen) { /* Safari */
document.webkitExitFullscreen();
} else if (document.msExitFullscreen) { /* IE11 */
document.msExitFullscreen();
}
}
state.isFullscreen = false;
elements.fullscreenBtn.textContent = '⛶';
}
}
// Toggle Slideshow
function toggleSlideshow() {
if (state.isSlideshow) {
clearInterval(state.slideshowInterval);
state.slideshowInterval = null;
state.isSlideshow = false;
updateSlideshowUI(false);
} else {
state.slideshowInterval = setInterval(() => {
if (state.currentIndex < imageUrls.length - 1) {
showImage(state.currentIndex + 1);
} else {
showImage(0);
}
}, CONFIG.SLIDESHOW.DEFAULT_INTERVAL * 1000);
state.isSlideshow = true;
updateSlideshowUI(true);
}
}
// Download Current Image
function downloadCurrentImage() {
const url = elements.mainImage.src;
if (!url) {
alert('No image to download.');
return;
}
const link = document.createElement('a');
link.href = url;
link.download = \`image_\${state.currentIndex + 1}.jpg\`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
// Handle Keyboard Events
function handleKeyboardEvents(e) {
switch(e.key) {
case 'ArrowLeft':
if (state.currentIndex > 0) {
showImage(state.currentIndex - 1);
}
break;
case 'ArrowRight':
if (state.currentIndex < imageUrls.length - 1) {
showImage(state.currentIndex + 1);
}
break;
case '+':
case '=':
setZoom(state.zoom + CONFIG.ZOOM.STEP);
break;
case '-':
setZoom(state.zoom - CONFIG.ZOOM.STEP);
break;
case '0':
resetZoomAndPan();
break;
case 'Escape':
if (state.isFullscreen) {
toggleFullscreen();
}
break;
}
}
// Panning Functions
function startPan(e) {
if (state.zoom <= 1) return;
state.isPanning = true;
state.startX = e.clientX;
state.startY = e.clientY;
state.initialX = state.translateX;
state.initialY = state.translateY;
elements.mainImage.classList.add('panning');
}
function pan(e) {
if (!state.isPanning) return;
const dx = e.clientX - state.startX;
const dy = e.clientY - state.startY;
state.translateX = state.initialX + dx;
state.translateY = state.initialY + dy;
updateTransform();
}
function endPan() {
if (state.isPanning) {
state.isPanning = false;
elements.mainImage.classList.remove('panning');
}
}
// Touch Event Handlers
let initialTouchDistance = 0;
let initialZoom = 1;
function handleTouchStart(e) {
if (e.touches.length === 2) {
initialTouchDistance = utils.getDistance(e.touches[0], e.touches[1]);
initialZoom = state.zoom;
}
}
function handleTouchMove(e) {
if (e.touches.length === 2) {
const currentDistance = utils.getDistance(e.touches[0], e.touches[1]);
const scale = currentDistance / initialTouchDistance;
setZoom(initialZoom * scale);
e.preventDefault();
} else if (e.touches.length === 1 && state.zoom > 1) {
// Handle panning with single touch
const touch = e.touches[0];
const dx = touch.clientX - state.startX;
const dy = touch.clientY - state.startY;
state.translateX = state.initialX + dx;
state.translateY = state.initialY + dy;
updateTransform();
}
}
function handleTouchEnd(e) {
if (e.touches.length < 2) {
initialTouchDistance = 0;
initialZoom = state.zoom;
}
}
// Initialize the viewer
function initViewer() {
initThumbnails();
showImage(state.currentIndex, false);
bindEvents();
}
// Initialize Viewer on Load
window.addEventListener('load', initViewer);
// Cleanup on Close
window.addEventListener('beforeunload', () => {
if (window.opener && !window.opener.closed) {
window.opener.ultimateImageViewerInstance = null;
}
});
})();
</script>
</body>
</html>
`;
}
// Start the viewer initialization
initializeViewer();
})();
3. Minify the Bookmarklet Script
Given the complexity and length of the script, it's essential to minify it to reduce size. Here's how you can do it:
-
Use a JavaScript Minifier: Tools like UglifyJS or online services like Javascript Minifier can compress your script.
-
Encode the Script for Bookmarklet Use: Replace special characters and wrap the script in a javascript: URL.
Example:
javascript:(function(){/* Minified JavaScript code here */})();
Note: Given the extensive size and complexity of your script, the minified version might still be too long for some browsers. Therefore, hosting the viewer externally is highly recommended.
4. Implement the External Viewer Approach
By hosting the viewer's HTML and JavaScript externally, you can simplify the bookmarklet. Here's how:
-
Host viewer.html: Upload your viewer.html (the content generated by generateViewerHTML(imageUrls)) to a public URL, e.g., https://yourdomain.com/viewer.html.
-
Modify the Bookmarklet to Pass Image URLs:
javascript:(function(){
'use strict';
// Function to sanitize URLs
function sanitizeURL(url) {
try {
const sanitized = new URL(url, window.location.href);
if (!['http:', 'https:'].includes(sanitized.protocol)) return null;
// Exclude dangerous file types
if (/\.(svg|svgz|html|htm|php|asp|aspx|jsp|cgi)$/i.test(sanitized.pathname)) return null;
// Check for common image extensions
if (!/\.(jpe?g|png|gif|webp|avif|bmp|ico)$/i.test(sanitized.pathname)) {
// Additional check for images without extensions
if (!/^data:image\/(jpeg|png|gif|webp|avif|bmp|ico)/i.test(url)) return null;
}
sanitized.hash = '';
sanitized.search = '';
return sanitized.href;
} catch (e) {
return null;
}
}
// Gather image sources
function gatherImageSources() {
const sources = new Set();
// Extract from <img> tags
document.querySelectorAll('img').forEach(img => {
['src', 'data-src', 'data-large', 'data-original', 'data-lazy', 'data-lazy-src'].forEach(attr => {
const src = img.getAttribute(attr);
if (src) {
const sanitized = sanitizeURL(src);
if (sanitized) sources.add(sanitized);
}
});
// Check if image is wrapped in a link
const parentLink = img.closest('a[href]');
if (parentLink) {
const href = parentLink.getAttribute('href');
if (href) {
const sanitizedLink = sanitizeURL(href);
if (sanitizedLink) sources.add(sanitizedLink);
}
}
});
// Extract from CSS background images
document.querySelectorAll('*').forEach(el => {
const bg = window.getComputedStyle(el).backgroundImage;
if (bg && bg !== 'none') {
const matches = bg.match(/url\(["']?(.+?)["']?\)/);
if (matches && matches[1]) {
const url = matches[1];
const sanitized = sanitizeURL(url);
if (sanitized) sources.add(sanitized);
}
}
});
// Extract from <source> tags (e.g., within <picture> elements)
document.querySelectorAll('source').forEach(source => {
['srcset', 'data-srcset'].forEach(attr => {
const srcset = source.getAttribute(attr);
if (srcset) {
srcset.split(',').forEach(part => {
const [url] = part.trim().split(' ');
const sanitized = sanitizeURL(url);
if (sanitized) sources.add(sanitized);
});
}
});
});
// Convert to array and limit
return Array.from(sources).slice(0, 200); // Adjust MAX_IMAGES as needed
}
const imageUrls = gatherImageSources();
if (imageUrls.length === 0) {
alert('No images found on this page.');
return;
}
// Encode image URLs as JSON and URI component
const encodedImageUrls = encodeURIComponent(JSON.stringify(imageUrls));
// Open viewer window with image URLs as query parameter
const viewerUrl = 'https://yourdomain.com/viewer.html?images=' + encodedImageUrls;
const viewer = window.open(viewerUrl, '_blank', 'width=1200,height=800,scrollbars=no,resizable=yes');
if (!viewer) {
alert('Unable to open image viewer. Please allow popups for this website.');
return;
}
window.ultimateImageViewerInstance = viewer;
// Add unload handler to reset the instance
window.addEventListener('unload', () => {
window.ultimateImageViewerInstance = null;
});
})();
Explanation:
- Sanitize URLs: Ensures only valid and safe image URLs are collected.
- Gather Image Sources: Extracts image URLs from various sources (
<img> tags, CSS backgrounds, <source> tags).
- Encode Image URLs: Converts the array of image URLs into a JSON string and then URI component for safe transmission.
- Open Viewer: Opens the externally hosted
viewer.html with the image URLs passed as a query parameter.
- Handle Multiple Instances: Prevents multiple instances by focusing the existing viewer if already open.
5. Update the Viewer Script to Receive Image URLs
In your externally hosted viewer.html, update the script to parse the image URLs from the query parameter:
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Your styles and metadata here -->
</head>
<body>
<!-- Your HTML structure here -->
<script>
(function() {
'use strict';
// Configuration
const CONFIG = {
// Your CONFIG settings here
};
// Parse image URLs from query parameter
const params = new URLSearchParams(window.location.search);
const imageUrlsParam = params.get('images');
let imageUrls = [];
if (imageUrlsParam) {
try {
imageUrls = JSON.parse(decodeURIComponent(imageUrlsParam));
} catch (e) {
console.error('Invalid image URLs:', e);
}
}
if (imageUrls.length === 0) {
alert('No valid images to display.');
window.close();
return;
}
// Rest of your viewer script here
// Ensure that any reference to 'window.opener.ultimateImageViewerInstance' is correctly handled
window.addEventListener('beforeunload', () => {
if (window.opener && !window.opener.closed) {
window.opener.ultimateImageViewerInstance = null;
}
});
// Continue with initializing the viewer using imageUrls
})();
</script>
</body>
</html>
Key Points:
- Parsing Image URLs: The viewer parses the
images query parameter to retrieve the image URLs.
- Handling Errors: If no valid images are found, the viewer alerts the user and closes.
- Cleanup: On unload, it resets the
ultimateImageViewerInstance in the opener window to allow new instances.
6. Final Bookmarklet Code
After implementing the external viewer approach, your bookmarklet will be significantly shorter and more maintainable. Here's the final bookmarklet code:
javascript:(function(){
'use strict';
function sanitizeURL(url) {
try {
const sanitized = new URL(url, window.location.href);
if (!['http:', 'https:'].includes(sanitized.protocol)) return null;
if (/\.(svg|svgz|html|htm|php|asp|aspx|jsp|cgi)$/i.test(sanitized.pathname)) return null;
if (!/\.(jpe?g|png|gif|webp|avif|bmp|ico)$/i.test(sanitized.pathname)) {
if (!/^data:image\/(jpeg|png|gif|webp|avif|bmp|ico)/i.test(url)) return null;
}
sanitized.hash = '';
sanitized.search = '';
return sanitized.href;
} catch (e) {
return null;
}
}
function gatherImageSources() {
const sources = new Set();
document.querySelectorAll('img').forEach(img => {
['src', 'data-src', 'data-large', 'data-original', 'data-lazy', 'data-lazy-src'].forEach(attr => {
const src = img.getAttribute(attr);
if (src) {
const sanitized = sanitizeURL(src);
if (sanitized) sources.add(sanitized);
}
});
const parentLink = img.closest('a[href]');
if (parentLink) {
const href = parentLink.getAttribute('href');
if (href) {
const sanitizedLink = sanitizeURL(href);
if (sanitizedLink) sources.add(sanitizedLink);
}
}
});
document.querySelectorAll('*').forEach(el => {
const bg = window.getComputedStyle(el).backgroundImage;
if (bg && bg !== 'none') {
const matches = bg.match(/url\(["']?(.+?)["']?\)/);
if (matches && matches[1]) {
const url = matches[1];
const sanitized = sanitizeURL(url);
if (sanitized) sources.add(sanitized);
}
}
});
document.querySelectorAll('source').forEach(source => {
['srcset', 'data-srcset'].forEach(attr => {
const srcset = source.getAttribute(attr);
if (srcset) {
srcset.split(',').forEach(part => {
const [url] = part.trim().split(' ');
const sanitized = sanitizeURL(url);
if (sanitized) sources.add(sanitized);
});
}
});
});
return Array.from(sources).slice(0, 200); // Adjust MAX_IMAGES as needed
}
const imageUrls = gatherImageSources();
if (imageUrls.length === 0) {
alert('No images found on this page.');
return;
}
const encodedImageUrls = encodeURIComponent(JSON.stringify(imageUrls));
const viewerUrl = 'https://yourdomain.com/viewer.html?images=' + encodedImageUrls;
const viewer = window.open(viewerUrl, '_blank', 'width=1200,height=800,scrollbars=no,resizable=yes');
if (!viewer) {
alert('Unable to open image viewer. Please allow popups for this website.');
return;
}
window.ultimateImageViewerInstance = viewer;
window.addEventListener('beforeunload', () => {
if (window.ultimateImageViewerInstance && !window.ultimateImageViewerInstance.closed) {
window.ultimateImageViewerInstance = null;
}
});
})();
Usage Instructions:
-
Replace Viewer URL: Update 'https://yourdomain.com/viewer.html' with the actual URL where you've hosted your viewer.html.
-
Create Bookmarklet:
- Copy the entire script above.
- URL-encode it if necessary (most browsers handle it correctly as is).
- Create a new bookmark in your browser and set the URL to the copied script.
-
Usage: Navigate to any webpage, click the bookmarklet, and it will open the externally hosted image viewer with all extracted images.
Advantages of This Approach
-
Bypass URL Length Limitations: Hosting the viewer externally avoids the bookmarklet exceeding browser URL length limits.
-
Maintainability: Updating the viewer's features or styles becomes simpler since it's hosted separately.
-
Performance: Loading an external resource is generally faster and more reliable, especially for large scripts.
Alternative: Single Bookmarklet (If Absolutely Necessary)
If you prefer to keep the entire functionality within a single bookmarklet, you can attempt to minify your script. However, be aware of the limitations:
-
Potentially Incomplete Features: Due to size constraints, some features might need to be simplified.
-
Browser Compatibility: Some browsers might not handle very long bookmarklets well.
Here's an extremely simplified version of your original script suitable for a bookmarklet. Note: This version lacks many advanced features due to size constraints.
javascript:(function(){
'use strict';
if(window.ultimateImageViewerInstance){
window.ultimateImageViewerInstance.focus();
return;
}
function sanitizeURL(url){
try{
const sanitized = new URL(url, window.location.href);
if(!['http:', 'https:'].includes(sanitized.protocol)) return null;
if(/\.(svg|svgz|html|htm|php|asp|aspx|jsp|cgi)$/i.test(sanitized.pathname)) return null;
if(!/\.(jpe?g|png|gif|webp|avif|bmp|ico)$/i.test(sanitized.pathname)){
if(!/^data:image\/(jpeg|png|gif|webp|avif|bmp|ico)/i.test(url)) return null;
}
sanitized.hash = '';
sanitized.search = '';
return sanitized.href;
} catch(e){
return null;
}
}
function gatherImageSources(){
const sources = new Set();
document.querySelectorAll('img').forEach(img=>{
['src','data-src','data-large','data-original','data-lazy','data-lazy-src'].forEach(attr=>{
const src = img.getAttribute(attr);
if(src){
const sanitized = sanitizeURL(src);
if(sanitized)sources.add(sanitized);
}
});
const parentLink = img.closest('a[href]');
if(parentLink){
const href = parentLink.getAttribute('href');
if(href){
const sanitizedLink = sanitizeURL(href);
if(sanitizedLink)sources.add(sanitizedLink);
}
}
});
document.querySelectorAll('*').forEach(el=>{
const bg = window.getComputedStyle(el).backgroundImage;
if(bg && bg!=='none'){
const matches = bg.match(/url\(["']?(.+?)["']?\)/);
if(matches && matches[1]){
const url = matches[1];
const sanitized = sanitizeURL(url);
if(sanitized)sources.add(sanitized);
}
}
});
document.querySelectorAll('source').forEach(source=>{
['srcset','data-srcset'].forEach(attr=>{
const srcset = source.getAttribute(attr);
if(srcset){
srcset.split(',').forEach(part=>{
const [url] = part.trim().split(' ');
const sanitized = sanitizeURL(url);
if(sanitized)sources.add(sanitized);
});
}
});
});
return Array.from(sources).slice(0,200);
}
async function initializeViewer(){
const imageUrls = gatherImageSources();
if(imageUrls.length === 0){
alert('No images found on this page.');
return;
}
const width = Math.min(1200, window.screen.availWidth * 0.9);
const height = Math.min(800, window.screen.availHeight * 0.9);
const left = (window.screen.availWidth - width)/2;
const top = (window.screen.availHeight - height)/2;
const viewer = window.open('', '_blank', \`width=\${width},height=\${height},left=\${left},top=\${top},scrollbars=no,resizable=yes\`);
if(!viewer){
alert('Unable to open image viewer. Please allow popups for this website.');
return;
}
window.ultimateImageViewerInstance = viewer;
const viewerHTML = \`
<!DOCTYPE html>
<html lang="en">
<head><title>Image Viewer</title></head>
<body style="background-color:black; color:white; display:flex; flex-direction:column; align-items:center; justify-content:center; height:100%;">
<img src="\${imageUrls[0]}" id="mainImage" style="max-width:100%; max-height:80%;">
<div style="margin-top:10px;">
<button onclick="window.opener.showNextImage()">Next</button>
<button onclick="window.opener.showPrevImage()">Prev</button>
</div>
<script>
window.opener.showNextImage = function(){
const img = document.getElementById('mainImage');
let current = imageUrls.indexOf(img.src);
current = (current + 1) % imageUrls.length;
img.src = imageUrls[current];
};
window.opener.showPrevImage = function(){
const img = document.getElementById('mainImage');
let current = imageUrls.indexOf(img.src);
current = (current - 1 + imageUrls.length) % imageUrls.length;
img.src = imageUrls[current];
};
window.addEventListener('beforeunload', () => {
if(window.opener && !window.opener.closed){
window.opener.ultimateImageViewerInstance = null;
}
});
</script>
</body>
</html>
\`;
viewer.document.open();
viewer.document.write(viewerHTML);
viewer.document.close();
}
initializeViewer();
})();
Note: This simplified version includes only basic functionalities (image display, next/prev buttons) to fit within typical bookmarklet size limits. Extending it with advanced features would require transitioning to the external viewer approach.
Conclusion
Creating a fully functional and feature-rich bookmarklet involves carefully managing script size and complexity. By hosting the viewer externally and keeping the bookmarklet concise, you ensure better performance, maintainability, and user experience. Implement the external viewer approach as outlined above for a robust solution.
If you encounter specific issues or need further assistance with particular functionalities, feel free to ask!