Explore base on this edge & chrome extension code ,manifest v3, content.js "class LinkSelector {… Save Share Download ▾ Reportbase on this edge & chrome extension code ,manifest v3, content.js "class LinkSelector {
constructor() {
this.isSelecting = false;
this.startX = 0;
this.startY = 0;
this.selectedLinks = new Set();
this.selectionBox = null;
this.counter = null;
this.scrollInterval = null;
this.initialScrollY = 0;
this.lastMouseX = 0;
this.lastMouseY = 0;
this.activeModifierKey = false;
this.settings = {
modifierKey: 'Control',
mouseButton: 0,
outlineColor: '#ffff00',
linkColor: '#0000ff',
borderSize: 4
};
this.init();
}
async init() {
await this.loadSettings();
this.createElements();
this.attachEventListeners();
this.updateStyles();
console.log('LinkSelector initialized');
}
createElements() {
this.selectionBox = document.createElement('div');
this.selectionBox.className = 'selection-box';
this.selectionBox.style.display = 'none';
this.selectionBox.style.position = 'absolute';
this.selectionBox.style.border = ${this.settings.borderSize}px solid ${this.settings.outlineColor};
this.selectionBox.style.backgroundColor = 'transparent';
this.selectionBox.style.pointerEvents = 'none';
this.selectionBox.style.zIndex = '10000';
code Copy code
this.counter = document.createElement('div');
this.counter.className = 'selection-counter';
this.counter.style.display = 'none';
this.counter.style.position = 'fixed';
this.counter.style.backgroundColor = 'white';
this.counter.style.padding = '2px 8px';
this.counter.style.borderRadius = '4px';
this.counter.style.zIndex = '10001';
document.body.appendChild(this.selectionBox);
document.body.appendChild(this.counter);
}
attachEventListeners() {
document.addEventListener('keydown', (e) => {
if (e.key === this.settings.modifierKey) {
this.activeModifierKey = true;
}
});
code Copy code
document.addEventListener('keyup', (e) => {
if (e.key === this.settings.modifierKey) {
this.activeModifierKey = false;
if (this.isSelecting) {
this.cancelSelection();
}
}
});
document.addEventListener('mousedown', (e) => this.handleMouseDown(e));
document.addEventListener('mousemove', (e) => this.handleMouseMove(e));
document.addEventListener('mouseup', (e) => this.handleMouseUp(e));
document.addEventListener('visibilitychange', () => {
if (document.hidden && this.isSelecting) {
this.cancelSelection();
}
});
Show full message · 573 lines Assistant2024-12-03 06:52 UTC Copy response
Copy first prompt
Details
Provider OpenAI
Model provenance As recorded by source dataset
Turns 1 (2 messages)
Language en
Conversation date Dec 3, 2024
Added to archive Nov 16, 2026
ID 01m7h42ajhdbg1q7fwn9vzm89rSource & license Imported from WildChat-4.8M (AI2) (source ). Imported records earn no Research Points.
Upstream record: 67a16a39250a351a3399b89437f7297c
Zhao et al., WildChat: 1M ChatGPT Interaction Logs in the Wild (ICLR 2024). Contains information from WildChat-4.8M, made available under the ODC Attribution License.
License: ODC-BY-1.0
cancelSelection() {
this.isSelecting = false;
this.selectedLinks.clear();
this.selectionBox.style.display = 'none';
this.counter.style.display = 'none';
if (this.scrollInterval) {
clearInterval(this.scrollInterval);
this.scrollInterval = null;
}
document.querySelectorAll('.link-highlight').forEach(el => {
el.classList.remove('link-highlight');
});
}
handleMouseDown(e) {
if (this.activeModifierKey && e.button === this.settings.mouseButton) {
console.log('Selection started');
this.isSelecting = true;
this.startX = e.pageX;
this.startY = e.pageY;
this.initialScrollY = window.scrollY;
this.lastMouseX = e.pageX;
this.lastMouseY = e.pageY;
code Copy code
this.selectionBox.style.display = 'block';
this.counter.style.display = 'block';
e.preventDefault();
}
handleMouseMove(e) {
if (!this.isSelecting || !this.activeModifierKey) {
if (this.isSelecting) {
this.cancelSelection();
}
return;
}
code Copy code
this.lastMouseX = e.pageX;
this.lastMouseY = e.pageY;
const currentScrollY = window.scrollY;
const scrollDiff = currentScrollY - this.initialScrollY;
const rect = {
left: Math.min(this.startX, e.pageX),
top: Math.min(this.startY, e.pageY + scrollDiff),
width: Math.abs(e.pageX - this.startX),
height: Math.abs((e.pageY + scrollDiff) - this.startY)
};
this.selectionBox.style.left = `${rect.left}px`;
this.selectionBox.style.top = `${rect.top}px`;
this.selectionBox.style.width = `${rect.width}px`;
this.selectionBox.style.height = `${rect.height}px`;
this.highlightLinks(rect);
const viewportRect = {
left: rect.left - window.scrollX,
top: rect.top - window.scrollY,
width: rect.width,
height: rect.height
};
this.counter.style.left = `${viewportRect.left + viewportRect.width - 50}px`;
this.counter.style.top = `${viewportRect.top + viewportRect.height - 20}px`;
this.counter.textContent = `${this.selectedLinks.size}`;
this.handleAutoScroll(e);
handleAutoScroll(e) {
const scrollThreshold = 50;
const scrollSpeed = 10;
const viewportHeight = window.innerHeight;
code Copy code
if (this.scrollInterval) {
clearInterval(this.scrollInterval);
this.scrollInterval = null;
}
if (e.clientY > viewportHeight - scrollThreshold) {
this.scrollInterval = setInterval(() => {
window.scrollBy(0, scrollSpeed);
this.handleMouseMove({
pageX: this.lastMouseX,
pageY: this.lastMouseY,
clientY: this.lastMouseY - window.scrollY
});
}, 16);
} else if (e.clientY < scrollThreshold) {
this.scrollInterval = setInterval(() => {
window.scrollBy(0, -scrollSpeed);
this.handleMouseMove({
pageX: this.lastMouseX,
pageY: this.lastMouseY,
clientY: this.lastMouseY - window.scrollY
});
}, 16);
}
highlightLinks(rect) {
const links = this.getSelectableElements();
this.selectedLinks.clear();
code Copy code
links.forEach(element => {
const elementRect = element.getBoundingClientRect();
const absoluteElementRect = {
left: elementRect.left + window.scrollX,
right: elementRect.right + window.scrollX,
top: elementRect.top + window.scrollY,
bottom: elementRect.bottom + window.scrollY
};
if (this.checkIntersection(rect, absoluteElementRect)) {
const url = this.getElementUrl(element);
if (url) {
this.selectedLinks.add(url);
element.classList.add('link-highlight');
}
} else {
element.classList.remove('link-highlight');
}
});
getSelectableElements() {
return [
...document.querySelectorAll('a'),
...document.querySelectorAll('.shopee-search-item-result__item'),
...document.querySelectorAll('.justify-between.flex-col.flex.flex-1.p-2')
];
}
checkIntersection(selectionRect, elementRect) {
return !(
elementRect.left > selectionRect.left + selectionRect.width ||
elementRect.right < selectionRect.left ||
elementRect.top > selectionRect.top + selectionRect.height ||
elementRect.bottom < selectionRect.top
);
}
getElementUrl(element) {
if (element.href) return element.href;
const link = element.querySelector('a');
return link?.href || null;
}
handleMouseUp(e) {
if (!this.isSelecting) return;
code Copy code
if (this.activeModifierKey) {
this.openSelectedLinks();
}
this.cleanup();
openSelectedLinks() {
const uniqueUrls = new Set();
this.selectedLinks.forEach(url => {
if (this.isValidUrl(url)) {
uniqueUrls.add(url);
}
});
code Copy code
uniqueUrls.forEach(url => {
window.open(url, '_blank');
});
isValidUrl(url) {
try {
new URL(url);
return true;
} catch {
return false;
}
}
cleanup() {
this.isSelecting = false;
this.selectedLinks.clear();
this.selectionBox.style.display = 'none';
this.counter.style.display = 'none';
code Copy code
if (this.scrollInterval) {
clearInterval(this.scrollInterval);
this.scrollInterval = null;
}
document.querySelectorAll('.link-highlight').forEach(el => {
el.classList.remove('link-highlight');
});
updateStyles() {
const style = document.createElement('style');
style.textContent = `
.selection-box {
position: absolute;
border: t h i s . s e t t i n g s . b o r d e r S i z e p x s o l i d {this.settings.borderSize}px solid t hi s . se tt in g s . b or d er S i z e p x so l i d {this.settings.outlineColor};
background-color: rgba(255, 255, 0, 0.1);
pointer-events: none;
z-index: 10000;
}
code Copy code
.link-highlight {
outline: ${this.settings.borderSize}px solid ${this.settings.linkColor} !important;
outline-offset: 2px;
transition: outline 0.1s ease;
}
.selection-counter {
position: fixed;
background-color: white;
color: black;
padding: 4px 8px;
border-radius: 4px;
font-size: 12px;
font-weight: bold;
box-shadow: 0 2px 4px rgba(0,0,0,0.2);
z-index: 10001;
pointer-events: none;
}
`;
const existingStyle = document.getElementById('link-selector-styles');
if (existingStyle) {
existingStyle.remove();
}
style.id = 'link-selector-styles';
document.head.appendChild(style);
async loadSettings() {
try {
const result = await chrome.storage.sync.get('settings');
if (result.settings) {
this.settings = { ...this.settings, ...result.settings };
}
} catch (error) {
console.error('Failed to load settings:', error);
}
}
updateSettings(newSettings) {
this.settings = { ...this.settings, ...newSettings };
this.updateStyles();
console.log('Settings updated:', this.settings);
}
}
// Initialize the extension with debug logging
try {
console.log('Initializing LinkSelector...');
const linkSelector = new LinkSelector();
// Add window resize handler
window.addEventListener('resize', () => {
if (linkSelector.isSelecting) {
const rect = {
left: Math.min(linkSelector.startX, linkSelector.lastMouseX),
top: Math.min(linkSelector.startY, linkSelector.lastMouseY + (window.scrollY - linkSelector.initialScrollY)),
width: Math.abs(linkSelector.lastMouseX - linkSelector.startX),
height: Math.abs((linkSelector.lastMouseY + (window.scrollY - linkSelector.initialScrollY)) - linkSelector.startY)
};
code Copy code
linkSelector.selectionBox.style.left = `${rect.left}px`;
linkSelector.selectionBox.style.top = `${rect.top}px`;
linkSelector.selectionBox.style.width = `${rect.width}px`;
linkSelector.selectionBox.style.height = `${rect.height}px`;
linkSelector.highlightLinks(rect);
}
// Listen for settings updates
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.type === 'settingsUpdated') {
console.log('Received settings update:', message.settings);
linkSelector.updateSettings(message.settings);
}
});
console.log('LinkSelector initialized successfully');
} catch (error) {
console.error('Failed to initialize LinkSelector:', error);
}" , popup.js "document.addEventListener('DOMContentLoaded', async () => {
// Load saved settings
const result = await chrome.storage.sync.get('settings');
const settings = result.settings || {
modifierKey: 'Control',
mouseButton: 0,
outlineColor: '#ffff00',
linkColor: '#0000ff',
borderSize: 4
};
code Copy code
// Initialize form values
document.getElementById('modifierKey').value = settings.modifierKey;
document.getElementById('mouseButton').value = settings.mouseButton.toString();
document.getElementById('outlineColor').value = settings.outlineColor;
document.getElementById('linkColor').value = settings.linkColor;
document.getElementById('borderSize').value = settings.borderSize;
// Save settings handler
document.getElementById('saveSettings').addEventListener('click', async () => {
const newSettings = {
modifierKey: document.getElementById('modifierKey').value,
mouseButton: parseInt(document.getElementById('mouseButton').value),
outlineColor: document.getElementById('outlineColor').value,
linkColor: document.getElementById('linkColor').value,
borderSize: parseInt(document.getElementById('borderSize').value)
};
console.log('Saving settings:', newSettings);
try {
await chrome.storage.sync.set({ settings: newSettings });
// Update active tab
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
if (tab) {
chrome.tabs.sendMessage(tab.id, {
type: 'settingsUpdated',
settings: newSettings
});
}
// Show save confirmation
const saveButton = document.getElementById('saveSettings');
const originalText = saveButton.textContent;
saveButton.textContent = 'Saved!';
saveButton.style.backgroundColor = '#45a049';
setTimeout(() => {
saveButton.textContent = originalText;
saveButton.style.backgroundColor = '#4CAF50';
}, 1000);
} catch (error) {
console.error('Error saving settings:', error);
alert('Failed to save settings. Please try again.');
}
});
});" , styles.css ".selection-box {
position: absolute;
background: transparent;
pointer-events: none;
z-index: 10000;
box-sizing: border-box;
}
.link-highlight {
transition: outline 0.1s ease;
}
.selection-counter {
position: absolute;
background: white;
color: black;
padding: 4px 8px;
border-radius: 4px;
font-size: 12px;
z-index: 10001;
box-shadow: 0 2px 5px rgba(0,0,0,0.2);
user-select: none;
}
/* Popup Styles */
.popup-container {
width: 300px;
padding: 16px;
}
.setting-row {
margin-bottom: 16px;
}
.setting-row label {
display: block;
margin-bottom: 4px;
font-weight: 500;
}
.setting-row input,
.setting-row select {
width: 100%;
padding: 6px;
border: 1px solid #ccc;
border-radius: 4px;
}
body {
position: relative;
}
.selection-box {
position: fixed !important;
pointer-events: none !important;
}
.selection-counter {
position: fixed !important;
pointer-events: none !important;
}
.link-highlight {
position: relative;
z-index: 1;
}" ,popup.html "
code Copy code
<div class="setting-row">
<label for="mouseButton">Mouse Button</label>
<select id="mouseButton">
<option value="0">Left</option>
<option value="1">Middle</option>
<option value="2">Right</option>
</select>
</div>
<div class="setting-row">
<label for="outlineColor">Selection Color</label>
<input type="color" id="outlineColor" value="#ffff00">
</div>
<div class="setting-row">
<label for="linkColor">Highlight Color</label>
<input type="color" id="linkColor" value="#0000ff">
</div>
<div class="setting-row">
<label for="borderSize">Border Size (px)</label>
<input type="number" id="borderSize" min="1" max="10" value="4">
</div>
<button id="saveSettings" class="save-button">Save Settings</button>
</div>
<script src="popup.js"></script>
It sounds like you're experiencing issues with your Chrome/Edge extension where the selection box and link highlights are not appearing correctly on some sites, especially when dragging down. Additionally, you mentioned that the selection area moves with the screen instead of staying fixed at the start of the drag.
Explanation of the Issues:
Conflict Between CSS and JavaScript Positioning:
In your JavaScript code , you set the position of the selectionBox and counter elements to absolute:
javascript Copy code
this.selectionBox.style.position = 'absolute';
// ...
this.counter.style.position = 'fixed';
However, in your styles.css file , you have a rule that overrides this with !important:
css Copy code
.selection-box {
position: fixed !important;
pointer-events: none !important;
}
.selection-counter {
position: fixed !important;
pointer-events: none !important;
}
This inconsistency causes the selectionBox to be positioned relative to the viewport (fixed) instead of relative to the document (absolute), leading to incorrect positioning, especially when scrolling.
Because the selectionBox is being positioned using document coordinates (pageX, pageY), but styled with position: fixed, it appears to move with the screen when you scroll.
Incorrect Coordinate Calculations:
In your handleMouseMove function, you're using pageX and pageY (which are document-relative coordinates) to position the selectionBox, but if the selectionBox is fixed, you should use viewport-relative coordinates like clientX and clientY.
Z-Index and Pointer Events Issues:
On some sites, the selectionBox or highlights might be covered by other elements due to z-index stacking contexts.
If other elements have higher z-index values or pointer-events: none, they might interfere with the visibility and interactivity of your selection elements.
Event Handling Conflicts:
Some sites might have event listeners that interfere with your extension's event handling, preventing your listeners from firing correctly.
If the site consumes the mousedown, mousemove, or mouseup events, your handlers might not execute as expected.
Steps to Fix the Problems:
Ensure Consistent Positioning Between CSS and JavaScript:
Remove or Adjust the CSS that Forces position: fixed:
Remove the position: fixed !important; rules from your styles.css:
css Copy code
.selection-box {
/* Remove position: fixed !important; */
pointer-events: none !important;
}
.selection-counter {
/* Remove position: fixed !important; */
pointer-events: none !important;
}
This will allow the selectionBox and counter to use the positions set in your JavaScript code.
Adjust JavaScript to Use Correct Coordinates if Using Fixed Positioning:
If you prefer to use position: fixed, you should modify your coordinate calculations to use clientX and clientY (viewport-relative coordinates) instead of pageX and pageY.
However, it's generally simpler and more compatible to use position: absolute for elements positioned with document-relative coordinates.
Increase Z-Index Values:
Ensure that your selectionBox and link highlights have sufficiently high z-index values to appear above other page elements:
css Copy code
.selection-box {
z-index: 999999;
}
.link-highlight {
position: relative;
z-index: 999998;
}
This helps prevent other elements from covering your selection box and highlights.
Handle Scrolling Correctly:
Since you're using position: absolute, you need to account for the scrolling offset when positioning the selectionBox.
In your handleMouseMove function, adjust your calculations to consider window.scrollX and window.scrollY if needed.
Check for Event Interference:
Some websites may cancel the default behavior of events or use event capture. To ensure your event listeners run, consider adding them with .
Summary:
The primary issue is the inconsistency in the positioning of your selectionBox and counter elements between your JavaScript and CSS.
By ensuring that these elements are consistently set to position: absolute and that their positions are calculated correctly with respect to scrolling, you can fix the selection area moving incorrectly.
Adjusting the z-index and pointer events can help ensure that the selection box and link highlights appear above other content.
Handling events with capture can help prevent websites from interfering with your extension's functionality.
Please apply these fixes and test your extension again. Let me know if you need further assistance or if any issues remain after making these changes.
Copy first response
Not yet included in a published release.
{ capture: true }
Example:
javascript Copy code
document.addEventListener('mousedown', (e) => this.handleMouseDown(e), { capture: true });
document.addEventListener('mousemove', (e) => this.handleMouseMove(e), { capture: true });
document.addEventListener('mouseup', (e) => this.handleMouseUp(e), { capture: true });
Ensure Elements Are Appended to document.documentElement:
Instead of appending your selectionBox and counter to document.body, append them to document.documentElement. This can help avoid some layout issues.
javascript Copy code
document.documentElement.appendChild(this.selectionBox);
document.documentElement.appendChild(this.counter);
Test on Different Sites:
Try your extension on multiple sites to ensure compatibility.
If issues persist on specific sites, inspect those sites to see if they have conflicting CSS or JavaScript that needs to be handled.