diff --git a/.kiro/specs/copy-to-clipboard-toggle/design.md b/.kiro/specs/copy-to-clipboard-toggle/design.md new file mode 100644 index 0000000..7d4af9a --- /dev/null +++ b/.kiro/specs/copy-to-clipboard-toggle/design.md @@ -0,0 +1,165 @@ +# Design Document + +## Overview + +The copy to clipboard toggle feature will be implemented as an additional setting in the extension popup, similar to the existing background color selector. The feature will use the modern Clipboard API with appropriate fallbacks for older browsers. The implementation will integrate seamlessly with the existing screenshot capture workflow, adding clipboard functionality without disrupting the current download behavior. + +## Architecture + +The feature will be implemented across three main components: + +1. **Popup UI Enhancement**: Add toggle control and persistence logic +2. **Content Script Integration**: Modify screenshot capture to include clipboard operations +3. **Storage Management**: Extend existing preference storage system + +The clipboard functionality will be implemented as an optional enhancement to the existing screenshot workflow, ensuring backward compatibility and graceful degradation. + +## Components and Interfaces + +### Popup Interface (`popup.html` & `popup.js`) + +**New UI Elements:** +- Toggle switch control for "Copy to Clipboard" option +- Positioned between background selector and start button +- Consistent styling with existing controls + +**Storage Integration:** +- Extend existing `chrome.storage.sync` usage to include `copyToClipboard` preference +- Default value: `true` (enabled by default for better user experience) +- Load and save preferences alongside existing background preference + +**Message Passing:** +- Include `copyToClipboard` setting in the `startSelector` message to content script +- No changes needed to existing message structure, just additional property + +### Content Script Enhancement (`content.js`) + +**ScreenshotSelector Class Modifications:** +- Add `copyToClipboard` property to constructor +- Modify `init()` method to accept and store clipboard preference +- Enhance `captureElement()` method to include clipboard operations + +**Clipboard Implementation:** +```javascript +async copyCanvasToClipboard(canvas) { + try { + // Convert canvas to blob + const blob = await new Promise(resolve => + canvas.toBlob(resolve, 'image/png') + ); + + // Use Clipboard API + await navigator.clipboard.write([ + new ClipboardItem({ 'image/png': blob }) + ]); + + return { success: true }; + } catch (error) { + return { success: false, error: error.message }; + } +} +``` + +**Error Handling:** +- Graceful fallback when Clipboard API is unavailable +- User-friendly error messages for clipboard failures +- Ensure screenshot download continues even if clipboard fails + +### User Feedback System + +**Success States:** +- "Screenshot saved and copied to clipboard!" - when both operations succeed +- "Screenshot saved! (Clipboard copy failed: [reason])" - when download succeeds but clipboard fails + +**Loading States:** +- Update existing loading message to indicate clipboard operation when enabled +- "Capturing screenshot and preparing clipboard..." vs "Capturing screenshot..." + +## Data Models + +### Settings Storage Schema +```javascript +{ + backgroundPreference: 'black' | 'transparent' | 'white', + copyToClipboard: boolean // New addition +} +``` + +### Message Interface Extension +```javascript +// startSelector message +{ + action: 'startSelector', + background: string, + copyToClipboard: boolean // New addition +} +``` + +## Error Handling + +### Clipboard API Availability +- Check for `navigator.clipboard` and `ClipboardItem` support +- Provide clear error messages when API is unavailable +- Continue with download-only functionality as fallback + +### Permission Handling +- Clipboard write operations may require user gesture +- Handle permission denied scenarios gracefully +- Provide user guidance for enabling clipboard permissions if needed + +### Browser Compatibility +- Primary support: Chrome/Edge 76+, Firefox 87+, Safari 13.1+ +- Fallback behavior for older browsers: disable clipboard feature with notification +- No impact on core screenshot functionality + +## Testing Strategy + +### Unit Testing Approach +- Mock Clipboard API for testing clipboard operations +- Test preference storage and retrieval +- Verify message passing between popup and content script +- Test error handling scenarios + +### Integration Testing +- Test complete workflow: toggle setting → capture screenshot → verify clipboard content +- Test with different background settings and clipboard combinations +- Verify graceful degradation when Clipboard API unavailable + +### Browser Compatibility Testing +- Test across Chrome, Firefox, Safari, Edge +- Verify behavior on older browser versions +- Test permission scenarios and user gesture requirements + +### User Experience Testing +- Verify toggle state persistence across browser sessions +- Test visual feedback for success/error states +- Confirm tooltip and help text clarity + +## Implementation Considerations + +### Performance Impact +- Clipboard operations are asynchronous and won't block screenshot download +- Canvas-to-blob conversion adds minimal overhead +- No impact on screenshot capture performance + +### Security Considerations +- Clipboard API requires secure context (HTTPS) +- User gesture requirement for clipboard write operations +- No sensitive data exposure through clipboard operations + +### Accessibility +- Toggle control will include proper ARIA labels +- Keyboard navigation support for toggle control +- Screen reader compatible success/error messages + +## Browser API Dependencies + +### Required APIs +- `navigator.clipboard.write()` - Modern clipboard API +- `ClipboardItem` constructor - For image data handling +- `canvas.toBlob()` - Convert canvas to blob format + +### Fallback Strategy +- Detect API availability before attempting clipboard operations +- Provide clear user feedback when clipboard features unavailable +- Maintain full functionality for screenshot download regardless of clipboard support \ No newline at end of file diff --git a/.kiro/specs/copy-to-clipboard-toggle/requirements.md b/.kiro/specs/copy-to-clipboard-toggle/requirements.md new file mode 100644 index 0000000..2553626 --- /dev/null +++ b/.kiro/specs/copy-to-clipboard-toggle/requirements.md @@ -0,0 +1,51 @@ +# Requirements Document + +## Introduction + +This feature adds a copy to clipboard toggle option to the Full Screenshot Selector extension, allowing users to choose whether captured screenshots should be automatically copied to the clipboard in addition to being downloaded as files. This provides users with more flexibility in how they handle their screenshots, enabling quick pasting into other applications without needing to locate and open the downloaded file. + +## Requirements + +### Requirement 1 + +**User Story:** As a user of the screenshot extension, I want to toggle whether screenshots are copied to clipboard, so that I can quickly paste them into other applications without downloading files. + +#### Acceptance Criteria + +1. WHEN the popup is opened THEN the system SHALL display a toggle control for "Copy to Clipboard" +2. WHEN the user toggles the copy to clipboard option THEN the system SHALL save this preference to browser storage +3. WHEN the extension is reopened THEN the system SHALL restore the previously saved copy to clipboard preference +4. WHEN a screenshot is captured AND copy to clipboard is enabled THEN the system SHALL copy the image data to the clipboard +5. WHEN a screenshot is captured AND copy to clipboard is enabled THEN the system SHALL still download the file as before (both actions occur) + +### Requirement 2 + +**User Story:** As a user, I want the copy to clipboard feature to work reliably across different browsers, so that I can depend on this functionality regardless of my browser choice. + +#### Acceptance Criteria + +1. WHEN copy to clipboard is enabled THEN the system SHALL use the Clipboard API if available +2. IF the Clipboard API is not available THEN the system SHALL provide appropriate fallback behavior +3. WHEN clipboard copying fails THEN the system SHALL display an error message to the user +4. WHEN clipboard copying succeeds THEN the system SHALL display a success confirmation + +### Requirement 3 + +**User Story:** As a user, I want clear visual feedback about the copy to clipboard feature, so that I understand when it's enabled and when clipboard operations succeed or fail. + +#### Acceptance Criteria + +1. WHEN the copy to clipboard toggle is enabled THEN the system SHALL display visual indication of the enabled state +2. WHEN a screenshot is captured with clipboard copying enabled THEN the system SHALL show a success message indicating both download and clipboard copy +3. WHEN clipboard copying fails THEN the system SHALL show an error message while still confirming the download succeeded +4. WHEN hovering over the copy to clipboard toggle THEN the system SHALL display helpful tooltip text + +### Requirement 4 + +**User Story:** As a user, I want the copy to clipboard feature to handle different image formats appropriately, so that the clipboard content works well with various applications. + +#### Acceptance Criteria + +1. WHEN copying to clipboard THEN the system SHALL copy the image in PNG format +2. WHEN copying to clipboard THEN the system SHALL preserve the same image quality as the downloaded file +3. WHEN copying to clipboard THEN the system SHALL handle transparency settings according to the background preference \ No newline at end of file diff --git a/.kiro/specs/copy-to-clipboard-toggle/tasks.md b/.kiro/specs/copy-to-clipboard-toggle/tasks.md new file mode 100644 index 0000000..25d7b74 --- /dev/null +++ b/.kiro/specs/copy-to-clipboard-toggle/tasks.md @@ -0,0 +1,64 @@ +# Implementation Plan + +- [x] 1. Add copy to clipboard toggle UI to popup + - Add HTML toggle control between background selector and start button in popup.html + - Style the toggle control to match existing UI design patterns + - Include proper ARIA labels and accessibility attributes for the toggle + - _Requirements: 1.1, 3.1, 3.4_ + +- [x] 2. Implement clipboard preference storage in popup + - Extend existing storage logic in popup.js to handle copyToClipboard preference + - Set default value to true for better user experience + - Load saved clipboard preference on popup initialization + - Save clipboard preference changes to chrome.storage.sync + - _Requirements: 1.2, 1.3_ + +- [x] 3. Update message passing to include clipboard setting + - Modify startSelector message in popup.js to include copyToClipboard property + - Update content script message handler to receive and store clipboard preference + - Ensure backward compatibility with existing message structure + - _Requirements: 1.1, 1.4_ + +- [x] 4. Implement clipboard API functionality in content script + - Add copyCanvasToClipboard method to ScreenshotSelector class + - Implement canvas to blob conversion for PNG format + - Use navigator.clipboard.write() with ClipboardItem for image data + - Handle async clipboard operations with proper error catching + - _Requirements: 2.1, 4.1, 4.2, 4.3_ + +- [x] 5. Add clipboard API availability detection + - Create method to check for navigator.clipboard and ClipboardItem support + - Implement graceful fallback when Clipboard API is unavailable + - Provide user feedback when clipboard features are not supported + - _Requirements: 2.2_ + +- [x] 6. Integrate clipboard operations into screenshot capture workflow + - Modify captureElement method to include clipboard operations when enabled + - Ensure clipboard copying happens after successful canvas generation + - Maintain existing download functionality regardless of clipboard success/failure + - _Requirements: 1.4, 1.5_ + +- [x] 7. Implement comprehensive error handling for clipboard operations + - Handle clipboard write permission errors gracefully + - Provide specific error messages for different failure scenarios + - Ensure screenshot download continues even when clipboard operations fail + - _Requirements: 2.3_ + +- [x] 8. Update user feedback messages for clipboard operations + - Modify loading message to indicate clipboard preparation when enabled + - Update success message to confirm both download and clipboard copy + - Create error messages that distinguish between download and clipboard failures + - _Requirements: 2.4, 3.2, 3.3_ + +- [x] 9. Add tooltip and help text for clipboard toggle + - Implement tooltip showing clipboard feature explanation + - Add help text explaining clipboard functionality and browser requirements + - Ensure tooltip is accessible and keyboard navigable + - _Requirements: 3.4_ + +- [x] 10. Test clipboard functionality across different scenarios + - Write test cases for clipboard API availability detection + - Test clipboard operations with different background settings (transparent, black, white) + - Verify error handling when clipboard API is unavailable or permissions denied + - Test preference persistence across browser sessions + - _Requirements: 2.1, 2.2, 2.3, 4.3_ \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..5480842 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "kiroAgent.configureMCP": "Disabled" +} \ No newline at end of file diff --git a/content.js b/content.js index 45161dd..2b6e2cf 100644 --- a/content.js +++ b/content.js @@ -6,15 +6,17 @@ class ScreenshotSelector { this.overlay = null; this.style = null; this.background = 'black'; + this.copyToClipboard = true; // Default to true } - async init(background = 'black') { + async init(background = 'black', copyToClipboard = true) { if (this.isActive) { console.log('Screenshot selector already active'); return; } this.background = background; + this.copyToClipboard = copyToClipboard; this.isActive = true; this.createUI(); @@ -363,12 +365,23 @@ class ScreenshotSelector { async captureElement(element) { try { + // Determine loading message based on clipboard settings + let loadingMessage = 'Capturing screenshot...'; + if (this.copyToClipboard) { + const availability = this.checkClipboardAPIAvailability(); + if (availability.available) { + loadingMessage = 'Capturing screenshot and preparing for clipboard...'; + } else { + loadingMessage = 'Capturing screenshot... (Clipboard not available)'; + } + } + // Show loading state this.overlay.innerHTML = `
+ Press n or j to go to the next uncovered block, b, p or k for the previous block. +
+ +| 1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 +39 +40 +41 +42 +43 +44 +45 +46 +47 +48 +49 +50 +51 +52 +53 +54 +55 +56 +57 +58 +59 +60 +61 +62 +63 +64 +65 +66 +67 +68 +69 +70 +71 +72 +73 +74 +75 +76 +77 +78 +79 +80 +81 +82 +83 +84 +85 +86 +87 +88 +89 +90 +91 +92 +93 +94 +95 +96 +97 +98 +99 +100 +101 +102 +103 +104 +105 +106 +107 +108 +109 +110 +111 +112 +113 +114 +115 +116 +117 +118 +119 +120 +121 +122 +123 +124 +125 +126 +127 +128 +129 +130 +131 +132 +133 +134 +135 +136 +137 +138 +139 +140 +141 +142 +143 +144 +145 +146 +147 +148 +149 +150 +151 +152 +153 +154 +155 +156 +157 +158 +159 +160 +161 +162 +163 +164 +165 +166 +167 +168 +169 +170 +171 +172 +173 +174 +175 +176 +177 +178 +179 +180 +181 +182 +183 +184 +185 +186 +187 +188 +189 +190 +191 +192 +193 +194 +195 +196 +197 +198 +199 +200 +201 +202 +203 +204 +205 +206 +207 +208 +209 +210 +211 +212 +213 +214 +215 +216 +217 +218 +219 +220 +221 +222 +223 +224 +225 +226 +227 +228 +229 +230 +231 +232 +233 +234 +235 +236 +237 +238 +239 +240 +241 +242 +243 +244 +245 +246 +247 +248 +249 +250 +251 +252 +253 +254 +255 +256 +257 +258 +259 +260 +261 +262 +263 +264 +265 +266 +267 +268 +269 +270 +271 +272 +273 +274 +275 +276 +277 +278 +279 +280 +281 +282 +283 +284 +285 +286 +287 +288 +289 +290 +291 +292 +293 +294 +295 +296 +297 +298 +299 +300 +301 +302 +303 +304 +305 +306 +307 +308 +309 +310 +311 +312 +313 +314 +315 +316 +317 +318 +319 +320 +321 +322 +323 +324 +325 +326 +327 +328 +329 +330 +331 +332 +333 +334 +335 +336 +337 +338 +339 +340 +341 +342 +343 +344 +345 +346 +347 +348 +349 +350 +351 +352 +353 +354 +355 +356 +357 +358 +359 +360 +361 +362 +363 +364 +365 +366 +367 +368 +369 +370 +371 +372 +373 +374 +375 +376 +377 +378 +379 +380 +381 +382 +383 +384 +385 +386 +387 +388 +389 +390 +391 +392 +393 +394 +395 +396 +397 +398 +399 +400 +401 +402 +403 +404 +405 +406 +407 +408 +409 +410 +411 +412 +413 +414 +415 +416 +417 +418 +419 +420 +421 +422 +423 +424 +425 +426 +427 +428 +429 +430 +431 +432 +433 +434 +435 +436 +437 +438 +439 +440 +441 +442 +443 +444 +445 +446 +447 +448 +449 +450 +451 +452 +453 +454 +455 +456 +457 +458 +459 +460 +461 +462 +463 +464 +465 +466 +467 +468 +469 +470 +471 +472 +473 +474 +475 +476 +477 +478 +479 +480 +481 +482 +483 +484 +485 +486 +487 +488 +489 +490 +491 +492 +493 +494 +495 +496 +497 +498 +499 +500 +501 +502 +503 +504 +505 +506 +507 +508 +509 +510 +511 +512 +513 +514 +515 +516 +517 +518 +519 +520 +521 +522 +523 +524 +525 +526 +527 +528 +529 +530 +531 +532 +533 +534 +535 +536 +537 +538 +539 +540 +541 +542 +543 +544 +545 +546 +547 +548 +549 +550 +551 +552 +553 +554 +555 +556 +557 +558 +559 +560 +561 +562 +563 +564 +565 +566 +567 +568 +569 +570 +571 +572 +573 +574 +575 +576 +577 +578 +579 +580 +581 +582 +583 +584 +585 +586 +587 +588 +589 +590 +591 +592 +593 +594 +595 +596 +597 +598 +599 +600 +601 +602 +603 +604 +605 +606 +607 +608 +609 +610 +611 +612 +613 +614 +615 +616 +617 +618 +619 +620 +621 +622 +623 +624 +625 +626 +627 +628 +629 +630 +631 +632 +633 +634 +635 +636 +637 +638 +639 +640 +641 +642 +643 +644 +645 +646 +647 +648 +649 +650 +651 +652 +653 +654 +655 +656 +657 +658 +659 +660 +661 +662 +663 +664 +665 +666 +667 +668 +669 +670 +671 +672 +673 +674 +675 +676 +677 +678 +679 +680 +681 +682 +683 +684 +685 +686 +687 +688 +689 +690 +691 +692 +693 +694 +695 +696 +697 +698 +699 +700 +701 +702 +703 +704 +705 +706 +707 +708 +709 +710 +711 +712 +713 +714 +715 +716 +717 +718 +719 +720 +721 +722 +723 +724 +725 +726 +727 +728 +729 +730 +731 +732 +733 +734 +735 +736 +737 +738 +739 +740 +741 +742 +743 +744 +745 +746 +747 +748 +749 +750 +751 +752 +753 +754 +755 +756 +757 +758 +759 +760 +761 +762 +763 +764 +765 +766 +767 +768 +769 +770 +771 +772 +773 +774 +775 +776 +777 +778 +779 +780 +781 +782 +783 +784 +785 +786 +787 +788 +789 +790 +791 +792 +793 +794 +795 +796 +797 +798 +799 +800 +801 +802 +803 +804 +805 +806 +807 +808 +809 +810 +811 +812 +813 +814 +815 +816 +817 +818 +819 +820 +821 +822 +823 +824 +825 +826 +827 +828 +829 +830 +831 +832 +833 +834 +835 +836 +837 +838 +839 +840 +841 +842 +843 +844 +845 +846 +847 +848 +849 +850 +851 +852 +853 +854 +855 +856 +857 +858 +859 +860 +861 +862 +863 +864 +865 +866 +867 +868 +869 +870 +871 +872 +873 +874 +875 +876 +877 +878 +879 +880 +881 +882 +883 +884 +885 +886 +887 +888 +889 +890 +891 +892 +893 +894 +895 +896 +897 +898 +899 +900 +901 +902 +903 +904 +905 +906 +907 +908 +909 +910 +911 +912 +913 +914 +915 +916 +917 +918 +919 +920 +921 +922 +923 +924 +925 +926 +927 +928 +929 +930 +931 +932 +933 +934 +935 +936 +937 | + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + | // Content script for Full Screenshot Selector Chrome Extension
+class ScreenshotSelector {
+ constructor() {
+ this.isActive = false;
+ this.currentHighlight = null;
+ this.overlay = null;
+ this.style = null;
+ this.background = 'black';
+ this.copyToClipboard = true; // Default to true
+ }
+
+ async init(background = 'black', copyToClipboard = true) {
+ if (this.isActive) {
+ console.log('Screenshot selector already active');
+ return;
+ }
+
+ this.background = background;
+ this.copyToClipboard = copyToClipboard;
+ this.isActive = true;
+
+ this.createUI();
+ this.addEventListeners();
+ }
+
+ createUI() {
+ // Create overlay UI
+ this.overlay = document.createElement('div');
+ this.overlay.id = 'screenshot-selector-overlay';
+ this.overlay.innerHTML = `
+ <div style="position: fixed; top: 20px; left: 20px; background: rgba(0,0,0,0.9); color: white; padding: 12px 16px; border-radius: 8px; z-index: 2147483647; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; font-size: 14px; box-shadow: 0 4px 20px rgba(0,0,0,0.3); backdrop-filter: blur(10px);">
+ <div style="display: flex; align-items: center; gap: 10px;">
+ <span>📸</span>
+ <span>Hover over elements and click to capture</span>
+ <button id="screenshot-cancel" style="margin-left: 10px; padding: 4px 8px; background: #ff4757; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 12px;">ESC</button>
+ </div>
+ </div>
+ `;
+
+ // Add hover highlighting styles
+ this.style = document.createElement('style');
+ this.style.textContent = `
+ .screenshot-highlight {
+ outline: 3px solid #00d2ff !important;
+ outline-offset: 2px !important;
+ cursor: crosshair !important;
+ position: relative !important;
+ }
+ .screenshot-highlight::after {
+ content: '';
+ position: absolute;
+ top: -5px;
+ left: -5px;
+ right: -5px;
+ bottom: -5px;
+ background: rgba(0, 210, 255, 0.1) !important;
+ pointer-events: none !important;
+ z-index: 2147483646 !important;
+ }
+ .screenshot-scrollable-indicator {
+ position: absolute !important;
+ border: 2px dotted #ff6b6b !important;
+ background: rgba(255, 107, 107, 0.05) !important;
+ pointer-events: none !important;
+ z-index: 2147483645 !important;
+ }
+ #screenshot-selector-overlay * {
+ cursor: default !important;
+ }
+ `;
+
+ document.head.appendChild(this.style);
+ document.body.appendChild(this.overlay);
+
+ // Cancel button functionality
+ document.getElementById('screenshot-cancel').onclick = () => this.cleanup();
+ }
+
+ addEventListeners() {
+ this.handleMouseOver = this.handleMouseOver.bind(this);
+ this.handleClick = this.handleClick.bind(this);
+ this.handleKeyPress = this.handleKeyPress.bind(this);
+
+ document.addEventListener('mouseover', this.handleMouseOver);
+ document.addEventListener('click', this.handleClick, true);
+ document.addEventListener('keydown', this.handleKeyPress);
+ }
+
+ handleMouseOver(e) {
+ if (e.target.closest('#screenshot-selector-overlay')) return;
+
+ // Clean up previous highlights and indicators
+ if (this.currentHighlight) {
+ this.currentHighlight.classList.remove('screenshot-highlight');
+ this.removeScrollableIndicators();
+ }
+
+ this.currentHighlight = e.target;
+ e.target.classList.add('screenshot-highlight');
+
+ // Add scrollable content indicators
+ this.addScrollableIndicators(e.target);
+ }
+
+ handleClick(e) {
+ if (e.target.closest('#screenshot-selector-overlay')) return;
+ e.preventDefault();
+ e.stopPropagation();
+
+ const element = e.target;
+ this.captureElement(element);
+ }
+
+ handleKeyPress(e) {
+ if (e.key === 'Escape') {
+ this.cleanup();
+ }
+ }
+
+ addScrollableIndicators(element) {
+ const rect = element.getBoundingClientRect();
+ const hasVerticalScroll = element.scrollHeight > element.clientHeight;
+ const hasHorizontalScroll = element.scrollWidth > element.clientWidth;
+
+ if (!hasVerticalScroll && !hasHorizontalScroll) return;
+
+ // Calculate the full content dimensions
+ const fullHeight = element.scrollHeight;
+ const fullWidth = element.scrollWidth;
+ const visibleHeight = element.clientHeight;
+ const visibleWidth = element.clientWidth;
+
+ // Create indicator for full scrollable area
+ if (hasVerticalScroll || hasHorizontalScroll) {
+ const indicator = document.createElement('div');
+ indicator.className = 'screenshot-scrollable-indicator';
+ indicator.setAttribute('data-screenshot-indicator', 'true');
+
+ // Position it relative to the viewport
+ const style = {
+ left: `${rect.left}px`,
+ top: `${rect.top}px`,
+ width: hasHorizontalScroll ? `${fullWidth}px` : `${rect.width}px`,
+ height: hasVerticalScroll ? `${fullHeight}px` : `${rect.height}px`,
+ };
+
+ Object.assign(indicator.style, style);
+ document.body.appendChild(indicator);
+
+ // Add a label to show the full dimensions
+ const label = document.createElement('div');
+ label.setAttribute('data-screenshot-indicator', 'true');
+ label.style.cssText = `
+ position: fixed;
+ top: ${rect.top - 25}px;
+ left: ${rect.left}px;
+ background: rgba(255, 107, 107, 0.9);
+ color: white;
+ padding: 2px 6px;
+ border-radius: 3px;
+ font-size: 11px;
+ font-family: monospace;
+ z-index: 2147483647;
+ pointer-events: none;
+ `;
+
+ const scrollInfo = [];
+ if (hasVerticalScroll) scrollInfo.push(`H: ${fullHeight}px (visible: ${visibleHeight}px)`);
+ if (hasHorizontalScroll) scrollInfo.push(`W: ${fullWidth}px (visible: ${visibleWidth}px)`);
+ label.textContent = `Full content - ${scrollInfo.join(', ')}`;
+
+ document.body.appendChild(label);
+ }
+ }
+
+ removeScrollableIndicators() {
+ const indicators = document.querySelectorAll('[data-screenshot-indicator]');
+ indicators.forEach(indicator => indicator.remove());
+ }
+
+ // Helper method to generate a unique selector for an element
+ getElementSelector(element) {
+ // Escape helper for CSS identifiers (handles Tailwind classes like lg:pr-0)
+ const escapeIdent = (ident) => {
+ try {
+ if (window.CSS && typeof window.CSS.escape === 'function') {
+ return window.CSS.escape(ident);
+ }
+ } catch (_) {}
+ // Fallback: escape most punctuation characters
+ return String(ident).replace(/([ !"#$%&'()*+,./:;<=>?@[\\\]^`{|}~])/g, '\\$1');
+ };
+
+ if (element.id) {
+ return `#${escapeIdent(element.id)}`;
+ }
+
+ if (element.classList && element.classList.length) {
+ const classSelector = Array.from(element.classList)
+ .filter(Boolean)
+ .map(cls => `.${escapeIdent(cls)}`)
+ .join('');
+ if (classSelector) {
+ return `${element.tagName.toLowerCase()}${classSelector}`;
+ }
+ }
+
+ // Fallback to tag name and position
+ const siblings = Array.from(element.parentNode?.children || []);
+ const index = siblings.indexOf(element);
+ return `${element.tagName.toLowerCase()}:nth-child(${index + 1})`;
+ }
+
+ // Preserve computed styles for better rendering
+ preserveComputedStyles(clonedElement, originalElement) {
+ if (!originalElement || !clonedElement) return;
+
+ const computedStyle = window.getComputedStyle(originalElement);
+
+ // Comprehensive style properties including layout and icon-related ones
+ const importantStyles = [
+ // Typography and fonts
+ 'font-family', 'font-size', 'font-weight', 'font-style', 'font-variant',
+ 'text-align', 'text-decoration', 'text-transform', 'text-indent',
+ 'line-height', 'letter-spacing', 'word-spacing', 'white-space',
+
+ // Colors and backgrounds
+ 'color', 'background-color', 'background-image', 'background-size',
+ 'background-position', 'background-repeat', 'background-attachment',
+
+ // Layout and positioning
+ 'display', 'position', 'top', 'left', 'right', 'bottom',
+ 'width', 'height', 'min-width', 'min-height', 'max-width', 'max-height',
+ 'margin', 'padding', 'border', 'border-radius',
+ 'float', 'clear', 'vertical-align',
+
+ // Flexbox and Grid
+ 'flex', 'flex-direction', 'flex-wrap', 'flex-basis', 'flex-grow', 'flex-shrink',
+ 'justify-content', 'align-items', 'align-self', 'align-content',
+ 'grid', 'grid-template', 'grid-area', 'grid-column', 'grid-row',
+
+ // Visual effects
+ 'opacity', 'visibility', 'overflow', 'overflow-x', 'overflow-y',
+ 'box-shadow', 'text-shadow', 'transform', 'filter',
+ 'z-index', 'cursor'
+ ];
+
+ // Apply computed styles
+ importantStyles.forEach(property => {
+ const value = computedStyle.getPropertyValue(property);
+ if (value && value !== 'none' && value !== 'normal' && value !== 'auto' && value !== 'initial') {
+ try {
+ clonedElement.style.setProperty(property, value, 'important');
+ } catch (e) {
+ // Skip properties that can't be set
+ }
+ }
+ });
+
+ // Handle pseudo-elements (::before and ::after) which often contain icons
+ this.preservePseudoElements(clonedElement, originalElement);
+
+ // Recursively apply to children
+ const originalChildren = Array.from(originalElement.children);
+ const clonedChildren = Array.from(clonedElement.children);
+
+ for (let i = 0; i < Math.min(originalChildren.length, clonedChildren.length); i++) {
+ this.preserveComputedStyles(clonedChildren[i], originalChildren[i]);
+ }
+ }
+
+ // Handle pseudo-elements that often contain icons
+ preservePseudoElements(clonedElement, originalElement) {
+ try {
+ ['::before', '::after'].forEach(pseudo => {
+ const pseudoStyle = window.getComputedStyle(originalElement, pseudo);
+ const content = pseudoStyle.getPropertyValue('content');
+
+ // If pseudo-element has content, try to preserve it
+ if (content && content !== 'none' && content !== '""') {
+ const pseudoProperties = [
+ 'content', 'display', 'position', 'top', 'left', 'right', 'bottom',
+ 'width', 'height', 'font-family', 'font-size', 'color',
+ 'background-color', 'background-image', 'border', 'border-radius',
+ 'transform', 'opacity'
+ ];
+
+ // Create inline style for pseudo-element
+ let selector = this.getElementSelector(clonedElement);
+ let pseudoCSS = `${selector}${pseudo} {`;
+ pseudoProperties.forEach(prop => {
+ const value = pseudoStyle.getPropertyValue(prop);
+ if (value && value !== 'none' && value !== 'normal') {
+ pseudoCSS += `${prop}: ${value} !important;`;
+ }
+ });
+ pseudoCSS += '}';
+
+ // Add to document head
+ const style = document.createElement('style');
+ style.textContent = pseudoCSS;
+ document.head.appendChild(style);
+ }
+ });
+ } catch (e) {
+ // Pseudo-element handling failed, continue without it
+ }
+ }
+
+ // Wait for fonts and resources to load properly
+ async waitForFontsAndResources(element) {
+ // Wait for document fonts to load
+ if (document.fonts && document.fonts.ready) {
+ try {
+ await document.fonts.ready;
+ } catch (e) {
+ // Font loading API not available or failed
+ }
+ }
+
+ // Check for icon fonts (Font Awesome, Material Icons, etc.)
+ const iconFontFamilies = [
+ 'FontAwesome', 'Font Awesome', 'Font Awesome 5', 'Font Awesome 6',
+ 'Material Icons', 'Material Icons Outlined', 'Material Icons Sharp',
+ 'Ionicons', 'Feather', 'Lucide', 'Tabler Icons'
+ ];
+
+ // Force load any icon fonts found in the element
+ const allElements = [element, ...element.querySelectorAll('*')];
+ const fontPromises = [];
+
+ allElements.forEach(el => {
+ const computedStyle = window.getComputedStyle(el);
+ const fontFamily = computedStyle.fontFamily;
+
+ iconFontFamilies.forEach(iconFont => {
+ if (fontFamily.includes(iconFont)) {
+ // Create a test element to ensure font is loaded
+ const testEl = document.createElement('span');
+ testEl.style.fontFamily = iconFont;
+ testEl.style.position = 'absolute';
+ testEl.style.left = '-9999px';
+ testEl.textContent = '■'; // Use a test character
+ document.body.appendChild(testEl);
+
+ const fontPromise = new Promise(resolve => {
+ setTimeout(() => {
+ document.body.removeChild(testEl);
+ resolve();
+ }, 100);
+ });
+ fontPromises.push(fontPromise);
+ }
+ });
+ });
+
+ // Wait for all font loading attempts
+ await Promise.all(fontPromises);
+
+ // Additional wait for any remaining resources
+ await new Promise(resolve => setTimeout(resolve, 500));
+ }
+
+
+
+ async captureElement(element) {
+ try {
+ // Determine loading message based on clipboard settings
+ let loadingMessage = 'Capturing screenshot...';
+ if (this.copyToClipboard) {
+ const availability = this.checkClipboardAPIAvailability();
+ if (availability.available) {
+ loadingMessage = 'Capturing screenshot and preparing for clipboard...';
+ } else {
+ loadingMessage = 'Capturing screenshot... (Clipboard not available)';
+ }
+ }
+
+ // Show loading state
+ this.overlay.innerHTML = `
+ <div style="position: fixed; top: 20px; left: 20px; background: rgba(0,0,0,0.9); color: white; padding: 12px 16px; border-radius: 8px; z-index: 2147483647; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; font-size: 14px; box-shadow: 0 4px 20px rgba(0,0,0,0.3);">
+ <div style="display: flex; align-items: center; gap: 10px;">
+ <div style="width: 16px; height: 16px; border: 2px solid #fff; border-top: 2px solid transparent; border-radius: 50%; animation: spin 1s linear infinite;"></div>
+ <span>${loadingMessage}</span>
+ </div>
+ </div>
+ <style>
+ @keyframes spin {
+ 0% { transform: rotate(0deg); }
+ 100% { transform: rotate(360deg); }
+ }
+ </style>
+ `;
+
+ // Remove highlight for clean capture first
+ element.classList.remove('screenshot-highlight');
+ this.removeScrollableIndicators();
+
+ // Store original styles
+ const originalStyles = {
+ overflow: element.style.overflow,
+ overflowY: element.style.overflowY,
+ overflowX: element.style.overflowX,
+ height: element.style.height,
+ maxHeight: element.style.maxHeight,
+ position: element.style.position,
+ zIndex: element.style.zIndex,
+ };
+
+ // Temporarily modify element for full capture
+ element.style.overflow = 'visible';
+ element.style.overflowY = 'visible';
+ element.style.overflowX = 'visible';
+ element.style.height = `${element.scrollHeight}px`;
+ element.style.maxHeight = 'none';
+
+ // Wait for fonts and external resources to load
+ await this.waitForFontsAndResources(element);
+
+ // Enhanced html2canvas configuration
+ const canvas = await html2canvas(element, {
+ useCORS: true,
+ allowTaint: false,
+ backgroundColor: this.background === 'transparent' ? null :
+ this.background === 'white' ? '#ffffff' : '#000000',
+
+ // Improved rendering options
+ scale: window.devicePixelRatio || 1, // Use device pixel ratio for crisp images
+ logging: false, // Disable logging for cleaner console
+
+ // Better handling of external resources
+ imageTimeout: 15000, // Wait longer for images to load
+
+ // Font handling and style preservation
+ onclone: (clonedDoc, clonedElementParam) => {
+ // Ensure all stylesheets are loaded in cloned document
+ const originalStyleSheets = Array.from(document.styleSheets);
+ const clonedHead = clonedDoc.head;
+
+ // Copy all stylesheets to cloned document
+ originalStyleSheets.forEach(styleSheet => {
+ try {
+ if (styleSheet.href) {
+ // External stylesheet
+ const link = clonedDoc.createElement('link');
+ link.rel = 'stylesheet';
+ link.href = styleSheet.href;
+ link.type = 'text/css';
+ clonedHead.appendChild(link);
+ } else if (styleSheet.ownerNode && styleSheet.ownerNode.tagName === 'STYLE') {
+ // Inline stylesheet
+ const style = clonedDoc.createElement('style');
+ style.type = 'text/css';
+ try {
+ const cssText = Array.from(styleSheet.cssRules).map(rule => rule.cssText).join('\n');
+ style.textContent = cssText;
+ } catch (e) {
+ // Fallback to original text content
+ style.textContent = styleSheet.ownerNode.textContent;
+ }
+ clonedHead.appendChild(style);
+ }
+ } catch (e) {
+ // Skip stylesheets that can't be accessed (CORS issues)
+ console.log('Skipped stylesheet due to CORS:', e);
+ }
+ });
+
+ // Apply computed styles to preserve appearance
+ const clonedElement = clonedElementParam;
+ const originalElement = element; // from outer scope
+ if (clonedElement && originalElement) {
+ this.preserveComputedStyles(clonedElement, originalElement);
+ }
+
+ return clonedDoc;
+ }
+ });
+
+ // Restore original styles
+ Object.assign(element.style, originalStyles);
+
+ // Always download the image first (core functionality)
+ const link = document.createElement('a');
+ link.href = canvas.toDataURL('image/png');
+ link.download = `screenshot-${new Date().toISOString().slice(0, 19).replace(/[:.]/g, '-')}.png`;
+ link.click();
+
+ // Handle clipboard operations if enabled (after successful canvas generation and download)
+ let clipboardResult = null;
+ if (this.copyToClipboard) {
+ const availability = this.checkClipboardAPIAvailability();
+ if (availability.available) {
+ try {
+ // Attempt clipboard operation with comprehensive error handling
+ clipboardResult = await this.copyCanvasToClipboard(canvas);
+ } catch (error) {
+ // Ensure clipboard errors don't break the workflow - this is a safety net
+ // The copyCanvasToClipboard method should handle all errors internally
+ console.error('Unexpected clipboard error caught in captureElement:', error);
+ clipboardResult = {
+ success: false,
+ error: 'Unexpected clipboard error occurred',
+ errorType: 'unexpected'
+ };
+ }
+ } else {
+ clipboardResult = {
+ success: false,
+ error: availability.reason,
+ errorType: 'api_unavailable'
+ };
+ }
+ }
+
+ // Generate user feedback message based on clipboard results
+ let successMessage = 'Screenshot downloaded successfully!';
+ let messageColor = 'rgba(39, 174, 96, 0.95)'; // Green for success
+
+ if (this.copyToClipboard) {
+ if (clipboardResult && clipboardResult.success) {
+ successMessage = 'Screenshot downloaded and copied to clipboard!';
+ // Keep green color for full success
+ } else {
+ // Download succeeded but clipboard failed - provide specific error feedback
+ const errorMessage = this.getClipboardErrorMessage(clipboardResult);
+ successMessage = `Screenshot downloaded successfully! ${errorMessage}`;
+ messageColor = 'rgba(243, 156, 18, 0.95)'; // Orange for partial success
+ }
+ }
+
+ this.overlay.innerHTML = `
+ <div style="position: fixed; top: 20px; left: 20px; background: ${messageColor}; color: white; padding: 12px 16px; border-radius: 8px; z-index: 2147483647; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; font-size: 14px; box-shadow: 0 4px 20px rgba(0,0,0,0.3);">
+ <div style="display: flex; align-items: center; gap: 10px;">
+ <span>✅</span>
+ <span>${successMessage}</span>
+ </div>
+ </div>
+ `;
+
+ // Notify popup
+ chrome.runtime.sendMessage({ action: 'selectorStopped', reason: 'screenshot-taken' });
+
+ setTimeout(() => this.cleanup(), 2000);
+
+ } catch (error) {
+ console.error('Screenshot failed:', error);
+
+ // Provide specific error messages for screenshot failures
+ let errorMessage = 'Screenshot capture failed. Please try again.';
+
+ if (error.message) {
+ if (error.message.includes('html2canvas')) {
+ errorMessage = 'Screenshot rendering failed. Try selecting a different element or refresh the page.';
+ } else if (error.message.includes('timeout')) {
+ errorMessage = 'Screenshot capture timed out. Try selecting a smaller area or simpler element.';
+ } else if (error.message.includes('network') || error.message.includes('CORS')) {
+ errorMessage = 'Screenshot failed: Some content is blocked by security restrictions.';
+ } else if (error.message.includes('memory') || error.message.includes('quota')) {
+ errorMessage = 'Screenshot failed: Not enough memory. Try capturing a smaller area.';
+ } else if (error.message.includes('canvas')) {
+ errorMessage = 'Screenshot failed: Unable to create image. Try a different element.';
+ }
+ }
+
+ this.overlay.innerHTML = `
+ <div style="position: fixed; top: 20px; left: 20px; background: rgba(231, 76, 60, 0.95); color: white; padding: 12px 16px; border-radius: 8px; z-index: 2147483647; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; font-size: 14px; box-shadow: 0 4px 20px rgba(0,0,0,0.3);">
+ <div style="display: flex; align-items: center; gap: 10px;">
+ <span>❌</span>
+ <span>${errorMessage}</span>
+ </div>
+ </div>
+ `;
+
+ // Notify popup about the failure
+ chrome.runtime.sendMessage({ action: 'selectorStopped', reason: 'screenshot-failed' });
+
+ setTimeout(() => this.cleanup(), 3000);
+ }
+ }
+
+ /**
+ * Check if Clipboard API is available and supported
+ * @returns {{available: boolean, reason?: string}} Clipboard API availability status
+ */
+ checkClipboardAPIAvailability() {
+ // Check for basic Clipboard API support
+ if (!navigator.clipboard) {
+ return {
+ available: false,
+ reason: 'Clipboard API not available in this browser'
+ };
+ }
+
+ // Check for ClipboardItem constructor (required for image data)
+ if (!window.ClipboardItem) {
+ return {
+ available: false,
+ reason: 'ClipboardItem not supported in this browser'
+ };
+ }
+
+ // Check if we're in a secure context (HTTPS required for clipboard)
+ if (!window.isSecureContext) {
+ return {
+ available: false,
+ reason: 'Clipboard API requires a secure context (HTTPS)'
+ };
+ }
+
+ // Check for write permission (this is the basic check, actual permission is checked during write)
+ if (!navigator.clipboard.write) {
+ return {
+ available: false,
+ reason: 'Clipboard write functionality not available'
+ };
+ }
+
+ return {
+ available: true
+ };
+ }
+
+ /**
+ * Get user-friendly feedback message about clipboard feature availability
+ * @returns {{supported: boolean, message: string}} User feedback about clipboard support
+ */
+ getClipboardSupportFeedback() {
+ const availability = this.checkClipboardAPIAvailability();
+
+ if (availability.available) {
+ return {
+ supported: true,
+ message: 'Clipboard copying is available and ready to use.'
+ };
+ }
+
+ // Provide user-friendly messages for different scenarios
+ let userMessage = '';
+
+ if (availability.reason.includes('not available') || availability.reason.includes('not supported')) {
+ userMessage = 'Your browser doesn\'t support clipboard copying. Screenshots will still be downloaded.';
+ } else if (availability.reason.includes('secure context')) {
+ userMessage = 'Clipboard copying requires HTTPS. Screenshots will still be downloaded.';
+ } else if (availability.reason.includes('write functionality')) {
+ userMessage = 'Clipboard writing is not available. Screenshots will still be downloaded.';
+ } else {
+ userMessage = 'Clipboard copying is not available. Screenshots will still be downloaded.';
+ }
+
+ return {
+ supported: false,
+ message: userMessage
+ };
+ }
+
+ /**
+ * Generate user-friendly error message for clipboard operation failures
+ * @param {Object} clipboardResult - Result object from clipboard operation
+ * @returns {string} User-friendly error message
+ */
+ getClipboardErrorMessage(clipboardResult) {
+ if (!clipboardResult || !clipboardResult.error) {
+ return 'Clipboard copy failed due to unknown error.';
+ }
+
+ const errorType = clipboardResult.errorType;
+ const errorMessage = clipboardResult.error;
+
+ // Provide contextual error messages based on error type
+ switch (errorType) {
+ case 'permission_denied':
+ return 'Clipboard copy failed: Permission denied. Please allow clipboard access in your browser settings.';
+
+ case 'not_supported':
+ case 'api_unavailable':
+ return 'Clipboard copy not available in this browser. Screenshot was still downloaded.';
+
+ case 'security_error':
+ return 'Clipboard copy blocked by browser security. Try using HTTPS or check site permissions.';
+
+ case 'size_limit':
+ case 'quota_exceeded':
+ return 'Clipboard copy failed: Image too large. Try capturing a smaller area.';
+
+ case 'timeout':
+ return 'Clipboard copy timed out. The image may be too large or complex.';
+
+ case 'network_error':
+ return 'Clipboard copy failed due to network error. Please try again.';
+
+ case 'canvas_conversion':
+ return 'Clipboard copy failed: Unable to prepare image. Try capturing a different element.';
+
+ case 'clipboard_item_creation':
+ return 'Clipboard copy not supported: Your browser doesn\'t support image clipboard operations.';
+
+ case 'invalid_state':
+ return 'Clipboard copy failed: Browser clipboard is busy. Please try again.';
+
+ case 'data_error':
+ return 'Clipboard copy failed: Invalid image data. Please try capturing again.';
+
+ case 'unexpected':
+ return 'Clipboard copy failed due to unexpected error. Screenshot was still downloaded.';
+
+ default:
+ // For unknown error types, try to extract meaningful info from the error message
+ if (errorMessage.includes('permission') || errorMessage.includes('denied')) {
+ return 'Clipboard copy failed: Access denied. Check browser permissions.';
+ } else if (errorMessage.includes('not supported') || errorMessage.includes('unavailable')) {
+ return 'Clipboard copy not supported in this browser.';
+ } else if (errorMessage.includes('timeout') || errorMessage.includes('timed out')) {
+ return 'Clipboard copy timed out. Try capturing a smaller area.';
+ } else if (errorMessage.includes('large') || errorMessage.includes('size')) {
+ return 'Clipboard copy failed: Image too large for clipboard.';
+ } else {
+ return `Clipboard copy failed: ${errorMessage}`;
+ }
+ }
+ }
+
+ /**
+ * Copy canvas content to clipboard using the Clipboard API
+ * @param {HTMLCanvasElement} canvas - The canvas element to copy
+ * @returns {Promise<{success: boolean, error?: string, errorType?: string}>} Result of clipboard operation
+ */
+ async copyCanvasToClipboard(canvas) {
+ try {
+ // Check clipboard API availability first
+ const availability = this.checkClipboardAPIAvailability();
+ if (!availability.available) {
+ return {
+ success: false,
+ error: availability.reason,
+ errorType: 'api_unavailable'
+ };
+ }
+
+ // Convert canvas to blob in PNG format with timeout
+ const blob = await Promise.race([
+ new Promise((resolve, reject) => {
+ canvas.toBlob((blob) => {
+ if (blob) {
+ resolve(blob);
+ } else {
+ reject(new Error('Canvas to blob conversion returned null'));
+ }
+ }, 'image/png');
+ }),
+ new Promise((_, reject) =>
+ setTimeout(() => reject(new Error('Canvas to blob conversion timed out')), 10000)
+ )
+ ]);
+
+ // Validate blob size (prevent extremely large clipboard operations)
+ const maxBlobSize = 50 * 1024 * 1024; // 50MB limit
+ if (blob.size > maxBlobSize) {
+ return {
+ success: false,
+ error: `Image too large for clipboard (${Math.round(blob.size / 1024 / 1024)}MB). Try capturing a smaller area.`,
+ errorType: 'size_limit'
+ };
+ }
+
+ // Create ClipboardItem with PNG image data
+ let clipboardItem;
+ try {
+ clipboardItem = new ClipboardItem({
+ 'image/png': blob
+ });
+ } catch (clipboardItemError) {
+ return {
+ success: false,
+ error: 'Failed to create clipboard item. Your browser may not support image clipboard operations.',
+ errorType: 'clipboard_item_creation'
+ };
+ }
+
+ // Write to clipboard with timeout
+ await Promise.race([
+ navigator.clipboard.write([clipboardItem]),
+ new Promise((_, reject) =>
+ setTimeout(() => reject(new Error('Clipboard write operation timed out')), 15000)
+ )
+ ]);
+
+ return { success: true };
+
+ } catch (error) {
+ console.error('Clipboard operation failed:', error);
+
+ // Comprehensive error handling with specific error types and user-friendly messages
+ let errorMessage = error.message || 'Unknown clipboard error';
+ let errorType = 'unknown';
+
+ // Permission-related errors
+ if (error.name === 'NotAllowedError') {
+ errorMessage = 'Clipboard access denied. Please allow clipboard permissions in your browser settings.';
+ errorType = 'permission_denied';
+ }
+ // API support errors
+ else if (error.name === 'NotSupportedError') {
+ errorMessage = 'Clipboard API not supported in this browser context.';
+ errorType = 'not_supported';
+ }
+ // Security context errors
+ else if (error.name === 'SecurityError') {
+ errorMessage = 'Clipboard access blocked by security policy. Try using HTTPS.';
+ errorType = 'security_error';
+ }
+ // Network or resource errors
+ else if (error.name === 'NetworkError') {
+ errorMessage = 'Network error during clipboard operation. Please try again.';
+ errorType = 'network_error';
+ }
+ // Timeout errors
+ else if (error.message.includes('timed out')) {
+ errorMessage = 'Clipboard operation timed out. The image may be too large.';
+ errorType = 'timeout';
+ }
+ // Canvas conversion errors
+ else if (error.message.includes('canvas') || error.message.includes('blob')) {
+ errorMessage = 'Failed to prepare image for clipboard. Try capturing a different area.';
+ errorType = 'canvas_conversion';
+ }
+ // Quota or storage errors
+ else if (error.name === 'QuotaExceededError' || error.message.includes('quota')) {
+ errorMessage = 'Clipboard storage quota exceeded. Try capturing a smaller image.';
+ errorType = 'quota_exceeded';
+ }
+ // DOM or state errors
+ else if (error.name === 'InvalidStateError') {
+ errorMessage = 'Clipboard is in an invalid state. Please try again.';
+ errorType = 'invalid_state';
+ }
+ // Data errors
+ else if (error.name === 'DataError') {
+ errorMessage = 'Invalid image data for clipboard. Please try again.';
+ errorType = 'data_error';
+ }
+ // Generic fallback for unknown errors
+ else {
+ errorMessage = `Clipboard operation failed: ${error.message}`;
+ errorType = 'unknown';
+ }
+
+ return {
+ success: false,
+ error: errorMessage,
+ errorType: errorType
+ };
+ }
+ }
+
+ cleanup() {
+ document.removeEventListener('mouseover', this.handleMouseOver);
+ document.removeEventListener('click', this.handleClick, true);
+ document.removeEventListener('keydown', this.handleKeyPress);
+
+ if (this.currentHighlight) {
+ this.currentHighlight.classList.remove('screenshot-highlight');
+ }
+
+ // Remove any scrollable indicators
+ this.removeScrollableIndicators();
+
+ if (this.overlay) {
+ this.overlay.remove();
+ this.overlay = null;
+ }
+
+ if (this.style) {
+ this.style.remove();
+ this.style = null;
+ }
+
+ this.isActive = false;
+ this.currentHighlight = null;
+ }
+}
+
+// Global instance
+let screenshotSelector = new ScreenshotSelector();
+
+// Add load indicator
+console.log('Full Screenshot Selector content script loaded');
+
+// Listen for messages from popup
+chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
+ try {
+ switch (message.action) {
+ case 'startSelector':
+ // Extract clipboard preference from message, default to true for backward compatibility
+ const copyToClipboard = message.copyToClipboard !== undefined ? message.copyToClipboard : true;
+ screenshotSelector.init(message.background, copyToClipboard);
+ sendResponse({ success: true });
+ break;
+
+ case 'stopSelector':
+ screenshotSelector.cleanup();
+ sendResponse({ success: true });
+ break;
+
+ case 'checkState':
+ sendResponse({ isActive: screenshotSelector.isActive });
+ break;
+
+ case 'checkClipboardSupport':
+ const availability = screenshotSelector.checkClipboardAPIAvailability();
+ const feedback = screenshotSelector.getClipboardSupportFeedback();
+ sendResponse({
+ availability: availability,
+ feedback: feedback
+ });
+ break;
+
+ default:
+ sendResponse({ error: 'Unknown action: ' + message.action });
+ }
+ } catch (error) {
+ console.error('Content script error:', error);
+ sendResponse({ error: error.message });
+ }
+
+ // Important: return true to indicate async response
+ return true;
+});
+
+// Handle keyboard shortcut
+chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
+ if (message.action === 'activateFromShortcut') {
+ if (!screenshotSelector.isActive) {
+ screenshotSelector.init('black', true); // Default background and clipboard enabled for shortcut
+ }
+ }
+}); |