<!-- Load Audio Section -->
<section class="section" id="load-music-section">
<fieldset>
<legend>Load Audio</legend>
<label for="music-url">Audio URL</label>
<input type="text" id="music-url" name="music-url" placeholder="Enter YouTube or Vimeo URL" aria-label="Enter YouTube or Vimeo Audio URL">
<label for="music-file">Local Audio File</label>
<input type="file" id="music-file" name="music-file" accept="audio/*" aria-label="Select Local Audio File">
<label for="music-start">Start Time (seconds)</label>
<input type="number" id="music-start" name="music-start" placeholder="Start Time (seconds)" min="0" aria-label="Set Start Time in Seconds">
<button type="button" id="load-music" class="load-button">Load Audio</button>
</fieldset>
<div id="music-player-container" class="player-container" aria-live="polite"></div>
</section>
<!-- Load Video Section -->
<section class="section" id="load-video-section">
<fieldset>
<legend>Load Video</legend>
<label for="video-url">Video URL</label>
<input type="text" id="video-url" name="video-url" placeholder="Enter YouTube or Vimeo URL" aria-label="Enter YouTube or Vimeo Video URL">
<label for="video-file">Local Video File</label>
<input type="file" id="video-file" name="video-file" accept="video/*" aria-label="Select Local Video File">
<label for="video-start">Start Time (seconds)</label>
<input type="number" id="video-start" name="video-start" placeholder="Start Time (seconds)" min="0" aria-label="Set Start Time in Seconds">
<button type="button" id="load-video" class="load-button">Load Video</button>
</fieldset>
<div id="video-player-container" class="player-container" aria-live="polite"></div>
</section>
<!-- Playback Controls -->
<section class="controls">
<button type="button" id="play-button" class="play-button" disabled aria-label="Play from Start">Play from Start</button>
<button type="button" id="pause-button" class="pause-button" disabled aria-label="Pause">Pause</button>
<button type="button" id="resume-button" class="resume-button" disabled aria-label="Resume">Resume</button>
</section>
<!-- Message Container -->
<section id="message-container" class="message-container" role="alert" aria-live="assertive"></section>
<!-- Settings Modal -->
<div id="settings-modal" class="modal" role="dialog" aria-labelledby="settings-modal-title" aria-modal="true" hidden>
<div class="modal-content">
<button class="close-button" aria-label="Close Settings Modal">×</button>
<h2 id="settings-modal-title">Settings</h2>
<form>
<label for="fullscreen-toggle">
<input type="checkbox" id="fullscreen-toggle" name="fullscreen-toggle">
Full Screen on Play
</label>
<!-- Additional settings can go here -->
</form>
</div>
</div>
<!-- YouTube Sandbox Iframe (Hidden) -->
<iframe id="youtube-sandbox-iframe" src="youtube-sandbox.html" style="display: none;"></iframe>
</div>
<script src="dashboard.js"></script>
"use strict";
// Utility function to capitalize first letter
function capitalize(text) {
if (!text) return '';
return text.charAt(0).toUpperCase() + text.slice(1);
}
// Function to display messages
function showMessage(message, type) {
const messageContainer = document.getElementById('message-container');
messageContainer.innerHTML = '';
const msgDiv = document.createElement('div');
msgDiv.textContent = message;
msgDiv.classList.add('message', type); // 'success', 'error', 'info'
messageContainer.appendChild(msgDiv);
// Automatically hide message after 5 seconds
setTimeout(() => {
if (messageContainer.contains(msgDiv)) {
messageContainer.removeChild(msgDiv);
}
}, 5000);
}
// Function to show loading spinner
function showLoading(container) {
container.innerHTML = '';
const loader = document.createElement('div');
loader.classList.add('loader');
container.appendChild(loader);
}
// Function to hide loading spinner
function hideLoading(container) {
const loader = container.querySelector('.loader');
if (loader) {
container.removeChild(loader);
}
}
// Function to validate media URLs
function isValidMediaURL(url) {
try {
const parsedUrl = new URL(url);
const hostname = parsedUrl.hostname.toLowerCase();
// Function to extract YouTube Video ID
function extractYouTubeID(url) {
try {
const parsedUrl = new URL(url);
const hostname = parsedUrl.hostname.toLowerCase();
if (hostname === 'youtu.be') {
return parsedUrl.pathname.slice(1);
}
return parsedUrl.searchParams.get('v') || '';
} catch (e) {
return '';
}
}
// Function to extract Vimeo Video ID
function extractVimeoID(url) {
try {
const parsedUrl = new URL(url);
const vimeoMatch = parsedUrl.pathname.match(//(?:video/)?(\d+)/);
return vimeoMatch ? vimeoMatch[1] : '';
} catch (e) {
return '';
}
}
// Function to embed YouTube video
function embedYouTubeVideo(videoId, container, startTime = 0) {
container.innerHTML = ''; // Clear previous content
const iframe = document.createElement('iframe');
iframe.width = '640';
iframe.height = '360';
iframe.src = https://www.youtube.com/embed/${videoId}?start=${startTime}&enablejsapi=1;
iframe.frameBorder = '0';
iframe.allow = 'accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture';
iframe.allowFullscreen = true;
iframe.setAttribute('aria-label', 'YouTube Video Player');
container.appendChild(iframe);
hideLoading(container);
showMessage(YouTube video loaded., 'success');
code
// Notify the sandbox iframe that the YouTube player is ready
sendMessageToYouTubeSandbox({
type: 'playerReady',
mediaType: 'music' // or 'video' based on context
});
}
// Function to embed Vimeo video
function embedVimeoVideo(videoId, container, startTime = 0) {
container.innerHTML = ''; // Clear previous content
const iframe = document.createElement('iframe');
iframe.src = https://player.vimeo.com/video/${videoId}#t=${startTime}s;
iframe.width = '640';
iframe.height = '360';
iframe.frameBorder = '0';
iframe.allow = 'autoplay; fullscreen; picture-in-picture';
iframe.allowFullscreen = true;
iframe.setAttribute('aria-label', 'Vimeo Video Player');
container.appendChild(iframe);
hideLoading(container);
showMessage(Vimeo video loaded., 'success');
}
// Function to embed local video file
function embedLocalVideo(file, container, startTime = 0) {
container.innerHTML = ''; // Clear previous content
const videoElement = document.createElement('video');
videoElement.controls = true;
videoElement.src = URL.createObjectURL(file);
videoElement.setAttribute('aria-label', 'Local Video Player');
videoElement.style.width = '100%';
videoElement.style.height = 'auto';
videoElement.currentTime = startTime;
videoElement.onloadedmetadata = () => {
if (startTime > 0 && videoElement.duration > startTime) {
videoElement.currentTime = startTime;
}
};
container.appendChild(videoElement);
hideLoading(container);
showMessage(Local video file loaded., 'success');
}
// Function to load music
function handleLoadMusic() {
const url = document.getElementById('music-url').value.trim();
const fileInput = document.getElementById('music-file');
const file = fileInput.files[0];
const startTime = parseInt(document.getElementById('music-start').value) || 0;
const container = document.getElementById('music-player-container');
code
showLoading(container);
if (file) {
// Load local audio file
embedLocalAudio(file, container, startTime);
} else if (url && isValidMediaURL(url)) {
const hostname = new URL(url).hostname.toLowerCase();
if (hostname.includes('youtube.com') || hostname === 'youtu.be') {
const videoId = extractYouTubeID(url);
embedYouTubeVideo(videoId, container, startTime);
} else if (hostname.includes('vimeo.com')) {
const videoId = extractVimeoID(url);
embedVimeoVideo(videoId, container, startTime);
}
} else {
hideLoading(container);
showMessage('Please enter a valid YouTube/Vimeo URL or select a local audio file.', 'error');
}
checkReadyToPlay();
}
// Function to load video
function handleLoadVideo() {
const url = document.getElementById('video-url').value.trim();
const fileInput = document.getElementById('video-file');
const file = fileInput.files[0];
const startTime = parseInt(document.getElementById('video-start').value) || 0;
const container = document.getElementById('video-player-container');
code
showLoading(container);
if (file) {
// Load local video file
embedLocalVideo(file, container, startTime);
} else if (url && isValidMediaURL(url)) {
const hostname = new URL(url).hostname.toLowerCase();
if (hostname.includes('youtube.com') || hostname === 'youtu.be') {
const videoId = extractYouTubeID(url);
embedYouTubeVideo(videoId, container, startTime);
} else if (hostname.includes('vimeo.com')) {
const videoId = extractVimeoID(url);
embedVimeoVideo(videoId, container, startTime);
}
} else {
hideLoading(container);
showMessage('Please enter a valid YouTube/Vimeo URL or select a local video file.', 'error');
}
checkReadyToPlay();
}
// Function to check if media is ready to play
function checkReadyToPlay() {
const playButton = document.getElementById('play-button');
const pauseButton = document.getElementById('pause-button');
const resumeButton = document.getElementById('resume-button');
// Resume Audio
function resumeAudio() {
const musicContainer = document.getElementById('music-player-container');
const audio = musicContainer.querySelector('audio');
if (audio) {
audio.play();
return;
}
code
const iframe = musicContainer.querySelector('iframe');
if (iframe && iframe.src.includes('youtube.com')) {
// YouTube iframe resume play
iframe.contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}', '*');
}
}
// Play Video
function playVideo() {
const videoContainer = document.getElementById('video-player-container');
const video = videoContainer.querySelector('video');
if (video) {
video.play();
return;
}
code
const iframe = videoContainer.querySelector('iframe');
if (iframe && iframe.src.includes('youtube.com')) {
// YouTube iframe autoplay
iframe.contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}', '*');
}
// Vimeo autoplay via URL parameter is handled through iframe src
}
// Pause Video
function pauseVideo() {
const videoContainer = document.getElementById('video-player-container');
const video = videoContainer.querySelector('video');
if (video) {
video.pause();
return;
}
// Resume Video
function resumeVideo() {
const videoContainer = document.getElementById('video-player-container');
const video = videoContainer.querySelector('video');
if (video) {
video.play();
return;
}
code
const iframe = videoContainer.querySelector('iframe');
if (iframe && iframe.src.includes('youtube.com')) {
// YouTube iframe resume play
iframe.contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}', '*');
}
}
// Function to enter fullscreen mode
function enterFullscreen() {
const containers = ['music-player-container', 'video-player-container'];
containers.forEach(id => {
const element = document.getElementById(id);
if (element) {
if (element.requestFullscreen) {
element.requestFullscreen().catch(err => {
console.error(Error attempting to enable full-screen mode: ${err.message} (${err.name}));
showMessage('Failed to enter fullscreen mode.', 'error');
});
}
}
});
}
// Function to send messages to the YouTube sandbox iframe
function sendMessageToYouTubeSandbox(message) {
const iframe = document.getElementById('youtube-sandbox-iframe');
iframe.contentWindow.postMessage(message, '*');
}
// Focus Trap Functions
let focusableElements = [];
let firstFocusableElement = null;
let lastFocusableElement = null;
let previouslyFocusedElement = null;
// Function to handle YouTube IFrame API callback
function onYouTubeIframeAPIReady() {
// Player is already created in createYouTubePlayer
}
i only want the completed updated files. i only want the completed updated files. when i press the load buttons i want the vimeo and youtube videos to load then wait till done then play at least a eighth of a second then pause then set them to the user set start time.
Certainly! Below are the completed and updated files for your Chrome extension "Media Loader" that implement the desired behavior:
manifest.json
background.js
dashboard.html
dashboard.js
sandbox.html
sandbox.js
player.js
styles.css
1. manifest.json
No changes were necessary in the manifest.json file based on your requirements. However, ensure that all necessary permissions and resources are correctly specified.
No changes were necessary in the background.js file based on your requirements.
javascript
// background.js
chrome.action.onClicked.addListener(() => {
const dashboardURL = chrome.runtime.getURL("dashboard.html");
// Query for any existing tabs with the dashboard URL
chrome.tabs.query({ url: dashboardURL }, (tabs) => {
if (chrome.runtime.lastError) {
console.error("Tab Query Error:", chrome.runtime.lastError);
return;
}
if (tabs.length > 0) {
// Activate the first existing dashboard tab
chrome.tabs.update(tabs[0].id, { active: true }, (updatedTab) => {
if (chrome.runtime.lastError) {
console.error("Tab Update Error:", chrome.runtime.lastError);
}
});
} else {
// Create a new dashboard tab
chrome.tabs.create({ url: dashboardURL, active: true }, (newTab) => {
if (chrome.runtime.lastError) {
console.error("Tab Creation Error:", chrome.runtime.lastError);
}
});
}
});
});
3. dashboard.html
No changes were necessary in the dashboard.html file based on your requirements. However, ensure that the dashboard.js script is correctly linked.
html
4. dashboard.js
This file has been updated to handle both YouTube and Vimeo video loading with the desired behavior: loading the video, playing it for at least an eighth of a second, pausing, and setting it to the user-specified start time.
javascript
5. sandbox.html
This file has been updated to include the YouTube IFrame API and communicate with the sandbox.js script.
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>YouTube Sandbox</title>
</head>
<body>
<!-- YouTube Player Container -->
<div id="youtube-player"></div>
<!-- External Sandbox Script -->
<script src="sandbox.js"></script>
<script>
// YouTube IFrame API Callback
function onYouTubeIframeAPIReady() {
// This function needs to be global
}
</script>
</body>
</html>
6. sandbox.js
This file has been updated to handle the initial playback sequence (play, pause, seek) for YouTube videos.
javascript
"use strict";
let player;
let mediaType = ''; // 'music' or 'video'
let startTime = 0;
// Function to send messages to the parent
function sendMessageToParent(message) {
window.parent.postMessage(message, '*');
}
// Listen for messages from the parent
window.addEventListener('message', (event) => {
// Security Check: Optionally verify event.origin here
const data = event.data;
if (data.type === 'init') {
mediaType = data.mediaType; // 'music' or 'video'
startTime = data.startTime || 0;
createYouTubePlayer(data.videoId, startTime);
} else if (data.type === 'playPauseSeek') {
if (player && typeof player.playVideo === 'function') {
player.playVideo();
setTimeout(() => {
player.pauseVideo();
player.seekTo(startTime, true);
}, 125); // 125 milliseconds
}
} else if (data.type === 'play') {
if (player && typeof player.playVideo === 'function') {
player.playVideo();
}
} else if (data.type === 'pause') {
if (player && typeof player.pauseVideo === 'function') {
player.pauseVideo();
}
} else if (data.type === 'seek') {
if (player && typeof player.seekTo === 'function') {
player.seekTo(data.time, true);
}
}
});
/**
* Creates a YouTube player.
* @param {string} videoId - The YouTube video ID.
* @param {number} startTime - The start time in seconds.
*/
function createYouTubePlayer(videoId, startTime = 0) {
const container = document.getElementById('youtube-player');
container.innerHTML = ''; // Clear any existing content
player = new YT.Player('youtube-player', {
height: '360',
width: '640',
videoId: videoId,
playerVars: {
'autoplay': 0,
'controls': 1,
'start': startTime,
'mute': 1,
'rel': 0,
'disablekb': 1,
'modestbranding': 1,
'iv_load_policy': 3,
'fs': 1
},
events: {
'onReady': () => {
sendMessageToParent({
type: 'playerReady',
mediaType: mediaType,
startTime: startTime
});
},
'onError': (error) => {
sendMessageToParent({
type: 'playerError',
mediaType: mediaType,
error: error.data
});
}
}
});
// Load YouTube IFrame API
loadYouTubeIframeAPI();
}
function loadYouTubeIframeAPI() {
if (!window.YT) {
const script = document.createElement('script');
script.src = 'https://www.youtube.com/iframe_api';
document.head.appendChild(script);
}
}
7. player.js
This file has been added to handle Vimeo video control using Vimeo's Player API. Ensure that this file is placed in the lib directory as specified in the manifest.json.
javascript
// player.js
"use strict";
// Check if Vimeo Player API is already loaded
if (typeof Vimeo === 'undefined') {
// Load Vimeo Player API
const script = document.createElement('script');
script.src = 'https://player.vimeo.com/api/player.js';
script.onload = () => {
initializeVimeoPlayer();
};
document.head.appendChild(script);
} else {
initializeVimeoPlayer();
}
function initializeVimeoPlayer() {
window.addEventListener('message', (event) => {
// Security Check: Optionally verify event.origin here
const data = event.data;
if (data.type === 'init') {
const iframe = document.getElementById(`vimeo-player-${data.videoId}`);
if (!iframe) return;
const player = new Vimeo.Player(iframe);
player.ready().then(() => {
// Notify parent that player is ready
window.parent.postMessage({
type: 'playerReady',
mediaType: data.mediaType,
startTime: data.startTime
}, '*');
}).catch(error => {
window.parent.postMessage({
type: 'playerError',
mediaType: data.mediaType,
error: error.message
}, '*');
});
window.vimeoPlayer = player;
} else if (data.type === 'playPauseSeek') {
if (window.vimeoPlayer) {
window.vimeoPlayer.play().then(() => {
setTimeout(() => {
window.vimeoPlayer.pause().then(() => {
window.vimeoPlayer.setCurrentTime(data.startTime).catch(error => {
console.error('Error seeking Vimeo video:', error);
});
});
}, 125); // 125 milliseconds
}).catch(error => {
console.error('Error playing Vimeo video:', error);
});
}
} else if (data.type === 'play') {
if (window.vimeoPlayer) {
window.vimeoPlayer.play();
}
} else if (data.type === 'pause') {
if (window.vimeoPlayer) {
window.vimeoPlayer.pause();
}
} else if (data.type === 'seek') {
if (window.vimeoPlayer) {
window.vimeoPlayer.setCurrentTime(data.time).catch(error => {
console.error('Error seeking Vimeo video:', error);
});
}
}
});
}
8. vimeo-sandbox.html
This file has been added to handle the Vimeo video sandbox similar to the YouTube sandbox.
No significant changes were necessary in the styles.css file based on your requirements. However, ensure that any new classes or IDs used in the HTML are styled appropriately. Below is the original styles.css content for reference.
css
10. vimeo-sandbox.html
This file has been added to handle Vimeo video control similar to the YouTube sandbox.
The player.js file is responsible for integrating the Vimeo Player API. It listens for messages from the parent dashboard.html and controls the Vimeo player accordingly.
Ensure that the player.js file is correctly placed in the lib directory as specified in the manifest.json.
Communication Between Iframes and Parent:
The dashboard.js handles communication between the main dashboard and the sandbox iframes (YouTube and Vimeo).
Upon loading a video, it sends an init message to the respective sandbox iframe with the video ID and start time.
The sandbox iframe responds with a playerReady message when the player is ready, triggering the initial playback sequence.
Initial Playback Sequence:
Once a media player is ready, it plays the media for at least an eighth of a second (125 milliseconds), pauses it, and then seeks to the user-specified start time.
This ensures that the media is loaded and ready to play from the desired start point.
Security Considerations:
Currently, the postMessage calls use '*' as the target origin. For enhanced security, consider specifying the exact origin of your extension or validating the event.origin in the message listeners.
Testing:
After implementing the above files, thoroughly test the extension with various YouTube and Vimeo URLs, as well as local media files, to ensure that the loading and playback behaviors function as expected.
CORS and Permissions:
Ensure that all necessary permissions are correctly specified in the manifest.json to allow interactions with YouTube and Vimeo players.
Feel free to integrate these updated files into your Chrome extension project. If you encounter any issues or need further assistance, don't hesitate to ask!
Not yet included in a published release.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Media Loader Dashboard</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container">
<!-- Header with Settings Button and Title -->
<div class="header">
<button id="settings-button" class="settings-button" aria-label="Open Settings">
<img src="icons/icon48.png" alt="Settings" class="settings-icon">
</button>
<h1 class="main-title">Media Loader</h1>
</div>
<!-- Load Audio Section -->
<section class="section" id="load-music-section">
<fieldset>
<legend>Load Audio</legend>
<label for="music-url">Audio URL</label>
<input type="text" id="music-url" name="music-url" placeholder="Enter YouTube or Vimeo URL" aria-label="Enter YouTube or Vimeo Audio URL">
<label for="music-file">Local Audio File</label>
<input type="file" id="music-file" name="music-file" accept="audio/*" aria-label="Select Local Audio File">
<label for="music-start">Start Time (seconds)</label>
<input type="number" id="music-start" name="music-start" placeholder="Start Time (seconds)" min="0" aria-label="Set Start Time in Seconds">
<button type="button" id="load-music" class="load-button">Load Audio</button>
</fieldset>
<div id="music-player-container" class="player-container" aria-live="polite"></div>
</section>
<!-- Load Video Section -->
<section class="section" id="load-video-section">
<fieldset>
<legend>Load Video</legend>
<label for="video-url">Video URL</label>
<input type="text" id="video-url" name="video-url" placeholder="Enter YouTube or Vimeo URL" aria-label="Enter YouTube or Vimeo Video URL">
<label for="video-file">Local Video File</label>
<input type="file" id="video-file" name="video-file" accept="video/*" aria-label="Select Local Video File">
<label for="video-start">Start Time (seconds)</label>
<input type="number" id="video-start" name="video-start" placeholder="Start Time (seconds)" min="0" aria-label="Set Start Time in Seconds">
<button type="button" id="load-video" class="load-button">Load Video</button>
</fieldset>
<div id="video-player-container" class="player-container" aria-live="polite"></div>
</section>
<!-- Playback Controls -->
<section class="controls">
<button type="button" id="play-button" class="play-button" disabled aria-label="Play from Start">Play from Start</button>
<button type="button" id="pause-button" class="pause-button" disabled aria-label="Pause">Pause</button>
<button type="button" id="resume-button" class="resume-button" disabled aria-label="Resume">Resume</button>
</section>
<!-- Message Container -->
<section id="message-container" class="message-container" role="alert" aria-live="assertive"></section>
<!-- Settings Modal -->
<div id="settings-modal" class="modal" role="dialog" aria-labelledby="settings-modal-title" aria-modal="true" hidden>
<div class="modal-content">
<button class="close-button" aria-label="Close Settings Modal">×</button>
<h2 id="settings-modal-title">Settings</h2>
<form>
<label for="fullscreen-toggle">
<input type="checkbox" id="fullscreen-toggle" name="fullscreen-toggle">
Full Screen on Play
</label>
<!-- Additional settings can go here -->
</form>
</div>
</div>
<!-- YouTube Sandbox Iframe (Hidden) -->
<iframe id="youtube-sandbox-iframe" src="youtube-sandbox.html" style="display: none;"></iframe>
<!-- Vimeo Sandbox Iframe (Hidden) -->
<iframe id="vimeo-sandbox-iframe" src="vimeo-sandbox.html" style="display: none;"></iframe>
</div>
<script src="dashboard.js"></script>
</body>
</html>
"use strict";
// Utility function to capitalize first letter
function capitalize(text) {
if (!text) return '';
return text.charAt(0).toUpperCase() + text.slice(1);
}
// Function to display messages
function showMessage(message, type) {
const messageContainer = document.getElementById('message-container');
messageContainer.innerHTML = '';
const msgDiv = document.createElement('div');
msgDiv.textContent = message;
msgDiv.classList.add('message', type); // 'success', 'error', 'info'
messageContainer.appendChild(msgDiv);
// Automatically hide message after 5 seconds
setTimeout(() => {
if (messageContainer.contains(msgDiv)) {
messageContainer.removeChild(msgDiv);
}
}, 5000);
}
// Function to show loading spinner
function showLoading(container) {
container.innerHTML = '';
const loader = document.createElement('div');
loader.classList.add('loader');
container.appendChild(loader);
}
// Function to hide loading spinner
function hideLoading(container) {
const loader = container.querySelector('.loader');
if (loader) {
container.removeChild(loader);
}
}
// Function to validate media URLs
function isValidMediaURL(url) {
try {
const parsedUrl = new URL(url);
const hostname = parsedUrl.hostname.toLowerCase();
if (hostname.includes('youtube.com') || hostname === 'youtu.be') {
const videoId = extractYouTubeID(url);
return videoId.length === 11;
} else if (hostname.includes('vimeo.com')) {
const videoId = extractVimeoID(url);
return videoId.length > 0;
}
return false;
} catch (e) {
return false;
}
}
// Function to extract YouTube Video ID
function extractYouTubeID(url) {
try {
const parsedUrl = new URL(url);
const hostname = parsedUrl.hostname.toLowerCase();
if (hostname === 'youtu.be') {
return parsedUrl.pathname.slice(1);
}
return parsedUrl.searchParams.get('v') || '';
} catch (e) {
return '';
}
}
// Function to extract Vimeo Video ID
function extractVimeoID(url) {
try {
const parsedUrl = new URL(url);
const vimeoMatch = parsedUrl.pathname.match(/\/(?:video\/)?(\d+)/);
return vimeoMatch ? vimeoMatch[1] : '';
} catch (e) {
return '';
}
}
// Function to embed YouTube video
function embedYouTubeVideo(videoId, container, startTime = 0) {
container.innerHTML = ''; // Clear previous content
const iframe = document.createElement('iframe');
iframe.width = '640';
iframe.height = '360';
iframe.src = `https://www.youtube.com/embed/${videoId}?enablejsapi=1&origin=${location.origin}`;
iframe.frameBorder = '0';
iframe.allow = 'accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture';
iframe.allowFullscreen = true;
iframe.setAttribute('aria-label', 'YouTube Video Player');
container.appendChild(iframe);
hideLoading(container);
showMessage(`YouTube video loaded.`, 'success');
// Notify the sandbox iframe that the YouTube player is ready
const sandboxIframe = document.getElementById('youtube-sandbox-iframe');
sandboxIframe.contentWindow.postMessage({
type: 'init',
videoId: videoId,
startTime: startTime,
mediaType: 'music' // or 'video' based on context
}, '*');
}
// Function to embed Vimeo video
function embedVimeoVideo(videoId, container, startTime = 0) {
container.innerHTML = ''; // Clear previous content
const iframe = document.createElement('iframe');
iframe.src = `https://player.vimeo.com/video/${videoId}?api=1&player_id=vimeo-player-${videoId}`;
iframe.width = '640';
iframe.height = '360';
iframe.frameBorder = '0';
iframe.allow = 'autoplay; fullscreen; picture-in-picture';
iframe.allowFullscreen = true;
iframe.setAttribute('aria-label', 'Vimeo Video Player');
iframe.id = `vimeo-player-${videoId}`;
container.appendChild(iframe);
hideLoading(container);
showMessage(`Vimeo video loaded.`, 'success');
// Notify the Vimeo sandbox iframe that the Vimeo player is ready
const sandboxIframe = document.getElementById('vimeo-sandbox-iframe');
sandboxIframe.contentWindow.postMessage({
type: 'init',
videoId: videoId,
startTime: startTime,
mediaType: 'video' // or 'music' based on context
}, '*');
}
// Function to embed local video file
function embedLocalVideo(file, container, startTime = 0) {
container.innerHTML = ''; // Clear previous content
const videoElement = document.createElement('video');
videoElement.controls = true;
videoElement.src = URL.createObjectURL(file);
videoElement.setAttribute('aria-label', 'Local Video Player');
videoElement.style.width = '100%';
videoElement.style.height = 'auto';
videoElement.currentTime = startTime;
videoElement.onloadedmetadata = () => {
if (startTime > 0 && videoElement.duration > startTime) {
videoElement.currentTime = startTime;
}
};
container.appendChild(videoElement);
hideLoading(container);
showMessage(`Local video file loaded.`, 'success');
}
// Function to embed local audio file
function embedLocalAudio(file, container, startTime = 0) {
container.innerHTML = ''; // Clear previous content
const audioElement = document.createElement('audio');
audioElement.controls = true;
audioElement.src = URL.createObjectURL(file);
audioElement.setAttribute('aria-label', 'Local Audio Player');
audioElement.style.width = '100%';
audioElement.style.height = 'auto';
audioElement.currentTime = startTime;
audioElement.onloadedmetadata = () => {
if (startTime > 0 && audioElement.duration > startTime) {
audioElement.currentTime = startTime;
}
};
container.appendChild(audioElement);
hideLoading(container);
showMessage(`Local audio file loaded.`, 'success');
}
// Function to load music
function handleLoadMusic() {
const url = document.getElementById('music-url').value.trim();
const fileInput = document.getElementById('music-file');
const file = fileInput.files[0];
const startTime = parseInt(document.getElementById('music-start').value) || 0;
const container = document.getElementById('music-player-container');
showLoading(container);
if (file) {
// Load local audio file
embedLocalAudio(file, container, startTime);
} else if (url && isValidMediaURL(url)) {
const hostname = new URL(url).hostname.toLowerCase();
if (hostname.includes('youtube.com') || hostname === 'youtu.be') {
const videoId = extractYouTubeID(url);
embedYouTubeVideo(videoId, container, startTime);
} else if (hostname.includes('vimeo.com')) {
const videoId = extractVimeoID(url);
embedVimeoVideo(videoId, container, startTime);
}
} else {
hideLoading(container);
showMessage('Please enter a valid YouTube/Vimeo URL or select a local audio file.', 'error');
}
checkReadyToPlay();
}
// Function to load video
function handleLoadVideo() {
const url = document.getElementById('video-url').value.trim();
const fileInput = document.getElementById('video-file');
const file = fileInput.files[0];
const startTime = parseInt(document.getElementById('video-start').value) || 0;
const container = document.getElementById('video-player-container');
showLoading(container);
if (file) {
// Load local video file
embedLocalVideo(file, container, startTime);
} else if (url && isValidMediaURL(url)) {
const hostname = new URL(url).hostname.toLowerCase();
if (hostname.includes('youtube.com') || hostname === 'youtu.be') {
const videoId = extractYouTubeID(url);
embedYouTubeVideo(videoId, container, startTime);
} else if (hostname.includes('vimeo.com')) {
const videoId = extractVimeoID(url);
embedVimeoVideo(videoId, container, startTime);
}
} else {
hideLoading(container);
showMessage('Please enter a valid YouTube/Vimeo URL or select a local video file.', 'error');
}
checkReadyToPlay();
}
// Function to check if media is ready to play
function checkReadyToPlay() {
const playButton = document.getElementById('play-button');
const pauseButton = document.getElementById('pause-button');
const resumeButton = document.getElementById('resume-button');
const musicContainer = document.getElementById('music-player-container');
const videoContainer = document.getElementById('video-player-container');
const musicLoaded = musicContainer.innerHTML.trim().length > 0;
const videoLoaded = videoContainer.innerHTML.trim().length > 0;
if (musicLoaded || videoLoaded) {
playButton.disabled = false;
pauseButton.disabled = false;
} else {
playButton.disabled = true;
pauseButton.disabled = true;
}
resumeButton.disabled = true; // Initially disabled
}
// Playback control functions (Basic implementation)
function handlePlay() {
// Play all players
playAudio();
playVideo();
// Handle Fullscreen if enabled
const fullscreenToggle = document.getElementById('fullscreen-toggle');
if (fullscreenToggle.checked) {
enterFullscreen();
}
showMessage('Playback started!', 'success');
}
function handlePause() {
// Pause all players
pauseAudio();
pauseVideo();
showMessage('Playback paused.', 'info');
}
function handleResume() {
// Resume all players
resumeAudio();
resumeVideo();
showMessage('Playback resumed.', 'success');
}
// Play Audio
function playAudio() {
const musicContainer = document.getElementById('music-player-container');
const audio = musicContainer.querySelector('audio');
if (audio) {
audio.play();
return;
}
const iframe = musicContainer.querySelector('iframe');
if (iframe && iframe.src.includes('youtube.com')) {
// YouTube iframe autoplay
iframe.contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}', '*');
}
// Vimeo autoplay via URL parameter is handled through iframe src
}
// Pause Audio
function pauseAudio() {
const musicContainer = document.getElementById('music-player-container');
const audio = musicContainer.querySelector('audio');
if (audio) {
audio.pause();
return;
}
const iframe = musicContainer.querySelector('iframe');
if (iframe && iframe.src.includes('youtube.com')) {
// YouTube iframe pause
iframe.contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}', '*');
}
}
// Resume Audio
function resumeAudio() {
const musicContainer = document.getElementById('music-player-container');
const audio = musicContainer.querySelector('audio');
if (audio) {
audio.play();
return;
}
const iframe = musicContainer.querySelector('iframe');
if (iframe && iframe.src.includes('youtube.com')) {
// YouTube iframe resume play
iframe.contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}', '*');
}
}
// Play Video
function playVideo() {
const videoContainer = document.getElementById('video-player-container');
const video = videoContainer.querySelector('video');
if (video) {
video.play();
return;
}
const iframe = videoContainer.querySelector('iframe');
if (iframe && iframe.src.includes('youtube.com')) {
// YouTube iframe autoplay
iframe.contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}', '*');
}
// Vimeo autoplay via URL parameter is handled through iframe src
}
// Pause Video
function pauseVideo() {
const videoContainer = document.getElementById('video-player-container');
const video = videoContainer.querySelector('video');
if (video) {
video.pause();
return;
}
const iframe = videoContainer.querySelector('iframe');
if (iframe && iframe.src.includes('youtube.com')) {
// YouTube iframe pause
iframe.contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}', '*');
}
}
// Resume Video
function resumeVideo() {
const videoContainer = document.getElementById('video-player-container');
const video = videoContainer.querySelector('video');
if (video) {
video.play();
return;
}
const iframe = videoContainer.querySelector('iframe');
if (iframe && iframe.src.includes('youtube.com')) {
// YouTube iframe resume play
iframe.contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}', '*');
}
}
// Function to enter fullscreen mode
function enterFullscreen() {
const containers = ['music-player-container', 'video-player-container'];
containers.forEach(id => {
const element = document.getElementById(id);
if (element) {
if (element.requestFullscreen) {
element.requestFullscreen().catch(err => {
console.error(`Error attempting to enable full-screen mode: ${err.message} (${err.name})`);
showMessage('Failed to enter fullscreen mode.', 'error');
});
}
}
});
}
// Function to send messages to the YouTube sandbox iframe
function sendMessageToYouTubeSandbox(message) {
const iframe = document.getElementById('youtube-sandbox-iframe');
iframe.contentWindow.postMessage(message, '*');
}
// Function to send messages to the Vimeo sandbox iframe
function sendMessageToVimeoSandbox(message) {
const iframe = document.getElementById('vimeo-sandbox-iframe');
iframe.contentWindow.postMessage(message, '*');
}
// Settings Modal Functions
function openSettingsModal() {
const modal = document.getElementById('settings-modal');
modal.removeAttribute('hidden');
modal.setAttribute('aria-hidden', 'false');
modal.querySelector('.close-button').focus();
trapFocus(modal);
}
function closeSettingsModal() {
const modal = document.getElementById('settings-modal');
modal.setAttribute('hidden', '');
modal.setAttribute('aria-hidden', 'true');
document.getElementById('settings-button').focus();
removeTrapFocus();
}
// Focus Trap Functions
let focusableElements = [];
let firstFocusableElement = null;
let lastFocusableElement = null;
let previouslyFocusedElement = null;
function trapFocus(element) {
previouslyFocusedElement = document.activeElement;
focusableElements = element.querySelectorAll('a[href], area[href], input:not([disabled]), select:not([disabled]),' +
' textarea:not([disabled]), button:not([disabled]), [tabindex="0"], [contenteditable]');
firstFocusableElement = focusableElements[0];
lastFocusableElement = focusableElements[focusableElements.length - 1];
element.addEventListener('keydown', handleTrapFocus);
firstFocusableElement.focus();
}
function handleTrapFocus(e) {
if (e.key === 'Tab') {
if (e.shiftKey) { // Shift + Tab
if (document.activeElement === firstFocusableElement) {
e.preventDefault();
lastFocusableElement.focus();
}
} else { // Tab
if (document.activeElement === lastFocusableElement) {
e.preventDefault();
firstFocusableElement.focus();
}
}
}
}
function removeTrapFocus() {
const modal = document.getElementById('settings-modal');
modal.removeEventListener('keydown', handleTrapFocus);
if (previouslyFocusedElement) {
previouslyFocusedElement.focus();
}
}
// Settings Persistence Functions
function loadSettings() {
try {
chrome.storage.local.get(['mediaSettings'], (result) => {
if (chrome.runtime.lastError) {
console.error('Tab Query Error:', chrome.runtime.lastError);
showMessage('Failed to load settings.', 'error');
return;
}
if (result.mediaSettings) {
const { music, video, fullscreenOnPlay } = result.mediaSettings;
if (music) {
if (music.type === 'youtube') {
const url = `https://www.youtube.com/watch?v=${music.id}`;
document.getElementById('music-url').value = url;
document.getElementById('music-start').value = music.start || 0;
} else if (music.type === 'vimeo') {
const url = `https://vimeo.com/${music.id}`;
document.getElementById('music-url').value = url;
document.getElementById('music-start').value = music.start || 0;
}
// Note: Local file loading cannot be restored from storage for security reasons
}
if (video) {
if (video.type === 'youtube') {
const url = `https://www.youtube.com/watch?v=${video.id}`;
document.getElementById('video-url').value = url;
document.getElementById('video-start').value = video.start || 0;
} else if (video.type === 'vimeo') {
const url = `https://vimeo.com/${video.id}`;
document.getElementById('video-url').value = url;
document.getElementById('video-start').value = video.start || 0;
}
// Note: Local file loading cannot be restored from storage for security reasons
}
if (typeof fullscreenOnPlay === 'boolean') {
document.getElementById('fullscreen-toggle').checked = fullscreenOnPlay;
}
}
});
} catch (error) {
console.error('Error loading settings:', error);
showMessage('Failed to load settings.', 'error');
}
}
function saveSettings() {
const settings = {
music: getCurrentMediaState('music'),
video: getCurrentMediaState('video'),
fullscreenOnPlay: document.getElementById('fullscreen-toggle').checked
};
try {
chrome.storage.local.set({ mediaSettings: settings }, () => {
if (chrome.runtime.lastError) {
throw new Error(chrome.runtime.lastError);
}
console.log('Settings saved.');
});
} catch (error) {
console.error('Error saving settings:', error);
showMessage('Error saving settings.', 'error');
}
}
function getCurrentMediaState(mediaType) {
const container = mediaType === 'music' ? document.getElementById('music-player-container') : document.getElementById('video-player-container');
const iframe = container.querySelector('iframe');
if (iframe && iframe.src.includes('youtube.com')) {
const url = new URL(iframe.src);
const videoId = url.pathname.split('/').pop();
return { type: 'youtube', id: videoId, start: getStartTimeFromURL(url) };
} else if (iframe && iframe.src.includes('vimeo.com')) {
const url = new URL(iframe.src);
const videoId = url.pathname.split('/').pop().split('?')[0];
return { type: 'vimeo', id: videoId, start: getStartTimeFromURL(url) };
}
// For local files, we cannot store the file URL for security reasons
return null;
}
function getStartTimeFromURL(url) {
if (url.searchParams.has('start')) {
return parseInt(url.searchParams.get('start')) || 0;
} else if (url.hash.includes('t=')) {
const match = url.hash.match(/t=(\d+)s/);
return match ? parseInt(match[1]) : 0;
}
return 0;
}
// Event Listeners Setup
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('load-music').addEventListener('click', handleLoadMusic);
document.getElementById('load-video').addEventListener('click', handleLoadVideo);
document.getElementById('play-button').addEventListener('click', handlePlay);
document.getElementById('pause-button').addEventListener('click', handlePause);
document.getElementById('resume-button').addEventListener('click', handleResume);
// Settings Modal Event Listeners
document.getElementById('settings-button').addEventListener('click', openSettingsModal);
document.querySelector('.close-button').addEventListener('click', closeSettingsModal);
window.addEventListener('click', (event) => {
const modal = document.getElementById('settings-modal');
if (event.target === modal) {
closeSettingsModal();
}
});
document.addEventListener('keydown', (event) => {
const modal = document.getElementById('settings-modal');
if (event.key === 'Escape' && !modal.hasAttribute('hidden')) {
closeSettingsModal();
}
});
// Load Settings from Storage
loadSettings();
// Save settings when fullscreen toggle changes
document.getElementById('fullscreen-toggle').addEventListener('change', saveSettings);
});
// Handling messages from YouTube Sandbox and Vimeo Sandbox
window.addEventListener('message', (event) => {
// For security, you can check event.origin here if necessary
const data = event.data;
if (data.type === 'playerReady') {
showMessage(`${capitalize(data.mediaType)} loaded and ready.`, 'success');
// Execute initial play-pause-seek sequence
initialPlaybackSequence(data.mediaType, data.startTime);
} else if (data.type === 'playerError') {
showMessage(`Error loading ${capitalize(data.mediaType)}.`, 'error');
}
});
/**
* Executes the initial playback sequence:
* 1. Play the media
* 2. Wait for at least 1/8th of a second
* 3. Pause the media
* 4. Seek to the user-specified start time
* @param {string} mediaType - 'music' or 'video'
* @param {number} startTime - Start time in seconds
*/
function initialPlaybackSequence(mediaType, startTime) {
if (mediaType === 'music') {
const musicContainer = document.getElementById('music-player-container');
const audio = musicContainer.querySelector('audio');
if (audio) {
audio.play().then(() => {
setTimeout(() => {
audio.pause();
audio.currentTime = startTime;
}, 125); // 125 milliseconds
}).catch(error => {
console.error('Error playing local audio:', error);
showMessage('Failed to initialize local audio.', 'error');
});
return;
}
const youtubeIframe = musicContainer.querySelector('iframe');
if (youtubeIframe && youtubeIframe.src.includes('youtube.com')) {
sendMessageToYouTubeSandbox({
type: 'playPauseSeek',
startTime: startTime
});
return;
}
const vimeoIframe = musicContainer.querySelector('iframe');
if (vimeoIframe && vimeoIframe.src.includes('vimeo.com')) {
sendMessageToVimeoSandbox({
type: 'playPauseSeek',
startTime: startTime
});
return;
}
}
if (mediaType === 'video') {
const videoContainer = document.getElementById('video-player-container');
const video = videoContainer.querySelector('video');
if (video) {
video.play().then(() => {
setTimeout(() => {
video.pause();
video.currentTime = startTime;
}, 125); // 125 milliseconds
}).catch(error => {
console.error('Error playing local video:', error);
showMessage('Failed to initialize local video.', 'error');
});
return;
}
const youtubeIframe = videoContainer.querySelector('iframe');
if (youtubeIframe && youtubeIframe.src.includes('youtube.com')) {
sendMessageToYouTubeSandbox({
type: 'playPauseSeek',
startTime: startTime
});
return;
}
const vimeoIframe = videoContainer.querySelector('iframe');
if (vimeoIframe && vimeoIframe.src.includes('vimeo.com')) {
sendMessageToVimeoSandbox({
type: 'playPauseSeek',
startTime: startTime
});
return;
}
}
}