Sure! Below is the code for a Chrome extension that meets your requirements:
- **Displays only images or videos on the webpage when the respective button is clicked.
- Images and videos are displayed consecutively in a single column.
- Includes a toggle option to turn the filter on and off.**
Extension Files
1. manifest.json
{
"manifest_version": 3,
"name": "Media Filter",
"version": "1.0",
"description": "Display only images or videos on the page.",
"action": {
"default_popup": "popup.html",
"default_icon": {
"16": "icon16.png",
"32": "icon32.png",
"48": "icon48.png",
"128": "icon128.png"
}
},
"permissions": [
"scripting",
"activeTab"
]
}
Explanation:
manifest_version: Specifies the version of the manifest file format (Manifest V3 is the latest).
name & description: Basic information about the extension.
action: Defines the toolbar icon and the popup that appears when the icon is clicked.
permissions: Allows the extension to inject scripts into web pages and access the active tab.
2. popup.html
<!DOCTYPE html>
<html>
<head>
<title>Media Filter</title>
<style>
body {
width: 200px;
font-family: Arial, sans-serif;
margin: 10px;
}
button {
width: 100%;
padding: 10px;
margin: 5px 0;
font-size: 16px;
cursor: pointer;
}
.toggle-container {
display: flex;
align-items: center;
margin-top: 10px;
}
input[type="checkbox"] {
margin-right: 5px;
}
label {
font-size: 14px;
}
</style>
</head>
<body>
<button id="showImages">Images</button>
<button id="showVideos">Videos</button>
<div class="toggle-container">
<input type="checkbox" id="toggleDisplay">
<label for="toggleDisplay">Toggle Display</label>
</div>
<script src="popup.js"></script>
</body>
</html>
Explanation:
- The popup includes two buttons: Images and Videos.
- A checkbox labeled Toggle Display allows you to turn the filter on and off.
- Styles ensure the popup looks clean and user-friendly.
3. popup.js
document.getElementById('showImages').addEventListener('click', () => {
sendMessageToContentScript('images');
});
document.getElementById('showVideos').addEventListener('click', () => {
sendMessageToContentScript('videos');
});
document.getElementById('toggleDisplay').addEventListener('change', () => {
sendMessageToContentScript(null); // No filter type change
});
function sendMessageToContentScript(filterType) {
const toggleState = getToggleState();
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
chrome.scripting.executeScript(
{
target: { tabId: tabs[0].id },
files: ['content_script.js'],
},
function () {
chrome.tabs.sendMessage(tabs[0].id, {
filterType: filterType,
toggle: toggleState,
});
}
);
});
}
function getToggleState() {
return document.getElementById('toggleDisplay').checked;
}
Explanation:
- Event Listeners: Handle clicks on the Images and Videos buttons and changes to the toggle checkbox.
sendMessageToContentScript(): Sends messages to the content script with the filter type and toggle state.
- Message Structure:
filterType: Can be 'images', 'videos', or null (when only the toggle changes).
toggle: true if the toggle is on; false otherwise.
4. content_script.js
(function () {
let originalHTML = '';
let isFiltered = false;
let currentFilterType = null;
const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
const videoExtensions = ['mp4', 'webm', 'ogg', 'avi', 'mov', 'mkv'];
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.filterType !== undefined && message.filterType !== null) {
// Update the current filter type
currentFilterType = message.filterType;
}
if (message.toggle !== undefined) {
if (message.toggle) {
// Apply the filter
applyFilter();
} else {
// Remove the filter
removeFilter();
}
}
});
function applyFilter() {
if (isFiltered) {
removeFilter();
}
// Store the original HTML once
if (!originalHTML) {
originalHTML = document.body.innerHTML;
}
const mediaElements = [];
if (currentFilterType === 'images') {
// Collect all image elements
const imgs = document.querySelectorAll('img');
mediaElements.push(...imgs);
// Include elements with background images
const bgImages = getElementsWithBackgroundImages();
mediaElements.push(...bgImages);
} else if (currentFilterType === 'videos') {
// Collect all video elements
const videos = document.querySelectorAll('video');
mediaElements.push(...videos);
}
// Clear the body content
document.body.innerHTML = '';
// Create a container to hold media elements
const container = document.createElement('div');
container.style.display = 'flex';
container.style.flexDirection = 'column';
container.style.alignItems = 'center';
document.body.appendChild(container);
mediaElements.forEach((el) => {
const clonedEl = el.cloneNode(true);
container.appendChild(clonedEl);
});
isFiltered = true;
}
function removeFilter() {
if (!isFiltered) return;
document.body.innerHTML = originalHTML;
isFiltered = false;
currentFilterType = null;
}
function getElementsWithBackgroundImages() {
const elements = [];
const allElements = document.body.querySelectorAll('*');
allElements.forEach((el) => {
const bgImage = window.getComputedStyle(el).backgroundImage;
if (bgImage && bgImage !== 'none') {
// Extract the image URL
const urlMatch = bgImage.match(/url\(['"]?([^'"]+)['"]?\)/);
if (urlMatch && urlMatch[1]) {
const url = urlMatch[1];
const ext = url
.split('.')
.pop()
.split('?')[0]
.split('#')[0]
.toLowerCase();
if (imageExtensions.includes(ext)) {
// Create an image element for the background image
const img = document.createElement('img');
img.src = url;
elements.push(img);
}
}
}
});
return elements;
}
})();
Explanation:
- Variables:
originalHTML: Stores the original page content to restore later.
isFiltered: Tracks whether the filter is currently applied.
currentFilterType: The type of media to display ('images' or 'videos').
- Event Listener:
- Listens for messages from
popup.js to apply or remove filters.
applyFilter():
- Checks and resets any existing filters.
- Collects media elements based on the
currentFilterType.
- Clears the page content and displays the media elements consecutively.
removeFilter():
- Restores the original page content from
originalHTML.
getElementsWithBackgroundImages():
- Finds elements with background images and creates image elements for them.
How to Set Up the Extension
-
Create a New Folder:
- Create a new folder on your computer to hold the extension files (e.g.,
media-filter-extension).
-
Add the Files:
- Save the
manifest.json, popup.html, popup.js, and content_script.js files into the folder.
- Add an icon for the extension (e.g.,
icon16.png, icon32.png, icon48.png, icon128.png). These can be any images you prefer, matching the specified sizes.
-
Load the Extension into Chrome:
- Open Google Chrome.
- Navigate to
chrome://extensions/.
- Enable Developer mode by toggling the switch in the top-right corner.
- Click on "Load unpacked".
- Select the folder you created in Step 1.
-
Use the Extension:
- Navigate to any webpage.
- Click on the extension icon in the toolbar.
- Click "Images" or "Videos" to select the media type you want to display.
- Check the "Toggle Display" checkbox to apply the filter.
- Uncheck the checkbox to restore the original page.
Notes
- Consecutive Display:
- The extension collects all the media elements and displays them one after another in a vertical column.
- Background Images:
- Elements with background images are also processed. The images are extracted and displayed as regular
<img> elements.
- Toggle Behavior:
- The "Toggle Display" checkbox controls whether the filter is active.
- You can switch between Images and Videos while the filter is active.
- Limitations:
- The extension works best on pages where images and videos are directly included.
- Dynamic content loaded after the initial page load may not be captured unless you reapply the filter.
Additional Considerations
- Permissions:
- The extension requires access to pages you visit to manipulate the content. Always be cautious when granting permissions.
- Privacy:
- This extension runs locally in your browser and does not collect or transmit any data.
Conclusion
You now have a Chrome extension that filters and displays only images or videos on any webpage. Feel free to customize and expand upon this code to suit your needs!