can you write a chrome extension that complies with chromes content security policy. if…
- User
can you write a chrome extension that complies with chromes content security policy. if the user is on a youtube video page and there is the letters SV and a youtube link right after it in the excerpt of the video description it should launch, when the main icon is clicked, into a full black screen with two videos one on top of the other, the video urls are the one on the youtube page and the one after the letters SV. escape key should close it and recommended videos that are in the videos that are clicked on should open where the video they were in was and not a new tab.
- Assistant
Creating a Chrome extension with the functionality you described involves several steps, including interacting with YouTube's DOM, handling user interactions, and dynamically injecting video players. Below is a simplified version of such an extension. Please note that depending on YouTube's frequent updates to their site structure, additional adjustments might be necessary to ensure compatibility.
Overview
-
Manifest File (
manifest.json)- Defines the extension's permissions, background scripts, and content scripts.
-
Content Script (
content.js)- Scans the YouTube video description for the pattern "SV" followed by a YouTube link.
- Stores the secondary video URL for later use.
-
Popup HTML (
popup.html) and JavaScript (popup.js)- Handles the main icon click.
- Injects a full-screen overlay with two embedded videos.
- Handles the Escape key to close the overlay.
- Ensures that recommended videos open in the same tab.
-
CSS (
styles.css)- Styles the full-screen overlay and video containers.
1.
manifest.json{ "manifest_version": 3, "name": "YouTube SV Video Launcher", "version": "1.0", "description": "Launches two YouTube videos from description when activated.", "permissions": ["activeTab", "scripting"], "action": { "default_popup": "popup.html", "default_icon": { "16": "icons/icon16.png", "48": "icons/icon48.png", "128": "icons/icon128.png" } }, "content_scripts": [ { "matches": ["https://www.youtube.com/watch*"], "js": ["content.js"] } ], "icons": { "16": "icons/icon16.png", "48": "icons/icon48.png", "128": "icons/icon128.png" } }Notes:
- Ensure you have icon files in the specified directory.
scriptingpermission is required for injecting scripts.
2.
content.js// content.js let svVideoUrl = null; // Function to extract SV video URL function extractSVVideoUrl() { const description = document.querySelector('#description') || document.querySelector('#meta #description'); if (description) { const text = description.innerText; const svIndex = text.indexOf('SV'); if (svIndex !== -1) { const afterSV = text.substring(svIndex + 2).trim(); const urlMatch = afterSV.match(/https?:\/\/www\.youtube\.com\/watch\?v=[\w-]{11}/); if (urlMatch) { svVideoUrl = urlMatch[0]; // Store in page's dataset for access by popup document.body.dataset.svVideoUrl = svVideoUrl; } } } } // Run extraction on page load extractSVVideoUrl();Notes:
- This script searches for "SV" in the video description and extracts the subsequent YouTube link.
- It stores the extracted URL in the page's
datasetfor access by the popup.
3.
popup.html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>YouTube SV Video Launcher</title> <link rel="stylesheet" href="styles.css"> </head> <body> <button id="launchButton">Launch Videos</button> <script src="popup.js"></script> </body> </html>4.
popup.js// popup.js document.getElementById('launchButton').addEventListener('click', async () => { // Query the active tab const [tab] = await chrome.tabs.query({ active: true, currentWindow: true }); // Execute a script to get the SV video URL from the page's dataset chrome.scripting.executeScript( { target: { tabId: tab.id }, function: () => document.body.dataset.svVideoUrl, }, (results) => { const svVideoUrl = results[0].result; if (svVideoUrl) { chrome.scripting.executeScript( { target: { tabId: tab.id }, func: launchVideos, args: [tab.url, svVideoUrl], } ); } else { alert('SV video URL not found in description.'); } } ); }); // Function to inject the overlay with videos function launchVideos(mainVideoUrl, svVideoUrl) { // Prevent multiple overlays if (document.getElementById('sv-overlay')) return; // Create overlay const overlay = document.createElement('div'); overlay.id = 'sv-overlay'; // Create container const container = document.createElement('div'); container.id = 'sv-container'; // Create video iframes const mainIframe = document.createElement('iframe'); mainIframe.src = `https://www.youtube.com/embed/${getYouTubeID(mainVideoUrl)}?autoplay=1`; mainIframe.allow = "autoplay; encrypted-media"; mainIframe.allowFullscreen = true; const svIframe = document.createElement('iframe'); svIframe.src = `https://www.youtube.com/embed/${getYouTubeID(svVideoUrl)}?autoplay=1`; svIframe.allow = "autoplay; encrypted-media"; svIframe.allowFullscreen = true; // Append iframes to container container.appendChild(mainIframe); container.appendChild(svIframe); // Append container to overlay overlay.appendChild(container); document.body.appendChild(overlay); // Add keydown listener to close on Escape function escListener(e) { if (e.key === 'Escape') { closeOverlay(); } } document.addEventListener('keydown', escListener); // Function to close overlay function closeOverlay() { document.body.removeChild(overlay); document.removeEventListener('keydown', escListener); } // Ensure recommended videos open in the same tab overrideLinks(); function overrideLinks() { const links = document.querySelectorAll('a'); links.forEach(link => { link.addEventListener('click', (e) => { e.preventDefault(); const url = link.href; if (url.startsWith('https://www.youtube.com/watch')) { window.location.href = url; } }); }); } // Utility to extract YouTube video ID function getYouTubeID(url) { const regex = /v=([a-zA-Z0-9_-]{11})/; const match = url.match(regex); return match ? match[1] : null; } }Notes:
- The popup script retrieves the current tab's URL and the SV video URL from the content script.
- It then injects an overlay with two embedded YouTube players.
- The
Escapekey listener allows users to close the overlay. - Recommended videos within the overlay are overridden to open in the same tab.
5.
styles.css/* styles.css */ #sv-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: black; z-index: 9999; display: flex; justify-content: center; align-items: center; flex-direction: column; } #sv-container { display: flex; flex-direction: column; gap: 20px; } #sv-container iframe { width: 80%; height: 45vh; }Notes:
- Styles the overlay to cover the entire screen with a black background.
- Two videos are stacked vertically with some spacing.
Additional Considerations
-
Content Security Policy (CSP):
- Manifest V3 enforces stricter CSP. Inline scripts and certain eval-like functions are disallowed.
- All JavaScript should be in separate
.jsfiles. - Ensure that any resources loaded comply with YouTube's embedding policies.
-
YouTube Embedding Restrictions:
- Some videos might have embedding disabled.
- Ensure that both videos allow embedding to avoid playback issues.
-
Dynamic Content Loading:
- YouTube dynamically loads content; ensure that the content script runs after the necessary elements are available or use mutation observers as needed.
-
Error Handling:
- Add more robust error handling for cases where URLs aren't found or embedding fails.
-
Permissions:
- The
activeTabandscriptingpermissions are essential for injecting scripts and modifying the current page.
- The
-
Icon Files:
- Ensure that you have appropriate icon files (
icon16.png,icon48.png,icon128.png) in aniconsdirectory.
- Ensure that you have appropriate icon files (
Testing the Extension
-
Prepare the Files:
- Create a directory for your extension.
- Add the
manifest.json,content.js,popup.html,popup.js,styles.css, and icon files to this directory.
-
Load the Extension:
- Open Chrome and navigate to
chrome://extensions/. - Enable "Developer mode" using the toggle in the top right corner.
- Click "Load unpacked" and select your extension's directory.
- Open Chrome and navigate to
-
Use the Extension:
- Navigate to a YouTube video page.
- Ensure the video description contains "SV" followed by a valid YouTube link.
- Click the extension icon and then the "Launch Videos" button in the popup.
- A full-screen overlay with two videos should appear.
- Press
Escapeto close the overlay.
Disclaimer
This extension is a basic implementation and may require enhancements for production use. Be mindful of YouTube's Terms of Service and ensure that your extension complies with all relevant guidelines and policies.
-