Extension Overview
This extension enhances web browsing by allowing users to select an area on a webpage using a specific trigger (holding the Alt key and the left mouse button while dragging). Within this selection area:
- A red dashed rectangular border is displayed to represent the selection.
- All clickable links (including those specified by user-defined selectors) within this area are highlighted with a blue dashed border.
- The number of links in the selection is displayed in the bottom-right corner of the selection area.
Depending on how the user releases the keys and mouse button:
- Releasing the
Alt key first cancels the selection without any action.
- Releasing the left mouse button while still holding
Alt opens all unique links within the selection in new background tabs to the right of the current tab. If there are more than 20 links, a confirmation dialog appears.
Additional features include:
- An options page where users can specify additional CSS selectors to identify links.
- Auto-save of changes made in the options page.
- Smooth auto-scrolling when dragging the selection area to the edges of the viewport.
File Structure
manifest.json - Defines the extension's metadata and permissions.
contentScript.js - Contains the logic for handling user interactions on web pages.
options.html - Provides the user interface for the extension's options page.
options.js - Handles the logic for saving and loading options.
styles.css - Contains the styling for the selection area and link highlights.
1. manifest.json
This file configures the extension, specifying permissions, scripts to run, and other metadata.
{
"manifest_version": 3,
"name": "Link Selection Extension",
"version": "1.0",
"description": "Select and open multiple links by drawing a selection rectangle.",
"permissions": ["storage", "tabs", "activeTab", "scripting"],
"host_permissions": ["<all_urls>"],
"action": {
"default_title": "Link Selection Extension",
"default_popup": "options.html"
},
"icons": {
"16": "icons/icon16.png",
"32": "icons/icon32.png",
"48": "icons/icon48.png",
"128": "icons/icon128.png"
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["contentScript.js"]
}
],
"options_ui": {
"page": "options.html",
"open_in_tab": false
}
}
- Permissions:
"storage": To save user-defined selectors.
"tabs" and "activeTab": To open new tabs next to the current one.
"scripting": To inject scripts if needed.
- Content Scripts:
contentScript.js runs on all web pages to handle the selection logic.
- Options UI: Points to
options.html for configuring user options.
2. contentScript.js
This script manages user interactions on web pages, including drawing the selection area, highlighting links, and opening links.
// contentScript.js
(async () => {
// Load user-defined selectors from storage
let { customSelectors } = await chrome.storage.sync.get("customSelectors");
if (!customSelectors) {
// Default selectors if none are set
customSelectors = `
li.shopee-search-item-result__item .article-name,
.article-link,
##li.shopee-search-item-result__item.col-xs-2-4:nth-of-type(6),
##li.shopee-search-item-result__item.col-xs-2-4:nth-of-type(5),
##.text-sm.min-h-[2\\.5rem].break-words.line-clamp-2
`.trim();
await chrome.storage.sync.set({ customSelectors });
}
const customSelectorList = customSelectors
.split(',')
.map(sel => sel.trim())
.filter(Boolean);
let isAltPressed = false;
let isMouseDown = false;
let startX, startY;
let selectionBox;
let linkCountLabel;
let highlightedLinks = new Set();
let scrollInterval;
// Create styles for the selection and highlights
const style = document.createElement('style');
style.textContent = `
.selection-box {
position: absolute;
border: 4px dashed red;
background: rgba(255, 0, 0, 0.1);
pointer-events: none;
z-index: 999999;
}
.link-highlight {
border: 4px dashed blue !important;
}
.link-count-label {
position: absolute;
background: black;
color: white;
font-size: 18px;
padding: 2px 5px;
pointer-events: none;
z-index: 1000000;
}
`;
document.head.appendChild(style);
// Function to start the selection
function startSelection(event) {
if (event.altKey && event.button === 0 && !isMouseDown) {
isMouseDown = true;
startX = event.clientX;
startY = event.clientY;
selectionBox = document.createElement('div');
selectionBox.classList.add('selection-box');
document.body.appendChild(selectionBox);
linkCountLabel = document.createElement('div');
linkCountLabel.classList.add('link-count-label');
document.body.appendChild(linkCountLabel);
highlightedLinks.clear();
updateSelection(event);
// Start auto-scrolling
scrollInterval = setInterval(autoScroll, 50);
}
}
// Function to update the selection area
function updateSelection(event) {
if (!isMouseDown || !selectionBox) return;
let currentX = event.clientX;
let currentY = event.clientY;
const rect = {
left: Math.min(startX, currentX),
top: Math.min(startY, currentY),
width: Math.abs(startX - currentX),
height: Math.abs(startY - currentY)
};
// Update selection box position and size
selectionBox.style.left = `${rect.left + window.scrollX}px`;
selectionBox.style.top = `${rect.top + window.scrollY}px`;
selectionBox.style.width = `${rect.width}px`;
selectionBox.style.height = `${rect.height}px`;
// Position the link count label
linkCountLabel.style.left = `${rect.left + rect.width - 50 + window.scrollX}px`;
linkCountLabel.style.top = `${rect.top + rect.height - 30 + window.scrollY}px`;
// Highlight links within the selection
highlightLinks(rect);
}
// Function to highlight links in the selection
function highlightLinks(rect) {
// Remove previous highlights
document.querySelectorAll('.link-highlight').forEach(el => {
el.classList.remove('link-highlight');
});
highlightedLinks.clear();
// Get all potential link elements
let linkElements = Array.from(document.querySelectorAll('a, area, [onclick], button, input[type="button"], input[type="submit"]'));
// Include custom selectors
customSelectorList.forEach(selector => {
if (selector.startsWith('##')) {
// If starts with ##, select the element itself
const elements = document.querySelectorAll(selector.slice(2));
elements.forEach(el => {
if (!linkElements.includes(el)) {
linkElements.push(el);
}
});
} else {
const elements = document.querySelectorAll(selector);
elements.forEach(el => {
// Add parent links if any
const linkAncestor = el.closest('a, area');
if (linkAncestor && !linkElements.includes(linkAncestor)) {
linkElements.push(linkAncestor);
} else if (!linkElements.includes(el)) {
linkElements.push(el);
}
});
}
});
linkElements.forEach(link => {
const linkRect = link.getBoundingClientRect();
if (
linkRect.bottom > rect.top &&
linkRect.top < rect.top + rect.height &&
linkRect.right > rect.left &&
linkRect.left < rect.left + rect.width
) {
link.classList.add('link-highlight');
highlightedLinks.add(link.href || link.getAttribute('href') || link);
}
});
// Update the link count
linkCountLabel.textContent = highlightedLinks.size;
}
// Function to clear the selection
function clearSelection() {
if (selectionBox) {
selectionBox.remove();
selectionBox = null;
}
if (linkCountLabel) {
linkCountLabel.remove();
linkCountLabel = null;
}
document.querySelectorAll('.link-highlight').forEach(el => {
el.classList.remove('link-highlight');
});
highlightedLinks.clear();
if (scrollInterval) {
clearInterval(scrollInterval);
scrollInterval = null;
}
isMouseDown = false;
}
// Function to handle mouse up event
function endSelection(event) {
if (isMouseDown && isAltPressed) {
// Open links if left mouse button is released while holding Alt
openLinks();
}
clearSelection();
}
// Function to open links
function openLinks() {
if (highlightedLinks.size === 0) return;
const uniqueLinks = new Set();
const linkList = [];
highlightedLinks.forEach(link => {
if (typeof link === 'string' && !uniqueLinks.has(link)) {
uniqueLinks.add(link);
linkList.push(link);
} else if (link instanceof HTMLElement && !uniqueLinks.has(link)) {
uniqueLinks.add(link);
linkList.push(link);
}
});
if (linkList.length > 20) {
if (!confirm(`You are about to open ${linkList.length} links. Do you want to proceed?`)) {
return;
}
}
// Open each link in a new tab next to the current one
chrome.runtime.sendMessage({ links: linkList });
}
// Auto-scrolling function
function autoScroll() {
const scrollMargin = 50;
const maxScrollSpeed = 20;
const mouseY = window.event.clientY;
const windowHeight = window.innerHeight;
if (mouseY < scrollMargin) {
window.scrollBy(0, -maxScrollSpeed);
} else if (mouseY > windowHeight - scrollMargin) {
window.scrollBy(0, maxScrollSpeed);
}
// Update selection while scrolling
updateSelection(window.event);
}
// Event listeners
document.addEventListener('mousedown', startSelection);
document.addEventListener('mousemove', updateSelection);
document.addEventListener('mouseup', endSelection);
document.addEventListener('keydown', (event) => {
if (event.key === 'Alt') {
isAltPressed = true;
}
});
document.addEventListener('keyup', (event) => {
if (event.key === 'Alt') {
isAltPressed = false;
clearSelection();
}
});
// Clean up on page unload
window.addEventListener('beforeunload', () => {
clearSelection();
});
})();
Explanation:
- The script uses an immediately invoked function expression (IIFE) to prevent global namespace pollution.
- It loads custom selectors from
chrome.storage.sync. If none are set, it initializes them with default selectors.
- Event listeners are added to handle mouse and keyboard events:
mousedown: Initiates selection if Alt is pressed and the left mouse button is clicked.
mousemove: Updates the selection area and highlights links.
mouseup: Ends selection and opens links if conditions are met.
keydown and keyup: Track the Alt key state.
- The
highlightLinks function identifies all clickable elements within the selection area, including those matching user-defined selectors.
- The
openLinks function sends a message to the background script to open links in new tabs.
- The
autoScroll function scrolls the page when the mouse is near the edges during selection.
3. background.js
This script handles opening the links in new tabs next to the current tab without changing focus.
// background.js
chrome.runtime.onMessage.addListener((message, sender) => {
if (message.links && message.links.length > 0) {
const currentTabId = sender.tab.id;
const links = message.links;
const uniqueUrls = links
.map(link => (typeof link === 'string' ? link : link.href))
.filter(url => url && url.startsWith('http'))
.filter((value, index, self) => self.indexOf(value) === index); // Remove duplicates
chrome.tabs.query({ currentWindow: true }, tabs => {
// Find the index of the current tab
const currentTabIndex = tabs.find(tab => tab.id === currentTabId).index;
let indexOffset = 1;
uniqueUrls.forEach(url => {
chrome.tabs.create({
url: url,
active: false,
index: currentTabIndex + indexOffset
});
indexOffset++;
});
});
}
});
Explanation:
- Listens for messages from the content script.
- Receives an array of links to open.
- Filters out duplicate URLs and ensures they start with
http or https.
- Uses
chrome.tabs.create to open each link in a new background tab next to the current tab.
4. options.html
Provides a simple interface for users to input custom selectors.
<!-- options.html -->
<!DOCTYPE html>
<html>
<head>
<title>Extension Options</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
textarea {
width: 100%;
height: 150px;
}
label {
display: block;
margin-bottom: 5px;
font-weight: bold;
}
.status {
margin-top: 10px;
color: green;
}
</style>
</head>
<body>
<h1>Extension Options</h1>
<label for="selectors">Custom Link Selectors (one per line):</label>
<textarea id="selectors"></textarea>
<div class="status" id="status"></div>
<script src="options.js"></script>
</body>
</html>
5. options.js
Handles saving and loading of custom selectors.
// options.js
document.addEventListener('DOMContentLoaded', () => {
const selectorsTextarea = document.getElementById('selectors');
const statusDiv = document.getElementById('status');
// Load saved selectors
chrome.storage.sync.get('customSelectors', data => {
selectorsTextarea.value = data.customSelectors || '';
});
// Save selectors on change
selectorsTextarea.addEventListener('input', () => {
const customSelectors = selectorsTextarea.value;
chrome.storage.sync.set({ customSelectors }, () => {
statusDiv.textContent = 'Options saved.';
setTimeout(() => {
statusDiv.textContent = '';
}, 2000);
});
});
});
Explanation:
- When the options page loads, it retrieves the saved custom selectors and displays them in the textarea.
- When the user modifies the textarea, the changes are automatically saved to
chrome.storage.sync.
- A brief status message is displayed to confirm the save.
6. styles.css
Although styles are included in the contentScript.js and options.html, if you prefer to have a separate CSS file, you can include it and reference it accordingly.
Additional Notes:
- Auto-Scroll Functionality: The
autoScroll function in the content script ensures smooth scrolling when the mouse is dragged to the top or bottom edges during selection.
- Duplicate Links: The script avoids opening duplicate links by using a
Set to store unique URLs.
- Confirmation Dialog: If more than 20 links are selected, a confirmation dialog is displayed before opening them.
- Opening Tabs Without Focus: The background script opens new tabs without changing the active tab, preserving the user's context.
- Selectors: Custom selectors can target elements directly (
##selector) or their descendants. The default selectors provided in the options are tailored for Shopee's website as per your requirement.
- Edge Compatibility: The code is compatible with both Chrome and Edge browsers supporting Manifest V3.
Icons
Include icon files in the icons directory with sizes specified in manifest.json. These are optional but recommended for a professional-looking extension.
Final Steps
- Testing: Before publishing, load the unpacked extension in your browser to test all functionalities.
- Permissions: Ensure that the extension requests only the necessary permissions to maintain user trust.
- Publishing: Follow the Chrome Web Store and Edge Add-ons store guidelines for publishing extensions.
Disclaimer: Always test your extension thoroughly to ensure it works as expected and complies with all relevant browser policies and guidelines.