Creating a Chrome extension like "Sync Waves" involves multiple components, including the manifest file, background scripts, content scripts, and various HTML/CSS/JavaScript files for the UI and functionality. Below is a step-by-step guide to building this extension while ensuring compliance with Chrome's Content Security Policy (CSP).
Overview of the Extension
- Manifest File (
manifest.json): Defines the extension's permissions, scripts, and other configurations.
- Content Script (
content.js): Detects if the user is on a YouTube video page and searches for the "SV" URL in the video description.
- Background Script (
background.js): Handles communication between the popup and content scripts.
- Popup UI (
popup.html, popup.js, popup.css): The user interface that appears when the extension icon is clicked.
- Fullscreen Overlay (
overlay.html, overlay.js, overlay.css): Displays the synchronized videos in a fullscreen black screen.
- Assets: Icons and other resources.
1. manifest.json
Create a manifest.json file in your project directory. This file tells Chrome about your extension, its permissions, and the files it uses.
{
"manifest_version": 3,
"name": "Sync Waves",
"version": "1.0",
"description": "Synchronize audio and video from YouTube with additional media.",
"icons": {
"16": "icons/icon16.png",
"48": "icons/icon48.png",
"128": "icons/icon128.png"
},
"permissions": [
"activeTab",
"scripting"
],
"action": {
"default_popup": "popup.html",
"default_title": "Sync Waves"
},
"background": {
"service_worker": "background.js"
},
"content_scripts": [
{
"matches": ["https://www.youtube.com/watch*"],
"js": ["content.js"]
}
],
"web_accessible_resources": [
{
"resources": ["overlay.html"],
"matches": ["<all_urls>"]
}
]
}
2. background.js
This script listens for messages from the popup and content scripts to handle actions like opening the overlay.
// background.js
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === "openOverlay") {
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
chrome.scripting.executeScript({
target: { tabId: tabs[0].id },
files: ["overlay.js"]
});
});
}
});
3. content.js
This script runs on YouTube video pages to search for the "SV" URL in the video description.
// content.js
function findSVUrl() {
const descriptionElement = document.querySelector('#description yt-formatted-string');
if (descriptionElement) {
const text = descriptionElement.innerText;
const svMatch = text.match(/SV\s+(https?:\/\/\S+)/);
if (svMatch && svMatch[1]) {
return svMatch[1];
}
}
return null;
}
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === "getSVUrl") {
const svUrl = findSVUrl();
sendResponse({ svUrl });
}
});
4. popup.html
This is the HTML file for the extension’s popup interface.
<!-- popup.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sync Waves</title>
<link rel="stylesheet" href="popup.css">
</head>
<body>
<h1>Sync Waves</h1>
<div class="section">
<h2>Audio</h2>
<input type="url" id="audio-url" placeholder="YouTube URL">
<input type="file" id="audio-file" accept="audio/*">
</div>
<div class="section">
<h2>Video</h2>
<input type="url" id="video-url" placeholder="YouTube URL">
</div>
<div class="controls">
<button id="play">Play</button>
<button id="pause">Pause</button>
<button id="resume">Resume</button>
</div>
<script src="popup.js"></script>
</body>
</html>
5. popup.css
CSS for styling the popup and making it responsive.
/* popup.css */
body {
font-family: Arial, sans-serif;
width: 300px;
padding: 10px;
}
h1 {
text-align: center;
font-size: 18px;
}
.section {
margin-bottom: 15px;
}
.section h2 {
font-size: 16px;
margin-bottom: 5px;
}
input[type="url"],
input[type="file"] {
width: 100%;
padding: 5px;
margin-bottom: 5px;
}
.controls {
display: flex;
justify-content: space-between;
}
button {
padding: 5px 10px;
flex: 1;
margin: 0 2px;
cursor: pointer;
}
@media (max-width: 400px) {
body {
width: 100%;
}
button {
padding: 10px;
font-size: 14px;
}
}
6. popup.js
Handles user interactions in the popup, such as play, pause, and resume actions.
// popup.js
document.addEventListener('DOMContentLoaded', () => {
const playBtn = document.getElementById('play');
const pauseBtn = document.getElementById('pause');
const resumeBtn = document.getElementById('resume');
playBtn.addEventListener('click', () => {
// Implement play functionality
console.log('Play clicked');
// You can expand this to communicate with content scripts or background scripts
});
pauseBtn.addEventListener('click', () => {
// Implement pause functionality
console.log('Pause clicked');
});
resumeBtn.addEventListener('click', () => {
// Implement resume functionality
console.log('Resume clicked');
});
});
7. overlay.html
This file represents the fullscreen overlay that displays the synchronized videos.
<!-- overlay.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sync Waves Overlay</title>
<link rel="stylesheet" href="overlay.css">
</head>
<body>
<div id="overlay">
<video id="mainVideo" controls autoplay></video>
<video id="svVideo" controls autoplay></video>
</div>
<script src="overlay.js"></script>
</body>
</html>
8. overlay.css
Styles for the fullscreen overlay.
/* overlay.css */
body, html {
margin: 0;
padding: 0;
height: 100%;
background-color: black;
}
#overlay {
display: flex;
flex-direction: column;
height: 100%;
width: 100%;
background-color: black;
}
video {
flex: 1;
width: 100%;
height: 50%;
object-fit: contain;
background-color: black;
}
9. overlay.js
Handles the logic for displaying the videos and closing the overlay with the Escape key.
// overlay.js
document.addEventListener('DOMContentLoaded', () => {
// Retrieve video URLs from storage or message
chrome.runtime.sendMessage({ action: "getVideoUrls" }, (response) => {
const { mainVideoUrl, svVideoUrl } = response;
const mainVideo = document.getElementById('mainVideo');
const svVideo = document.getElementById('svVideo');
mainVideo.src = mainVideoUrl;
svVideo.src = svVideoUrl;
});
// Close overlay on Escape key
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
window.close();
}
});
// Handle recommended videos to open in the same overlay
// This part can be complex as it involves intercepting YouTube's navigation
});
10. Handling Communication between Scripts
To facilitate communication between different parts of your extension, such as passing video URLs from the popup to the overlay, you can use Chrome's messaging API.
Update background.js to handle video URLs:
// background.js
let videoUrls = {
mainVideoUrl: '',
svVideoUrl: ''
};
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === "openOverlay") {
// You can inject the overlay.html into the current tab
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
chrome.scripting.executeScript({
target: { tabId: tabs[0].id },
files: ["overlay.js"]
});
});
} else if (request.action === "setVideoUrls") {
videoUrls.mainVideoUrl = request.mainVideoUrl;
videoUrls.svVideoUrl = request.svVideoUrl;
sendResponse({ status: "success" });
} else if (request.action === "getVideoUrls") {
sendResponse(videoUrls);
}
});
Update popup.js to send video URLs:
// popup.js
document.addEventListener('DOMContentLoaded', () => {
const playBtn = document.getElementById('play');
const pauseBtn = document.getElementById('pause');
const resumeBtn = document.getElementById('resume');
playBtn.addEventListener('click', () => {
const audioUrl = document.getElementById('audio-url').value;
const audioFile = document.getElementById('audio-file').files[0];
const videoUrl = document.getElementById('video-url').value;
// Handle audio file upload (if any)
if (audioFile) {
const reader = new FileReader();
reader.onload = function(e) {
const localAudioUrl = e.target.result;
chrome.runtime.sendMessage({
action: "setVideoUrls",
mainVideoUrl: videoUrl,
svVideoUrl: audioUrl || localAudioUrl
}, () => {
chrome.runtime.sendMessage({ action: "openOverlay" });
});
};
reader.readAsDataURL(audioFile);
} else {
chrome.runtime.sendMessage({
action: "setVideoUrls",
mainVideoUrl: videoUrl,
svVideoUrl: audioUrl
}, () => {
chrome.runtime.sendMessage({ action: "openOverlay" });
});
}
});
// Implement pause and resume functionalities as needed
});
11. Icons
Place your extension icons in an icons folder within your project directory. Ensure you have icons with sizes 16x16, 48x48, and 128x128 pixels named accordingly (icon16.png, icon48.png, icon128.png).
12. Loading the Extension
-
Prepare the Directory Structure:
SyncWaves/
│
├── background.js
├── content.js
├── manifest.json
├── popup.html
├── popup.js
├── popup.css
├── overlay.html
├── overlay.js
├── overlay.css
└── icons/
├── icon16.png
├── icon48.png
└── icon128.png
-
Load the Extension in Chrome:
- Open Chrome and navigate to
chrome://extensions/.
- Enable "Developer mode" by toggling the switch in the top right corner.
- Click on "Load unpacked" and select the
SyncWaves directory.
-
Testing the Extension:
- Navigate to a YouTube video page.
- Ensure the video description contains "SV" followed by a valid URL.
- Click on the "Sync Waves" extension icon.
- The overlay should appear with the main video and the SV video synchronized.
- Press the Escape key to close the overlay.
- If not on a YouTube video page, clicking the icon should open the popup without the overlay.
Notes and Enhancements
-
CSP Compliance: Ensure that all scripts are referenced externally and avoid inline JavaScript in HTML files to comply with Chrome's CSP.
-
Recommended Videos Handling: To manage recommended videos opening in the same overlay, you might need to intercept YouTube's navigation or modify the links dynamically. This requires more advanced scripting and handling YouTube's dynamic content.
-
Error Handling: Implement proper error handling for cases where the "SV" URL is not found or invalid.
-
Audio File Support: Currently, the extension supports uploading local audio files. Ensure that you handle different audio formats and fallback gracefully if unsupported formats are uploaded.
-
Responsive Design: The provided CSS offers basic responsiveness. You can enhance it further using media queries and more flexible layouts to cater to different screen sizes.
-
Security Considerations: Always validate and sanitize URLs and inputs to prevent potential security vulnerabilities.
Conclusion
This guide provides a foundational structure for building the "Sync Waves" Chrome extension. Depending on your specific requirements and enhancements, you may need to expand upon these scripts and styles. Ensure thorough testing across different YouTube pages and scenarios to provide a seamless user experience.