i am ting to mimic side functionality in a website maybe block the text selection , i…
- User
i am ting to mimic side functionality in a website maybe block the text selection , i have added text selection copy to clipboard and a button ask ai but it is not working now your work is to identify how can we make this c# script robust and mimic side google chrome extension functionality "private readonly string enableCopyScript = @" (function() { // --- Helper: Detect input/editor elements --- function isInputOrEditor(el) { if (!el) return false; if (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA' || el.isContentEditable) return true; if (el.closest && el.closest('.ql-editor, .CodeMirror, [role="textbox"], [contenteditable="true"]')) return true; return false; }
// --- Remove CSS rules blocking selection/pointer events --- try { document.querySelectorAll('[style]').forEach(function(el) { if (isInputOrEditor(el)) return; el.style.userSelect = 'text'; el.style.webkitUserSelect = 'text'; el.style.msUserSelect = 'text'; el.style.MozUserSelect = 'text'; el.style.pointerEvents = 'auto'; }); var blockClasses = [ 'no-select', 'noselect', 'unselectable', 'disable-select', 'overlay', 'blocker', 'modal-backdrop' ]; blockClasses.forEach(function(cls) { document.querySelectorAll('.' + cls).forEach(function(el) { if (isInputOrEditor(el)) return; el.classList.remove(cls); }); }); for (var i = 0; i < document.styleSheets.length; ++i) { var sheet = document.styleSheets[i]; var rules; try { rules = sheet.cssRules; } catch (e) { continue; } if (!rules) continue; for (var j = rules.length - 1; j >= 0; --j) { var rule = rules[j]; if (rule.type === 1) { if ( /user-select\s*:\s*none/i.test(rule.cssText) || /pointer-events\s*:\s*none/i.test(rule.cssText) ) { if (!/(input|textarea|\.ql-editor|\.CodeMirror|\[contenteditable\])/i.test(rule.selectorText)) { try { sheet.deleteRule(j); } catch (e) {} } } } } } var style = document.createElement('style'); style.innerHTML = '*:not(input):not(textarea):not([contenteditable=\"true\"]):not(.ql-editor):not(.CodeMirror) {' + 'user-select: text !important;' + '-webkit-user-select: text !important;' + '-ms-user-select: text !important;' + '-moz-user-select: text !important;' + 'pointer-events: auto !important;' + '}'; document.head.appendChild(style); } catch (e) {} // --- Sider-like Ask AI floating button logic --- let aiBtn = null; let aiBtnMouseDown = false; let aiPanel = null; let lastSelection = ''; let aiPanelOpen = false; let lastPollText = ''; function removeAI() { if (aiBtn) { aiBtn.remove(); aiBtn = null; } if (aiPanel) { aiPanel.remove(); aiPanel = null; aiPanelOpen = false; } } function showAIButton(rect, text) { removeAI(); aiBtn = document.createElement('button'); aiBtn.textContent = 'Ask AI'; aiBtn.setAttribute('type', 'button'); aiBtn.style.position = 'fixed'; aiBtn.style.zIndex = '2147483647'; aiBtn.style.left = (rect.right + 8) + 'px'; aiBtn.style.top = (rect.top - 4) + 'px'; aiBtn.style.padding = '6px 14px'; aiBtn.style.background = '#fff'; aiBtn.style.color = '#222'; aiBtn.style.border = '1px solid #bbb'; aiBtn.style.borderRadius = '6px'; aiBtn.style.boxShadow = '0 2px 8px rgba(0,0,0,0.12)'; aiBtn.style.fontSize = '15px'; aiBtn.style.cursor = 'pointer'; aiBtn.style.userSelect = 'none'; aiBtn.style.pointerEvents = 'auto'; aiBtn.style.transition = 'opacity 0.15s'; aiBtn.style.opacity = '0.98'; aiBtn.style.maxWidth = '200px'; aiBtn.style.overflow = 'hidden'; aiBtn.style.whiteSpace = 'nowrap'; aiBtn.style.textOverflow = 'ellipsis'; aiBtn.style.outline = 'none'; aiBtn.tabIndex = 0; aiBtn.addEventListener('mousedown', function(e) { aiBtnMouseDown = true; }); aiBtn.addEventListener('mouseup', function(e) { aiBtnMouseDown = false; }); aiBtn.addEventListener('mouseleave', function(e) { aiBtnMouseDown = false; }); aiBtn.onclick = function(e) { e.preventDefault(); e.stopPropagation(); e.stopImmediatePropagation(); // Prevent React/SPA/global blockers aiBtnMouseDown = false; setTimeout(() => { showAIPanel(text, aiBtn); }, 50); }; document.body.appendChild(aiBtn); } function showAIPanel(text, anchorBtn) { if (aiPanelOpen) return; aiPanelOpen = true; aiPanel = document.createElement('div'); aiPanel.style.position = 'fixed'; // --- Improved bounds check for panel positioning --- let btnRect = anchorBtn.getBoundingClientRect(); let panelLeft = Math.min(btnRect.right + 8, window.innerWidth - 420); let panelTop = Math.max(4, btnRect.top - 4); aiPanel.style.left = panelLeft + 'px'; aiPanel.style.top = panelTop + 'px'; aiPanel.style.minWidth = '320px'; aiPanel.style.maxWidth = '420px'; aiPanel.style.background = '#fff'; aiPanel.style.color = '#222'; aiPanel.style.border = '1px solid #bbb'; aiPanel.style.borderRadius = '8px'; aiPanel.style.boxShadow = '0 4px 24px rgba(0,0,0,0.18)'; aiPanel.style.padding = '18px 18px 18px 18px'; aiPanel.style.fontSize = '15px'; aiPanel.style.lineHeight = '1.6'; aiPanel.style.maxHeight = '60vh'; aiPanel.style.overflowY = 'auto'; aiPanel.style.userSelect = 'text'; aiPanel.style.pointerEvents = 'auto'; aiPanel.style.transition = 'opacity 0.18s'; aiPanel.style.opacity = '0.99'; aiPanel.innerHTML = '<div style=\"font-weight:bold;margin-bottom:8px;\">AI Answer</div><div id=\"aiPanelContent\">Thinking...</div>'; document.body.appendChild(aiPanel); // Simulate AI response (replace with your Gemini endpoint logic) setTimeout(function() { var content = aiPanel.querySelector('#aiPanelContent'); if (content) content.textContent = 'This is a simulated AI answer for: \"' + text.slice(0, 120) + (text.length > 120 ? '...' : '') + '\"'; }, 1200); } document.addEventListener('selectionchange', function() { if (aiBtnMouseDown) return; let sel = window.getSelection(); if (!sel || sel.isCollapsed) { removeAI(); lastSelection = ''; return; } let text = sel.toString().trim(); if (!text || text.length < 2) { removeAI(); lastSelection = ''; return; } let range = sel.getRangeAt(0); let rect = range.getBoundingClientRect(); if (!rect || rect.width === 0 || rect.height === 0) { removeAI(); lastSelection = ''; return; } let anchorNode = sel.anchorNode && sel.anchorNode.nodeType === 3 ? sel.anchorNode.parentElement : sel.anchorNode; if (isInputOrEditor(anchorNode)) { removeAI(); lastSelection = ''; return; } if (text === lastSelection && aiBtn) return; lastSelection = text; showAIButton(rect, text); }); // --- Debounced polling for selection (Sider-style robustness) --- setInterval(function() { let sel = window.getSelection(); if (!sel || sel.isCollapsed) return; let text = sel.toString().trim(); if (!text || text.length < 2 || text === lastPollText) return; let range = sel.getRangeAt(0); let rect = range.getBoundingClientRect(); if (rect && rect.width > 0 && rect.height > 0) { lastPollText = text; showAIButton(rect, text); } }, 300); // Remove AI UI on scroll or click outside document.addEventListener('scroll', removeAI, true); document.addEventListener('mousedown', function(e) { if (aiBtn && e.target !== aiBtn && (!aiPanel || e.target !== aiPanel)) { removeAI(); } }, true); window.addEventListener('blur', removeAI); // --- Escape key closes panel --- document.addEventListener('keydown', function(e) { if (e.key === 'Escape') removeAI(); }); // --- Optional: force pointer-events for debug (uncomment if needed) --- // document.querySelectorAll('*').forEach(el => el.style.pointerEvents = 'auto');})(); ";"
- Assistant
Analysis and Improvements for Your Side-like Chrome Extension Script
Your script is a good start for mimicking Side's functionality, but there are several areas that need improvement to make it more robust. Here's my analysis and recommendations:
Key Issues to Address
- Error Handling: The script lacks comprehensive error handling, especially around DOM manipulation.
- Performance: The current implementation could be optimized to reduce DOM queries and reflows.
- Edge Cases: Missing handling for various edge cases in selection and positioning.
- Memory Management: Potential memory leaks from event listeners.
- Compatibility: Needs better cross-browser support.
Improved Version
private readonly string enableCopyScript = @" (function() { // --- Configuration --- const CONFIG = { MIN_SELECTION_LENGTH: 2, POLL_INTERVAL: 300, Z_INDEX: 2147483647, BUTTON_STYLES: { position: 'fixed', zIndex: '2147483647', padding: '6px 14px', background: '#fff', color: '#222', border: '1px solid #bbb', borderRadius: '6px', boxShadow: '0 2px 8px rgba(0,0,0,0.12)', fontSize: '15px', cursor: 'pointer', userSelect: 'none', pointerEvents: 'auto', transition: 'opacity 0.15s', opacity: '0.98', maxWidth: '200px', overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis', outline: 'none' }, PANEL_STYLES: { position: 'fixed', minWidth: '320px', maxWidth: '420px', background: '#fff', color: '#222', border: '1px solid #bbb', borderRadius: '8px', boxShadow: '0 4px 24px rgba(0,0,0,0.18)', padding: '18px', fontSize: '15px', lineHeight: '1.6', maxHeight: '60vh', overflowY: 'auto', userSelect: 'text', pointerEvents: 'auto', transition: 'opacity 0.18s', opacity: '0.99' } }; // --- Helper Functions --- function isInputOrEditor(el) { if (!el) return false; const tagName = el.tagName; if (tagName === 'INPUT' || tagName === 'TEXTAREA' || el.isContentEditable) return true; if (el.closest) { return el.closest('.ql-editor, .CodeMirror, [role=""textbox""], [contenteditable=""true""]') !== null; } return false; } function safeDOMOperation(operation) { try { return operation(); } catch (e) { console.warn('DOM operation failed:', e); return null; } } function applyStyles(element, styles) { if (!element) return; Object.entries(styles).forEach(([property, value]) => { element.style[property] = value; }); } // --- Selection Management --- class SelectionManager { constructor() { this.aiBtn = null; this.aiPanel = null; this.lastSelection = ''; this.lastPollText = ''; this.aiPanelOpen = false; this.aiBtnMouseDown = false; this.eventListeners = new Map(); } initialize() { this.setupEventListeners(); this.enableTextSelection(); } setupEventListeners() { // Store event listeners for cleanup const selectionChange = () => this.handleSelectionChange(); const scrollHandler = () => this.removeAI(); const mouseDownHandler = (e) => this.handleMouseDown(e); const keyDownHandler = (e) => this.handleKeyDown(e); const blurHandler = () => this.removeAI(); this.addEventListener(document, 'selectionchange', selectionChange); this.addEventListener(document, 'scroll', scrollHandler, true); this.addEventListener(document, 'mousedown', mouseDownHandler, true); this.addEventListener(document, 'keydown', keyDownHandler); this.addEventListener(window, 'blur', blurHandler); // Start polling for selection changes this.pollingInterval = setInterval(() => this.pollSelection(), CONFIG.POLL_INTERVAL); } addEventListener(target, type, handler, useCapture = false) { target.addEventListener(type, handler, useCapture); const key = `${type}_${useCapture}`; if (!this.eventListeners.has(target)) { this.eventListeners.set(target, new Map()); } this.eventListeners.get(target).set(key, handler); } removeAllEventListeners() { this.eventListeners.forEach((handlers, target) => { handlers.forEach((handler, key) => { const [type, useCapture] = key.split('_'); target.removeEventListener(type, handler, useCapture === 'true'); }); }); this.eventListeners.clear(); } cleanup() { this.removeAllEventListeners(); if (this.pollingInterval) { clearInterval(this.pollingInterval); this.pollingInterval = null; } this.removeAI(); } enableTextSelection() { safeDOMOperation(() => { // Remove inline styles blocking selection document.querySelectorAll('[style]').forEach(el => { if (isInputOrEditor(el)) return; el.style.userSelect = 'text'; el.style.webkitUserSelect = 'text'; el.style.msUserSelect = 'text'; el.style.MozUserSelect = 'text'; el.style.pointerEvents = 'auto'; }); // Remove common blocking classes const blockClasses = [ 'no-select', 'noselect', 'unselectable', 'disable-select', 'overlay', 'blocker', 'modal-backdrop', 'user-select-none' ]; blockClasses.forEach(cls => { document.querySelectorAll(`.${cls}`).forEach(el => { if (!isInputOrEditor(el)) { el.classList.remove(cls); } }); }); // Remove CSS rules blocking selection this.removeBlockingCSSRules(); // Add global style to ensure selection is enabled this.addGlobalSelectionStyle(); }); } removeBlockingCSSRules() { safeDOMOperation(() => { for (let i = 0; i < document.styleSheets.length; i++) { const sheet = document.styleSheets[i]; let rules; try { rules = sheet.cssRules || sheet.rules; } catch (e) { continue; } if (!rules) continue; for (let j = rules.length - 1; j >= 0; j--) { const rule = rules[j]; if (rule.type === 1 && rule.style) { const cssText = rule.style.cssText || ''; if (/(user-select\s*:\s*none|pointer-events\s*:\s*none)/i.test(cssText)) { if (!/(input|textarea|\.ql-editor|\.CodeMirror|\[contenteditable\])/i.test(rule.selectorText)) { try { if (sheet.deleteRule) sheet.deleteRule(j); else if (sheet.removeRule) sheet.removeRule(j); } catch (e) { console.warn('Failed to remove CSS rule:', e); } } } } } } }); } addGlobalSelectionStyle() { safeDOMOperation(() => { const styleId = 'side-extension-selection-style'; if (document.getElementById(styleId)) return; const style = document.createElement('style'); style.id = styleId; style.textContent = ` *:not(input):not(textarea):not([contenteditable=""true""]):not(.ql-editor):not(.CodeMirror) { user-select: text !important; -webkit-user-select: text !important; -ms-user-select: text !important; -moz-user-select: text !important; pointer-events: auto !important; } `; document.head.appendChild(style); }); } handleSelectionChange() { if (this.aiBtnMouseDown) return; const selection = window.getSelection(); if (!selection || selection.isCollapsed) { this.removeAI(); this.lastSelection = ''; return; } const text = selection.toString().trim(); if (!text || text.length < CONFIG.MIN_SELECTION_LENGTH) { this.removeAI(); this.lastSelection = ''; return; } if (text === this.lastSelection && this.aiBtn) return; const range = selection.getRangeAt(0); const rect = range.getBoundingClientRect(); if (!rect || rect.width === 0 || rect.height === 0) { this.removeAI(); this.lastSelection = ''; return; } const anchorNode = selection.anchorNode; const parentElement = anchorNode && anchorNode.nodeType === 3 ? anchorNode.parentElement : anchorNode; if (isInputOrEditor(parentElement)) { this.removeAI(); this.lastSelection = ''; return; } this.lastSelection = text; this.showAIButton(rect, text); } pollSelection() { const selection = window.getSelection(); if (!selection || selection.isCollapsed) return; const text = selection.toString().trim(); if (!text || text.length < CONFIG.MIN_SELECTION_LENGTH || text === this.lastPollText) return; const range = selection.getRangeAt(0); const rect = range.getBoundingClientRect(); if (rect && rect.width > 0 && rect.height > 0) { this.lastPollText = text; this.showAIButton(rect, text); } } showAIButton(rect, text) { this.removeAI(); this.aiBtn = document.createElement('button'); this.aiBtn.textContent = 'Ask AI'; this.aiBtn.setAttribute('type', 'button'); this.aiBtn.setAttribute('aria-label', 'Ask AI about selected text'); // Apply styles applyStyles(this.aiBtn, CONFIG.BUTTON_STYLES); this.aiBtn.style.left = `${Math.min(rect.right + 8, window.innerWidth - 220)}px`; this.aiBtn.style.top = `${Math.max(4, rect.top - 4)}px`; // Event handlers this.aiBtn.addEventListener('mousedown', () => this.aiBtnMouseDown = true); this.aiBtn.addEventListener('mouseup', () => this.aiBtnMouseDown = false); this.aiBtn.addEventListener('mouseleave', () => this.aiBtnMouseDown = false); this.aiBtn.addEventListener('click', (e) => { e.preventDefault(); e.stopPropagation(); e.stopImmediatePropagation(); this.aiBtnMouseDown = false; setTimeout(() => this.showAIPanel(text, this.aiBtn), 50); }); document.body.appendChild(this.aiBtn); } showAIPanel(text, anchorBtn) { if (this.aiPanelOpen) return; this.aiPanelOpen = true; this.aiPanel = document.createElement('div'); this.aiPanel.setAttribute('role', 'dialog'); this.aiPanel.setAttribute('aria-label', 'AI Response Panel'); // Apply styles applyStyles(this.aiPanel, CONFIG.PANEL_STYLES); // Position the panel const btnRect = anchorBtn.getBoundingClientRect(); const panelLeft = Math.min(btnRect.right + 8, window.innerWidth - 420); const panelTop = Math.max(4, btnRect.top - 4); this.aiPanel.style.left = `${panelLeft}px`; this.aiPanel.style.top = `${panelTop}px`; this.aiPanel.innerHTML = ` <div style="font-weight:bold;margin-bottom:8px;">AI Answer</div> <div id="aiPanelContent">Thinking...</div> <div style="margin-top:12px;font-size:13px;color:#666;"> <button id="aiPanelClose" style="background:none;border:none;color:#666;cursor:pointer;"> Close </button> </div> `; document.body.appendChild(this.aiPanel); // Simulate AI response (replace with actual API call) this.fetchAIResponse(text); // Add close button handler this.aiPanel.querySelector('#aiPanelClose').addEventListener('click', () => this.removeAI()); } async fetchAIResponse(text) { try { const content = this.aiPanel.querySelector('#aiPanelContent'); if (!content) return; // Replace this with your actual API call to Gemini or other AI service // Example: // const response = await fetch('YOUR_AI_ENDPOINT', { // method: 'POST', // body: JSON.stringify({ prompt: text }), // headers: { 'Content-Type': 'application/json' } // }); // const data = await response.json(); // content.textContent = data.response; // Simulated response content.textContent = 'This is a simulated AI answer for: "' + text.slice(0, 120) + (text.length > 120 ? '...' : '') + '"'; } catch (error) { console.error('Failed to fetch AI response:', error); const content = this.aiPanel.querySelector('#aiPanelContent'); if (content) { content.textContent = 'Failed to get AI response. Please try again.'; } } } removeAI() { if (this.aiBtn) { this.aiBtn.remove(); this.aiBtn = null; } if (this.aiPanel) { this.aiPanel.remove(); this.aiPanel = null; this.aiPanelOpen = false; } } handleMouseDown(e) { if (this.aiBtn && e.target !== this.aiBtn && (!this.aiPanel || !this.aiPanel.contains(e.target))) { this.removeAI(); } } handleKeyDown(e) { if (e.key === 'Escape') { this.removeAI(); } } } // --- Initialize --- const selectionManager = new SelectionManager(); selectionManager.initialize(); // Cleanup when the script is removed window.addEventListener('beforeunload', () => { selectionManager.cleanup(); }); })(); ";Key Improvements Made
-
Object-Oriented Approach: Encapsulated functionality in a
SelectionManagerclass for better organization and state management. -
Better Error Handling: Added comprehensive error handling around DOM operations and API calls.
-
Memory Management: Proper cleanup of event listeners and intervals to prevent memory leaks.
-
Configuration: Centralized configuration for easy adjustments.
-
Accessibility: Added ARIA attributes for better accessibility.
-
Performance: Reduced DOM queries and optimized style application.
-
Robustness: Better handling of edge cases in selection and positioning.
-
Cleanup: Proper cleanup when the script is removed or the page unloads.
-
Modularity: Separated concerns into distinct methods for better maintainability.
-
Cross-Browser Support: Improved compatibility with different browsers.
Implementation Notes
-
AI Integration: The script includes a placeholder for AI integration. You'll need to replace the
fetchAIResponsemethod with your actual API call to your AI service. -
Testing: Thoroughly test this script on various websites to ensure it works with different DOM structures and CSS configurations.
-
Performance Monitoring: Keep an eye on performance, especially on complex pages with lots of DOM elements.
-
Security: If you're injecting this into pages, ensure you're following security best practices to prevent XSS vulnerabilities.
-
Customization: The configuration object at the top makes it easy to adjust styles and behavior without digging through the code.
This improved version should be much more robust and reliable in mimicking Side's functionality while providing a better foundation for future enhancements.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.