this.isSelecting = false;
this.startX = 0;
this.startY = 0;
this.selectedLinks = new Set();
this.selectionBox = null;
this.counter = null;
this.scrollAnimationFrame = null;
this.initialScrollY = 0;
this.lastMouseX = 0;
this.lastMouseY = 0;
this.highlightTimeout = null;
this.currentRect = null;
this.selectableElements = [];
this.activeModifierKey = false; // Track modifier key state
this.mouseButtonDown = false; // Track mouse button state
this.settings = {
outlineColor: '#ff0000', // Red color for selection box border
linkColor: '#0000ff',
borderSize: 4
};
this.init();
}
async init() {
await this.loadSettings();
this.createElements();
this.attachEventListeners();
this.updateStyles();
console.log('LinkSelector initialized');
}
createElements() {
if (!document.getElementById('link-selector-selection-box')) {
this.selectionBox = document.createElement('div');
this.selectionBox.id = 'link-selector-selection-box';
this.selectionBox.className = 'selection-box';
this.selectionBox.style.display = 'none';
this.selectionBox.style.position = 'absolute';
this.selectionBox.style.pointerEvents = 'none';
this.selectionBox.style.zIndex = '2147483647';
this.selectionBox.style.boxSizing = 'border-box';
// Set border style to dashed
this.selectionBox.style.border = `${this.settings.borderSize}px dashed ${this.settings.outlineColor}`;
this.selectionBox.style.backgroundColor = 'transparent'; // Make inside transparent
document.documentElement.appendChild(this.selectionBox);
} else {
this.selectionBox = document.getElementById('link-selector-selection-box');
}
if (!document.getElementById('link-selector-counter')) {
this.counter = document.createElement('div');
this.counter.id = 'link-selector-counter';
this.counter.className = 'selection-counter';
this.counter.style.display = 'none';
this.counter.style.position = 'absolute';
this.counter.style.pointerEvents = 'none';
this.counter.style.zIndex = '2147483648'; // Ensure it appears above the selection box
// Append counter as a child of the selection box
this.selectionBox.appendChild(this.counter);
} else {
this.counter = document.getElementById('link-selector-counter');
}
}
attachEventListeners() {
if (!this.listenersAttached) {
this.keyDownHandler = (e) => this.handleKeyDown(e);
this.keyUpHandler = (e) => this.handleKeyUp(e);
this.mouseDownHandler = (e) => this.handleMouseDown(e);
this.mouseMoveHandler = (e) => this.handleMouseMove(e);
this.mouseUpHandler = (e) => this.handleMouseUp(e);
document.addEventListener('keydown', this.keyDownHandler);
document.addEventListener('keyup', this.keyUpHandler);
document.addEventListener('mousedown', this.mouseDownHandler, { capture: true });
document.addEventListener('mousemove', this.mouseMoveHandler, { capture: true });
document.addEventListener('mouseup', this.mouseUpHandler, { capture: true });
this.visibilityChangeHandler = () => {
if (document.hidden && this.isSelecting) {
this.cancelSelection();
}
};
document.addEventListener('visibilitychange', this.visibilityChangeHandler);
// Ensure listeners are only attached once
this.listenersAttached = true;
}
}
handleKeyDown(e) {
if (e.ctrlKey || e.altKey || e.shiftKey || e.metaKey) {
this.activeModifierKey = true;
}
}
handleKeyUp(e) {
if (!(e.ctrlKey || e.altKey || e.shiftKey || e.metaKey)) {
this.activeModifierKey = false;
if (this.isSelecting) {
this.cancelSelection();
}
}
}
cancelSelection() {
this.cleanup();
}
handleMouseDown(e) {
if (this.activeModifierKey) {
this.mouseButtonDown = true;
this.startX = e.pageX;
this.startY = e.pageY;
this.initialScrollY = window.scrollY;
this.lastMouseX = e.pageX;
this.lastMouseY = e.pageY;
// Do not start the selection yet
}
}
handleMouseMove(e) {
if (!this.mouseButtonDown || !this.activeModifierKey) {
if (this.isSelecting) {
this.cancelSelection();
}
return;
}
if (!this.isSelecting) {
// Calculate distance moved
const deltaX = e.pageX - this.startX;
const deltaY = e.pageY - this.startY;
const distanceSquared = deltaX * deltaX + deltaY * deltaY;
const threshold = 5 * 5; // 5 pixels threshold
if (distanceSquared >= threshold) {
// Distance threshold exceeded, start selection
this.startSelection(e);
} else {
// Distance not exceeded, do not start selection
return;
}
}
// Now proceed with updating selection
this.lastMouseX = e.pageX;
this.lastMouseY = e.pageY;
this.updateSelectionBox();
// Throttle the highlighting to every 16ms (~60fps)
if (this.highlightTimeout) {
clearTimeout(this.highlightTimeout);
}
this.highlightTimeout = setTimeout(() => {
this.highlightLinks(this.currentRect);
this.updateCounter();
}, 16);
this.handleAutoScroll(e);
}
startSelection(e) {
this.isSelecting = true;
// Initialize selection box dimensions to zero
this.updateSelectionBox();
this.selectionBox.style.display = 'block';
// Cache selectable elements
this.selectableElements = this.getSelectableElements();
// Prevent default behavior
e.preventDefault();
}
handleMouseUp(e) {
if (!this.mouseButtonDown) return;
this.mouseButtonDown = false;
if (this.isSelecting) {
if (this.activeModifierKey) {
this.openSelectedLinks();
}
this.cleanup();
} else {
// No selection was started, allow default behavior
// Do not prevent default
}
}
updateSelectionBox() {
const rect = {
left: Math.min(this.startX, this.lastMouseX),
top: Math.min(this.startY, this.lastMouseY),
width: Math.abs(this.lastMouseX - this.startX),
height: Math.abs(this.lastMouseY - this.startY)
};
this.currentRect = rect;
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`;
}
updateCounter() {
if (this.selectedLinks.size > 0) {
// Show the counter
this.counter.style.display = 'block';
this.counter.textContent = `${this.selectedLinks.size}`;
} else {
// Hide the counter when no links are selected
this.counter.style.display = 'none';
this.counter.textContent = '';
}
}
handleAutoScroll(e) {
const scrollThreshold = 50;
const scrollSpeed = 30;
const viewportHeight = window.innerHeight;
if (this.scrollAnimationFrame) {
cancelAnimationFrame(this.scrollAnimationFrame);
this.scrollAnimationFrame = null;
}
const autoScroll = () => {
if (!this.isSelecting) return;
const scrollDelta = e.clientY > viewportHeight - scrollThreshold
? scrollSpeed
: e.clientY < scrollThreshold
? -scrollSpeed
: 0;
if (scrollDelta !== 0) {
window.scrollBy(0, scrollDelta);
// Update mouse position and selection
this.lastMouseY += scrollDelta;
this.updateSelectionBox();
this.highlightLinks(this.currentRect);
this.updateCounter();
// Continue scrolling
this.scrollAnimationFrame = requestAnimationFrame(autoScroll);
}
};
// Start auto-scrolling if necessary
if (e.clientY > viewportHeight - scrollThreshold || e.clientY < scrollThreshold) {
this.scrollAnimationFrame = requestAnimationFrame(autoScroll);
}
}
highlightLinks(rect) {
if (!rect) return;
const links = this.selectableElements;
this.selectedLinks.clear();
links.forEach(element => {
try {
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');
// For images
const images = element.querySelectorAll('img');
images.forEach(img => {
img.classList.add('link-highlight-img');
});
}
} else if (element.classList.contains('link-highlight')) {
element.classList.remove('link-highlight');
const images = element.querySelectorAll('img');
images.forEach(img => {
img.classList.remove('link-highlight-img');
});
}
} catch (error) {
console.error('Error during highlightLinks:', error);
}
});
}
getSelectableElements() {
try {
return [
...document.querySelectorAll(`
a,
[role="link"],
[onclick],
[data-href],
[data-url],
[data-link],
.article-name,
.article-link,
.listingResult,
.ytd-video-renderer,
.yt-simple-endpoint,
[class*="link"],
[class*="Link"],
[class*="button"],
[class*="Button"],
li.shopee-search-item-result__item /* Add selector for Shopee items */
`)
];
} catch (error) {
console.error('Error getting selectable elements:', error);
return [];
}
}
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) {
try {
if (element.href) return element.href;
const urlAttributes = ['data-href', 'data-url', 'data-link'];
for (const attr of urlAttributes) {
if (element.getAttribute(attr)) {
return element.getAttribute(attr);
}
}
const link = element.querySelector('a');
return link?.href || null;
} catch (error) {
console.error('Error getting element URL:', error);
return null;
}
}
openSelectedLinks() {
const uniqueUrls = new Set();
this.selectedLinks.forEach(url => {
if (this.isValidUrl(url)) {
uniqueUrls.add(url);
}
});
if (uniqueUrls.size > 20) {
// Confirmation popup logic using window.confirm()
if (window.confirm(`You are about to open ${uniqueUrls.size} links. Are you sure?`)) {
// User clicked OK
this.openLinksInTabs(uniqueUrls);
} else {
// User clicked Cancel
// Do nothing
}
} else if (uniqueUrls.size > 0) {
// Open links directly if 20 or fewer
this.openLinksInTabs(uniqueUrls);
}
}
openLinksInTabs(uniqueUrls) {
// Open tabs next to the current tab without changing focus
chrome.runtime.sendMessage({ type: 'openLinks', links: Array.from(uniqueUrls) });
}
isValidUrl(url) {
try {
new URL(url);
return true;
} catch {
return false;
}
}
cleanup() {
this.isSelecting = false;
this.selectedLinks.clear();
// Hide and reset elements
if (this.selectionBox) {
this.selectionBox.style.display = 'none';
}
if (this.counter) {
this.counter.style.display = 'none';
this.counter.textContent = ''; // Clear counter content
}
this.currentRect = null;
this.startX = 0;
this.startY = 0;
this.lastMouseX = 0;
this.lastMouseY = 0;
this.initialScrollY = 0;
this.selectableElements = [];
if (this.scrollAnimationFrame) {
cancelAnimationFrame(this.scrollAnimationFrame);
this.scrollAnimationFrame = null;
}
if (this.highlightTimeout) {
clearTimeout(this.highlightTimeout);
this.highlightTimeout = null;
}
this.mouseButtonDown = false;
document.querySelectorAll('.link-highlight').forEach(el => {
el.classList.remove('link-highlight');
});
document.querySelectorAll('.link-highlight-img').forEach(img => {
img.classList.remove('link-highlight-img');
});
}
updateStyles() {
const styleId = 'link-selector-styles';
let style = document.getElementById(styleId);
if (!style) {
style = document.createElement('style');
style.id = styleId;
document.head.appendChild(style);
}
style.textContent = `
.selection-box {
position: absolute;
border: ${this.settings.borderSize}px dashed ${this.settings.outlineColor}; /* Dashed border */
background-color: transparent; /* Make inside transparent */
pointer-events: none;
z-index: 2147483647;
box-sizing: border-box;
}
.link-highlight {
z-index: 2147483646;
outline: ${this.settings.borderSize}px solid ${this.settings.linkColor};
outline-offset: -${this.settings.borderSize / 2}px;
}
.link-highlight * {
outline: none !important;
}
.link-highlight-img {
box-shadow: 0 0 0 ${this.settings.borderSize}px ${this.settings.linkColor};
}
.selection-counter {
position: absolute;
bottom: 0; /* Anchor to bottom */
right: 0; /* Anchor to right */
margin: 4px; /* Add some margin */
background-color: black;
color: white;
padding: 4px 8px;
border-radius: 4px;
font-size: 18px;
font-weight: bold;
box-shadow: 0 2px 4px rgba(0,0,0,0.2);
pointer-events: none;
}
`;
}
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();
// Update existing selectionBox styles
if (this.selectionBox) {
this.selectionBox.style.border = `${this.settings.borderSize}px dashed ${this.settings.outlineColor}`;
this.selectionBox.style.backgroundColor = 'transparent';
}
console.log('Settings updated:', this.settings);
}
// Clean up on page unload
window.addEventListener('beforeunload', () => {
if (LinkSelector.instance) {
LinkSelector.instance.cleanup();
}
});
}" ,there is problem with when hold modifier key + hold left mouse it does not prevent select text so when user hold both key and drag it select text too ,fix this and show complete update code.
// Check if LinkSelector is already initialized
if (!window.linkSelectorInitialized) {
window.linkSelectorInitialized = true;
class LinkSelector {
constructor() {
// Singleton instance
if (LinkSelector.instance) {
return LinkSelector.instance;
}
LinkSelector.instance = this;
this.isSelecting = false;
this.startX = 0;
this.startY = 0;
this.selectedLinks = new Set();
this.selectionBox = null;
this.counter = null;
this.scrollAnimationFrame = null;
this.initialScrollY = 0;
this.lastMouseX = 0;
this.lastMouseY = 0;
this.highlightTimeout = null;
this.currentRect = null;
this.selectableElements = [];
this.activeModifierKey = false; // Track modifier key state
this.mouseButtonDown = false; // Track mouse button state
this.settings = {
outlineColor: '#ff0000', // Red color for selection box border
linkColor: '#0000ff',
borderSize: 4
};
this.init();
}
async init() {
await this.loadSettings();
this.createElements();
this.attachEventListeners();
this.updateStyles();
console.log('LinkSelector initialized');
}
// ... (other methods)
startSelection(e) {
this.isSelecting = true;
// Initialize selection box dimensions to zero
this.updateSelectionBox();
this.selectionBox.style.display = 'block';
// Cache selectable elements
this.selectableElements = this.getSelectableElements();
// Prevent default behavior
e.preventDefault();
// Disable text selection
document.body.style.userSelect = 'none';
document.body.style.webkitUserSelect = 'none';
document.body.style.msUserSelect = 'none';
}
// ... (other methods)
cleanup() {
this.isSelecting = false;
this.selectedLinks.clear();
// Hide and reset elements
if (this.selectionBox) {
this.selectionBox.style.display = 'none';
}
if (this.counter) {
this.counter.style.display = 'none';
this.counter.textContent = ''; // Clear counter content
}
this.currentRect = null;
this.startX = 0;
this.startY = 0;
this.lastMouseX = 0;
this.lastMouseY = 0;
this.initialScrollY = 0;
this.selectableElements = [];
if (this.scrollAnimationFrame) {
cancelAnimationFrame(this.scrollAnimationFrame);
this.scrollAnimationFrame = null;
}
if (this.highlightTimeout) {
clearTimeout(this.highlightTimeout);
this.highlightTimeout = null;
}
this.mouseButtonDown = false;
document.querySelectorAll('.link-highlight').forEach(el => {
el.classList.remove('link-highlight');
});
document.querySelectorAll('.link-highlight-img').forEach(img => {
img.classList.remove('link-highlight-img');
});
// Restore text selection
document.body.style.userSelect = '';
document.body.style.webkitUserSelect = '';
document.body.style.msUserSelect = '';
}
// ... (other methods)
}
// Initialize the extension
try {
console.log('Initializing LinkSelector...');
const linkSelector = new LinkSelector();
// Add window resize handler
window.addEventListener('resize', () => {
if (linkSelector.isSelecting) {
linkSelector.updateSelectionBox();
linkSelector.highlightLinks(linkSelector.currentRect);
linkSelector.updateCounter();
}
});
// Listen for messages
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.type === 'ping') {
sendResponse({ status: 'alive' });
return true;
}
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);
}
// Clean up on page unload
window.addEventListener('beforeunload', () => {
if (LinkSelector.instance) {
LinkSelector.instance.cleanup();
}
});
}