Creating a Chrome extension that meets your specifications involves several components: the manifest.json file, HTML files for the popup and the new tab, and corresponding JavaScript files to handle the functionality. Below is a step-by-step guide along with the necessary code snippets for each part of the extension.
Overview
- Extension Name: Syncwaves
- Features:
- Audio Section:
- Input YouTube URL
- Load local audio file (restricted to supported formats)
- Specify start time in seconds
- Load button
- Video Section:
- Input YouTube URL
- Load local video file (restricted to supported formats)
- Specify start time in seconds
- Load button
- Control Section:
- Play Button
- Pause Button
- Resume Button
- Functionality:
- Upon clicking the Load buttons, the selected media (audio/video) is loaded in a new tab.
- The media plays for 1/8th of a second, pauses, and sets to the user-specified start time.
- Control buttons allow playback manipulation.
Directory Structure
syncwaves/
│
├── manifest.json
├── popup.html
├── popup.js
├── newtab.html
├── newtab.js
├── styles.css
└── icons/
└── icon.png
1. manifest.json
This file describes your extension's properties, permissions, and resources.
{
"manifest_version": 3,
"name": "Syncwaves",
"description": "Sync audio and video from YouTube or local files with start time controls.",
"version": "1.0",
"action": {
"default_popup": "popup.html",
"default_icon": {
"16": "icons/icon.png",
"48": "icons/icon.png",
"128": "icons/icon.png"
}
},
"permissions": [
"tabs",
"scripting"
],
"host_permissions": [
"https://www.youtube.com/*"
],
"icons": {
"16": "icons/icon.png",
"48": "icons/icon.png",
"128": "icons/icon.png"
}
}
Notes:
manifest_version: Using version 3, which is the latest as of the knowledge cutoff.
permissions:
"tabs" and "scripting" are needed to open new tabs and inject scripts.
host_permissions:
- Allows embedding YouTube videos.
icons:
- Replace
"icons/icon.png" with your actual icon path.
2. popup.html
This is the HTML file for the extension's popup UI.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Syncwaves</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>Syncwaves</h1>
<div class="section">
<h2>Audio</h2>
<label for="audio-url">YouTube URL:</label>
<input type="url" id="audio-url" placeholder="https://www.youtube.com/watch?v=..." />
<label for="audio-file">Load Local Audio:</label>
<input type="file" id="audio-file" accept="audio/*" />
<label for="audio-start">Start Time (seconds):</label>
<input type="number" id="audio-start" min="0" value="0" />
<button id="load-audio">Load Audio</button>
</div>
<div class="section">
<h2>Video</h2>
<label for="video-url">YouTube URL:</label>
<input type="url" id="video-url" placeholder="https://www.youtube.com/watch?v=..." />
<label for="video-file">Load Local Video:</label>
<input type="file" id="video-file" accept="video/*" />
<label for="video-start">Start Time (seconds):</label>
<input type="number" id="video-start" min="0" value="0" />
<button id="load-video">Load Video</button>
</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>
3. styles.css
Basic styling for the popup. Feel free to customize as needed.
body {
font-family: Arial, sans-serif;
width: 300px;
padding: 10px;
}
h1 {
text-align: center;
}
.section {
margin-bottom: 20px;
}
label {
display: block;
margin-top: 10px;
}
input[type="url"],
input[type="file"],
input[type="number"] {
width: 100%;
padding: 5px;
box-sizing: border-box;
}
button {
margin-top: 10px;
padding: 10px;
width: 100%;
cursor: pointer;
}
.controls button {
width: 30%;
display: inline-block;
margin-right: 5%;
}
.controls button:last-child {
margin-right: 0;
}
4. popup.js
Handles the interaction logic for the popup. It captures user inputs and opens a new tab with the specified media.
// popup.js
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('load-audio').addEventListener('click', () => {
const audioURL = document.getElementById('audio-url').value;
const audioFile = document.getElementById('audio-file').files[0];
const audioStart = parseInt(document.getElementById('audio-start').value, 10);
chrome.tabs.create({ url: chrome.runtime.getURL('newtab.html') }, (tab) => {
// Send a message to the new tab with audio details
chrome.tabs.onUpdated.addListener(function listener(tabId, info) {
if (tabId === tab.id && info.status === 'complete') {
chrome.tabs.onUpdated.removeListener(listener);
chrome.tabs.sendMessage(tab.id, {
type: 'load-media',
media: 'audio',
url: audioURL,
file: audioFile ? URL.createObjectURL(audioFile) : null,
startTime: audioStart
});
}
});
});
});
document.getElementById('load-video').addEventListener('click', () => {
const videoURL = document.getElementById('video-url').value;
const videoFile = document.getElementById('video-file').files[0];
const videoStart = parseInt(document.getElementById('video-start').value, 10);
chrome.tabs.create({ url: chrome.runtime.getURL('newtab.html') }, (tab) => {
// Send a message to the new tab with video details
chrome.tabs.onUpdated.addListener(function listener(tabId, info) {
if (tabId === tab.id && info.status === 'complete') {
chrome.tabs.onUpdated.removeListener(listener);
chrome.tabs.sendMessage(tab.id, {
type: 'load-media',
media: 'video',
url: videoURL,
file: videoFile ? URL.createObjectURL(videoFile) : null,
startTime: videoStart
});
}
});
});
});
// Control Buttons
document.getElementById('play').addEventListener('click', () => {
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
chrome.tabs.sendMessage(tabs[0].id, { type: 'play' });
});
});
document.getElementById('pause').addEventListener('click', () => {
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
chrome.tabs.sendMessage(tabs[0].id, { type: 'pause' });
});
});
document.getElementById('resume').addEventListener('click', () => {
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
chrome.tabs.sendMessage(tabs[0].id, { type: 'resume' });
});
});
});
Notes:
- Loading Media:
- When the Load button is clicked, a new tab is opened with
newtab.html.
- Once the new tab is fully loaded (
status === 'complete'), a message is sent containing the media details.
- Control Buttons:
- Send messages to the active tab to control playback.
5. newtab.html
This HTML file is loaded in the new tab and is responsible for playing the media based on the received instructions.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Syncwaves Player</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>Syncwaves Player</h1>
<div id="player-container"></div>
<script src="newtab.js"></script>
</body>
</html>
6. newtab.js
Handles receiving messages from the popup and controlling media playback accordingly.
// newtab.js
let mediaType = null; // 'audio' or 'video'
let mediaElement = null;
let startTime = 0;
let resumeTime = 0;
// Listen for messages from the popup
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.type === 'load-media') {
mediaType = request.media;
startTime = request.startTime;
if (request.url) {
if (mediaType === 'audio') {
loadYouTubeAudio(request.url);
} else if (mediaType === 'video') {
loadYouTubeVideo(request.url);
}
} else if (request.file) {
loadLocalMedia(request.file, mediaType);
}
} else if (request.type === 'play') {
if (mediaElement) mediaElement.play();
} else if (request.type === 'pause') {
if (mediaElement) mediaElement.pause();
} else if (request.type === 'resume') {
if (mediaElement) {
mediaElement.currentTime = resumeTime;
mediaElement.play();
}
}
});
function loadYouTubeVideo(url) {
const videoId = extractYouTubeID(url);
if (!videoId) {
alert('Invalid YouTube URL');
return;
}
const iframe = document.createElement('iframe');
iframe.src = `https://www.youtube.com/embed/${videoId}?enablejsapi=1&autoplay=0`;
iframe.width = '640';
iframe.height = '360';
iframe.allow = 'autoplay; encrypted-media';
iframe.frameBorder = '0';
document.getElementById('player-container').appendChild(iframe);
// Load YouTube IFrame API
const tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
document.body.appendChild(tag);
window.onYouTubeIframeAPIReady = function() {
const player = new YT.Player(iframe, {
events: {
'onReady': (event) => {
mediaElement = player;
// Play for 1/8th of a second then pause
player.playVideo();
setTimeout(() => {
player.pauseVideo();
player.seekTo(startTime, true);
}, 125);
}
}
});
};
}
function loadYouTubeAudio(url) {
const videoId = extractYouTubeID(url);
if (!videoId) {
alert('Invalid YouTube URL');
return;
}
// Extract audio using YouTube Audio API workaround
const audio = document.createElement('audio');
audio.controls = true;
audio.src = `https://www.youtube.com/watch?v=${videoId}`; // Note: Direct audio extraction might not work due to CORS
document.getElementById('player-container').appendChild(audio);
mediaElement = audio;
audio.addEventListener('loadedmetadata', () => {
audio.play();
setTimeout(() => {
audio.pause();
audio.currentTime = startTime;
}, 125);
});
}
function loadLocalMedia(fileURL, type) {
if (type === 'audio') {
const audio = document.createElement('audio');
audio.controls = true;
audio.src = fileURL;
document.getElementById('player-container').appendChild(audio);
mediaElement = audio;
audio.addEventListener('loadedmetadata', () => {
audio.play();
setTimeout(() => {
audio.pause();
audio.currentTime = startTime;
}, 125);
});
} else if (type === 'video') {
const video = document.createElement('video');
video.controls = true;
video.src = fileURL;
video.width = 640;
video.height = 360;
document.getElementById('player-container').appendChild(video);
mediaElement = video;
video.addEventListener('loadedmetadata', () => {
video.play();
setTimeout(() => {
video.pause();
video.currentTime = startTime;
}, 125);
});
}
}
function extractYouTubeID(url) {
const regex = /(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/ ]{11})/;
const match = url.match(regex);
return match ? match[1] : null;
}
Important Notes:
-
YouTube Audio Playback:
- Due to YouTube's CORS policies and restrictions on direct audio streaming from URLs, playing YouTube audio directly using the
<audio> element as shown might not work. A more robust solution would involve using the YouTube IFrame Player API for audio, but it’s more complex.
- Alternatively, consider using the YouTube API to extract audio streams legally and ethically, ensuring compliance with YouTube's Terms of Service.
-
Playback Control:
- The
play, pause, and resume functionalities are implemented for local media. For YouTube videos via the IFrame API, control is handled through the YT.Player instance.
-
Playing for 1/8th of a Second:
- Implemented using
setTimeout to pause the media after 125 milliseconds (1/8th of a second) and set the currentTime to the user-specified start time.
-
Error Handling:
- Basic error handling is implemented (e.g., invalid YouTube URLs). You may want to expand this based on specific needs.
7. icons/icon.png
Provide an icon for your extension. It's recommended to include icons of sizes 16x16, 48x48, and 128x128 pixels. Place them in the icons/ directory as referenced in the manifest.json.
Installation Steps
-
Prepare the Extension Files:
- Create a directory named
syncwaves.
- Inside this directory, create the files as described above (
manifest.json, popup.html, popup.js, newtab.html, newtab.js, styles.css).
- Add an
icons folder and place your icon image(s) inside.
-
Load the Extension in Chrome:
- Open Chrome and navigate to
chrome://extensions/.
- Enable "Developer mode" using the toggle switch in the top right corner.
- Click on "Load unpacked" and select the
syncwaves directory you created.
-
Usage:
- Click on the Syncwaves extension icon in the Chrome toolbar to open the popup.
- In the Audio or Video section, enter a YouTube URL or load a local file.
- Specify the start time in seconds.
- Click the Load button to open the media in a new tab.
- Use the Play, Pause, and Resume buttons in the popup to control playback in the new tab.
Compliance with Content Security Policy (CSP)
Potential Enhancements and Considerations
-
YouTube Audio Playback:
- Due to restrictions, consider implementing the YouTube IFrame API for better control over audio streams.
- Alternatively, use the YouTube Data API to fetch audio metadata.
-
File Type Validation:
- Enhance the file input elements to strictly accept only supported audio/video formats.
- Provide user feedback if unsupported files are selected.
-
Error Handling:
- Implement more robust error handling for network issues, unsupported URLs, and media playback errors.
-
UI/UX Improvements:
- Improve the styling and layout for better user experience.
- Provide progress indicators or status messages during media loading and playback.
-
Testing:
- Test the extension thoroughly with various YouTube URLs and local files to ensure compatibility and stability.