create edge & chrome extension code manifest v3 ,main function is when user trigger shortcut (first hold alt then hold left mouse) and then drag it will show rectangle selection area with border color yellow and all link (clickable link like image link or text link) in selection area will be highlighted border color blue with border size 4,with extension option to add element to detect link in inputbox auto save change ,it will work by check if trigger key is both hold then start script and selections area ,explain first then show complete code.
Assistant
To create a Chrome and Edge extension with Manifest V3 that allows users to select an area on a webpage by holding the Alt key and the left mouse button, and then highlights all clickable links within that area, we need to follow several steps:
1. Overview of the Extension Functionality:
Trigger Mechanism: The script activates when the user holds down the Alt key and the left mouse button simultaneously and starts dragging the mouse.
Selection Rectangle: As the user drags the mouse, a yellow-bordered rectangle appears, indicating the selection area.
Link Detection: All clickable links (both text and image links) within the selection area are detected.
Highlighting Links: Detected links are highlighted with a blue border of size 4 pixels.
Extension Options: An options page allows users to add custom selectors for elements that should be considered as links. Any changes in the options are auto-saved.
2. Components of the Extension:
Manifest File (manifest.json): Defines the extension's properties, permissions, and resources.
Content Script (contentScript.js): Runs in the context of web pages and handles the UI interactions (selection rectangle, event listeners).
Options Page (options.html and options.js): Provides a UI for users to specify custom link selectors.
Background Script: Not required in this case since we're dealing with content scripts and options.
3. Implementation Details:
a. Manifest File (manifest.json):
Specifies the content script to be injected into web pages.
Includes permissions for storage to save user preferences.
Defines the options page for user configurations.
b. Content Script (contentScript.js):
Event Listeners: Adds listeners for keydown, keyup, mousedown, mouseup, and mousemove to detect the trigger condition (Alt + left mouse drag).
Selection Rectangle: Creates a visual rectangle (div element) that follows the mouse movement during the drag.
Link Detection and Highlighting:
Retrieves all elements matching the default and user-defined link selectors.
Checks if these elements intersect with the selection rectangle using their bounding rectangles.
Applies a blue border to the intersecting elements.
Cleanup: Removes event listeners and the selection rectangle after the operation is complete.
c. Options Page (options.html and options.js):
User Interface: Provides an input box where users can enter custom selectors for link detection.
Auto-Save Feature: Saves the user's input to chrome.storage whenever it changes.
Default Selectors: Uses a default selector ('a[href]') for links if the user doesn't specify any.
4. Step-by-Step Execution Flow:
User Action: The user presses and holds the Alt key and the left mouse button.
Selection Start: The content script detects this combination and creates a selection rectangle at the mouse's starting position.
Mouse Dragging: As the user moves the mouse, the rectangle resizes to encompass the area between the starting point and the current mouse position.
Selection End: When the user releases the mouse button, the content script:
Retrieves all potential link elements based on the selectors.
Calculates each element's position and checks if it overlaps with the selection rectangle.
Highlights overlapping elements with a blue border.
Post-Selection: The selection rectangle is removed, and the content script awaits the next trigger.
5. Handling User-Defined Link Selectors:
The options page allows users to input custom CSS selectors for elements they consider as links.
These selectors are saved in chrome.storage and retrieved by the content script.
During link detection, the content script uses both the default and user-defined selectors to find elements.
6. Complete Code:
Below is the complete code for each component of the extension.
manifest.json
json
{
"manifest_version": 3,
"name": "Selection Link Highlighter",
"version": "1.0",
"description": "Highlight all links within a selection area activated by Alt + left mouse drag.",
"permissions": ["storage"],
"options_page": "options.html",
"background": {
"service_worker": "background.js"
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["contentScript.js"]
}
],
"icons": {
"16": "icons/icon16.png",
"48": "icons/icon48.png",
"128": "icons/icon128.png"
}
}
contentScript.js
javascript
(function() {
let isAltPressed = false;
let isMouseDown = false;
let startX, startY;
let selectionDiv;
let userSelectors = ['a[href]']; // Default selector
// Load user-defined selectors from storage
chrome.storage.sync.get(['linkSelectors'], function(result) {
if (result.linkSelectors) {
userSelectors = result.linkSelectors.split(',').map(s => s.trim()).filter(s => s);
}
});
document.addEventListener('keydown', function(e) {
if (e.key === 'Alt') {
isAltPressed = true;
}
});
document.addEventListener('keyup', function(e) {
if (e.key === 'Alt') {
isAltPressed = false;
}
});
document.addEventListener('mousedown', function(e) {
if (isAltPressed && e.button === 0) {
isMouseDown = true;
startX = e.pageX;
startY = e.pageY;
createSelectionDiv(startX, startY);
document.addEventListener('mousemove', onMouseMove);
e.preventDefault(); // Prevent text selection
}
});
document.addEventListener('mouseup', function(e) {
if (isMouseDown) {
isMouseDown = false;
document.removeEventListener('mousemove', onMouseMove);
highlightLinksInSelection();
removeSelectionDiv();
}
});
function createSelectionDiv(x, y) {
selectionDiv = document.createElement('div');
selectionDiv.style.position = 'absolute';
selectionDiv.style.border = '2px solid yellow';
selectionDiv.style.top = y + 'px';
selectionDiv.style.left = x + 'px';
selectionDiv.style.zIndex = 1000000;
document.body.appendChild(selectionDiv);
}
function onMouseMove(e) {
let x = Math.min(e.pageX, startX);
let y = Math.min(e.pageY, startY);
let width = Math.abs(e.pageX - startX);
let height = Math.abs(e.pageY - startY);
selectionDiv.style.left = x + 'px';
selectionDiv.style.top = y + 'px';
selectionDiv.style.width = width + 'px';
selectionDiv.style.height = height + 'px';
}
function removeSelectionDiv() {
if (selectionDiv) {
document.body.removeChild(selectionDiv);
selectionDiv = null;
}
}
function highlightLinksInSelection() {
let rect = selectionDiv.getBoundingClientRect();
let elements = [];
userSelectors.forEach(selector => {
let elems = document.querySelectorAll(selector);
elements = elements.concat(Array.from(elems));
});
elements.forEach(elem => {
let elemRect = elem.getBoundingClientRect();
if (isIntersecting(rect, elemRect)) {
elem.style.outline = '4px solid blue';
}
});
}
function isIntersecting(r1, r2) {
return !(r2.left > r1.right ||
r2.right < r1.left ||
r2.top > r1.bottom ||
r2.bottom < r1.top);
}
})();
options.html
html
<!DOCTYPE html>
<html>
<head>
<title>Selection Link Highlighter Options</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
label {
display: block;
font-weight: bold;
}
input {
width: 100%;
padding: 8px;
margin-top: 5px;
box-sizing: border-box;
}
.note {
font-size: 0.9em;
color: #555;
}
</style>
</head>
<body>
<h1>Selection Link Highlighter Options</h1>
<label for="selectors">Custom Link Selectors (comma-separated):</label>
<input type="text" id="selectors" placeholder="e.g., a[href], img.clickable">
<p class="note">Add custom CSS selectors for elements to be considered as links. Default is <code>a[href]</code>.</p>
<script src="options.js"></script>
</body>
</html>
Permissions: The storage permission is required to save and retrieve user preferences.
Event Handling: Preventing the default action on mousedown ensures that the text on the page is not selected while drawing the selection rectangle.
Z-index: A high z-index ensures that the selection rectangle is visible above other page elements.
Outline vs. Border: Using outline for highlighting prevents layout shifts that can occur with borders.
8. Instructions to Test the Extension:
Load the Extension:
Go to chrome://extensions/ or edge://extensions/ in your browser.
Enable "Developer mode" using the toggle switch.
Click on "Load unpacked" and select the folder containing the extension files.
Set Custom Selectors (Optional):
Click on the extension's "Options" link.
Add any custom CSS selectors in the input box and they will be auto-saved.
Use the Extension:
Navigate to any webpage.
Hold down the Alt key and the left mouse button.
Drag the mouse to create a selection area.
Release the mouse button.
All links within the selection area should now be highlighted with a blue border.
Testing Custom Selectors:
If you added custom selectors, repeat the selection process to see elements matching those selectors highlighted.
9. Conclusion:
This extension enhances user interaction by allowing quick visual identification of links within a selected area. By providing options for custom selectors, users have flexibility in defining what elements are considered links, catering to various webpage structures and user needs.