Create a manifest V3 code for an Edge and Chrome extension with the following…
- User
Create a manifest V3 code for an Edge and Chrome extension with the following functionality:
Functionality Overview: Trigger Shortcut:
When the user holds the Alt key first and then holds the left mouse button (prevents text selection when holding alt key and hold left mouse), and then dragging the mouse will display a rectangular dot selection area with a yellow border with a border size of 4 (transparent inside, only the border has color).
Highlight Links:
All clickable links (such as image links or text links) within the selection area will have a blue border (transparent inside, only the border has color) with a border size of 4.
Link Count Display:
The number of links within the selection area will be displayed in the bottom-right corner of the selection area with a black background and white text (text size 18).
Link Opening Behavior:
If the user releases the Alt key first, the selection area is canceled without opening any links.
If the user releases the left mouse button while holding the Alt key (rules of open link), all links within the selection area will open in new tabs from the current tab.
Extension Options:
An option to add elements to detect links within input boxes (in format like "li.shopee-search-item-result__item .article-name, .article-link," also add that into inputbox by default and make sure it will work with that element ) and for example link in shopee grid item "##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" ,for ##li.shopee-search-item-result__item.col-xs-2-4:nth-of-type(this part can be different) ,make sure it will by default with this element, and when user select and drag over that add element and release left mouse (match rules of open link) it will open that add element too (it show highlights and open link).
Auto-save changes to the extension's options.
Script Execution: The script is activated when both the trigger keys (Alt and left mouse button) are held down.
The selection area appears while dragging the mouse (it will show from when first mouse drag and maintain that point until user release alt key ,it will not repeat show old value area).
Releasing the Alt key cancels the selection area (make sure it will not show same selection area if user release alt key it should show only if user hold alt and hold left mouse and drag it will always show area where left mouse is first hold and drag from that not just hold or click both alt and left mouse but drag too).
Opening Tabs to the Right of the Current Tab: When the user releases the left mouse button while holding the Alt key, the extension should open all unique links within the selection area in new tabs to the right of the current tab, preserving tab order and without change tab focus (the browser will try to switch tab to newly open link ,make sure it does not switch tab ,active tab is be the same when open new tab link) and if link open more then 20 link show dialog confirm if user click ok will open all link, and it will not count and open duplicate link.
and when user hold alt + hold left mouse and drag to top or bottom edge it will auto scroll down at bottom or up at the top while selection area still update and cover more link (make it smooth scrolling and fast).
,make sure user hold alt + hold left mouse (more then 300ms) to trigger prevent text selection and allow drag to show selection area.
,explain first then show complete code.
- Assistant
To create an Edge and Chrome extension with the specified functionality, we'll build an extension using Manifest V3 that includes a content script, background script, and an options page. Here is an explanation of how the extension works, followed by the complete code.
Explanation:
1. Content Script (
content.js):-
Event Listeners:
- Keyboard Events: Listens for
keydownandkeyupevents to detect when the Alt key is pressed or released. - Mouse Events: Listens for
mousedown,mouseup, andmousemoveevents to detect when the left mouse button is pressed, released, and when the mouse is moved. - Prevent Default Behavior: Prevents default text selection behavior when the extension is active.
- Keyboard Events: Listens for
-
Selection Logic:
- Activation Delay: The selection rectangle is only activated if the Alt key is held for more than 300ms before holding the left mouse button.
- Drawing the Selection Rectangle: When the user drags the mouse while holding Alt and the left mouse button, a selection rectangle with a yellow border is displayed.
- Updating Selection Area: The rectangle updates its size and position as the mouse moves.
- Auto-Scrolling: If the mouse is dragged to the top or bottom edges of the window, the page auto-scrolls smoothly to extend the selection area.
-
Link Detection and Highlighting:
- Detecting Clickable Links: All clickable links (including those specified in the options page) within the selection area are detected.
- Highlighting Links: These links are highlighted with a blue border.
- Displaying Link Count: The number of detected links is displayed in the bottom-right corner of the selection rectangle.
-
Link Opening Behavior:
- Canceling Selection: If the Alt key is released before the left mouse button, the selection is canceled without opening any links.
- Opening Links: If the left mouse button is released while still holding Alt, all unique detected links are opened in new tabs to the right of the current tab without changing focus.
- Confirmation for Many Links: If more than 20 links are selected, a confirmation dialog is shown before opening them.
2. Background Script (
background.js):- Opening Tabs:
- Receives messages from the content script containing the list of links to open.
- Opens each link in a new tab to the right of the current tab without changing focus.
- Ensures tabs are opened in order and avoids opening duplicate links.
- Handles confirmation if more than 20 links are to be opened.
3. Options Page (
options.htmlandoptions.js):- Custom Link Detection:
- Provides an input box for users to specify additional CSS selectors for elements to be treated as links.
- Pre-populates the input box with default selectors for elements like "li.shopee-search-item-result__item .article-name" and others provided.
- Auto-saves changes to the extension's options.
4. Manifest File (
manifest.json):- Extension Configuration:
- Specifies the extension's name, description, version, permissions, and scripts.
- Defines content scripts and background scripts.
5. Styles and Icons:
- Styles:
- Injects CSS styles to define the appearance of the selection rectangle and highlighted links.
- Icons:
- References icons for different sizes; ensure that icon files are included in the
iconsdirectory.
- References icons for different sizes; ensure that icon files are included in the
Now, here's the complete code for the extension.
manifest.json
{ "manifest_version": 3, "name": "Selection Link Opener", "version": "1.0", "description": "Select links to open by dragging with Alt + Left Mouse Button.", "permissions": ["tabs", "storage", "scripting", "activeTab"], "background": { "service_worker": "background.js" }, "options_page": "options.html", "content_scripts": [ { "matches": ["<all_urls>"], "js": ["content.js"] } ], "host_permissions": ["<all_urls>"], "icons": { "16": "icons/icon16.png", "32": "icons/icon32.png", "48": "icons/icon48.png", "128": "icons/icon128.png" } }
background.js
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { if (message.action === 'openLinks') { const links = message.links; const currentTabId = sender.tab.id; const maxLinks = 20; const linksToOpen = links.slice(0); // Copy of links chrome.tabs.query({ currentWindow: true, active: true }, (tabs) => { const currentIndex = tabs[0].index; const openTabs = () => { linksToOpen.forEach((link, index) => { chrome.tabs.create({ url: link, active: false, index: currentIndex + index + 1 }); }); }; if (links.length > maxLinks) { chrome.tabs.sendMessage(currentTabId, { action: 'confirmOpen', count: links.length }, (response) => { if (response.confirmed) { openTabs(); } }); } else { openTabs(); } }); } });
content.js
let isAltDown = false; let isMouseDown = false; let selectionDiv = null; let startX = 0; let startY = 0; let altDownTime = 0; let altMouseDelay = 300; // 300ms delay let autoScrollInterval = null; let detectedLinks = new Set(); let highlightedElements = new Set(); let additionalSelectors = ''; function loadOptions() { chrome.storage.sync.get(['additionalSelectors'], (data) => { additionalSelectors = data.additionalSelectors || 'li.shopee-search-item-result__item .article-name, .article-link'; }); } loadOptions(); // Inject styles const style = document.createElement('style'); style.textContent = ` .highlighted-link-extension { border: 4px solid blue !important; } .selection-rectangle-extension { position: fixed; border: 4px solid yellow; pointer-events: none; z-index: 9999; } #link-count-display-extension { position: absolute; bottom: 0; right: 0; background-color: black; color: white; font-size: 18px; padding: 2px 5px; } `; document.head.appendChild(style); // Event listeners document.addEventListener('keydown', (e) => { if (e.code === 'AltLeft' || e.code === 'AltRight') { if (!isAltDown) { isAltDown = true; altDownTime = Date.now(); } } }); document.addEventListener('keyup', (e) => { if (e.code === 'AltLeft' || e.code === 'AltRight') { isAltDown = false; if (selectionDiv) { cleanupSelection(); } } }); document.addEventListener('mousedown', (e) => { if (e.button !== 0) return; // Only left mouse button if (isAltDown && (Date.now() - altDownTime) >= altMouseDelay) { e.preventDefault(); isMouseDown = true; startX = e.clientX; startY = e.clientY; createSelectionDiv(startX, startY); document.addEventListener('mousemove', onMouseMove); } }); document.addEventListener('mouseup', (e) => { if (isMouseDown) { isMouseDown = false; if (isAltDown && selectionDiv) { openLinks(); } cleanupSelection(); document.removeEventListener('mousemove', onMouseMove); } }); function onMouseMove(e) { if (!isMouseDown || !isAltDown || !selectionDiv) return; updateSelectionDiv(e.clientX, e.clientY); detectLinksWithinSelection(); handleAutoScroll(e.clientY); } function createSelectionDiv(x, y) { selectionDiv = document.createElement('div'); selectionDiv.classList.add('selection-rectangle-extension'); selectionDiv.style.left = x + 'px'; selectionDiv.style.top = y + 'px'; selectionDiv.style.width = '0px'; selectionDiv.style.height = '0px'; document.body.appendChild(selectionDiv); // Link count display const countDiv = document.createElement('div'); countDiv.id = 'link-count-display-extension'; countDiv.textContent = '0'; selectionDiv.appendChild(countDiv); } function updateSelectionDiv(currentX, currentY) { const x = Math.min(currentX, startX); const y = Math.min(currentY, startY); const width = Math.abs(currentX - startX); const height = Math.abs(currentY - startY); selectionDiv.style.left = x + 'px'; selectionDiv.style.top = y + 'px'; selectionDiv.style.width = width + 'px'; selectionDiv.style.height = height + 'px'; } function detectLinksWithinSelection() { // Clear previous highlights highlightedElements.forEach((el) => { el.classList.remove('highlighted-link-extension'); }); highlightedElements.clear(); detectedLinks.clear(); const rect = selectionDiv.getBoundingClientRect(); const elements = document.querySelectorAll('a[href], area[href], [role="link"]'); // Include additional selectors from options if (additionalSelectors.trim() !== '') { const additionalElements = document.querySelectorAll(additionalSelectors.replace(/##/g, '')); elements.forEach((el) => additionalElements.push(el)); } elements.forEach((el) => { const elRect = el.getBoundingClientRect(); if (rectIntersect(rect, elRect)) { const href = el.href || el.getAttribute('data-href') || el.getAttribute('href'); if (href && !detectedLinks.has(href)) { detectedLinks.add(href); el.classList.add('highlighted-link-extension'); highlightedElements.add(el); } } }); const countDiv = selectionDiv.querySelector('#link-count-display-extension'); countDiv.textContent = detectedLinks.size.toString(); } function rectIntersect(rect1, rect2) { return !( rect2.left > rect1.right || rect2.right < rect1.left || rect2.top > rect1.bottom || rect2.bottom < rect1.top ); } function openLinks() { if (detectedLinks.size === 0) return; chrome.runtime.sendMessage({ action: 'openLinks', links: Array.from(detectedLinks) }); } function cleanupSelection() { if (selectionDiv) { selectionDiv.remove(); selectionDiv = null; } highlightedElements.forEach((el) => { el.classList.remove('highlighted-link-extension'); }); highlightedElements.clear(); detectedLinks.clear(); if (autoScrollInterval) { clearInterval(autoScrollInterval); autoScrollInterval = null; } } function handleAutoScroll(mouseY) { const autoScrollMargin = 50; // pixels const scrollSpeed = 10; // pixels per interval const intervalTime = 10; // milliseconds const windowHeight = window.innerHeight; if (mouseY < autoScrollMargin) { if (!autoScrollInterval) { autoScrollInterval = setInterval(() => { window.scrollBy(0, -scrollSpeed); updateSelectionDivCursorPosition(); detectLinksWithinSelection(); }, intervalTime); } } else if (mouseY > windowHeight - autoScrollMargin) { if (!autoScrollInterval) { autoScrollInterval = setInterval(() => { window.scrollBy(0, scrollSpeed); updateSelectionDivCursorPosition(); detectLinksWithinSelection(); }, intervalTime); } } else { if (autoScrollInterval) { clearInterval(autoScrollInterval); autoScrollInterval = null; } } } function updateSelectionDivCursorPosition() { const e = window.event; if (e) { updateSelectionDiv(e.clientX, e.clientY); } } // Confirmation dialog handling chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { if (message.action === 'confirmOpen') { const confirmed = confirm(`You are about to open ${message.count} links. Do you want to proceed?`); sendResponse({ confirmed }); } }); // Prevent default text selection function preventDefaultSelection(e) { if (isAltDown && isMouseDown && (Date.now() - altDownTime) >= altMouseDelay) { e.preventDefault(); } } document.addEventListener('selectstart', preventDefaultSelection); document.addEventListener('dragstart', preventDefaultSelection);
options.html
<!DOCTYPE html> <html> <head> <title>Selection Link Opener Options</title> <style> body { font-family: Arial, sans-serif; margin: 20px; } textarea { width: 100%; height: 150px; } label { font-weight: bold; } </style> </head> <body> <h1>Selection Link Opener Options</h1> <label for="selectors">Additional CSS Selectors for Links (one per line):</label><br> <textarea id="selectors"></textarea> <p>Default selectors are already included: <code>li.shopee-search-item-result__item .article-name, .article-link</code></p> <p>Your changes are auto-saved.</p> <script src="options.js"></script> </body> </html>
options.js
const selectorsTextArea = document.getElementById('selectors'); function saveOptions() { chrome.storage.sync.set({ additionalSelectors: selectorsTextArea.value }); } function loadOptions() { chrome.storage.sync.get(['additionalSelectors'], (data) => { selectorsTextArea.value = data.additionalSelectors || `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`; }); } selectorsTextArea.addEventListener('input', saveOptions); document.addEventListener('DOMContentLoaded', loadOptions);
Additional Notes:
- Icons: Ensure you have icon files in the
iconsdirectory as specified in themanifest.json. - Permissions: The extension requires permissions for tabs, storage, scripting, and activeTab to function correctly.
- Compatibility: The extension is compatible with both Edge and Chrome browsers.
- Auto-Save Options: The options page automatically saves user inputs using Chrome's
storage.sync. - Testing: After installing the extension, you can test it on any webpage by holding Alt, then holding the left mouse button, and dragging to select an area with links.
This complete code should implement all the functionalities you've requested for the Edge and Chrome extension.
-