.controls button {
padding: 10px;
font-size: 0.9em;
}
.modal-content {
padding: 10px 15px;
}
.main-title {
font-size: 1.8em;
}
.player-container video,
.player-container iframe {
height: 360px; /* Further adjusted height for very small screens */
}
.loader {
width: 40px; /* Further adjusted size for very small screens */
height: 40px; /* Further adjusted size for very small screens */
}
}
make the master play button say "play from start". youtube videos loaded and played but did not get paused and set to user set start time. load local audio file did not show the audio player. load local video file came up with an error: file is over 50mb, can we set this to unrestricted size?
Certainly! Let's address each of the issues you've encountered with your Chrome Extension and provide the necessary code modifications to resolve them.
1. Change the Master Play Button Label to "Play from Start"
HTML Update:
Locate the Play button in your HTML and update its text content to "Play from Start".
<button type="button" id="play-button" class="play-button" disabled aria-label="Play from Start">Play from Start</button>
2. Fix YouTube Videos Loading and Playback Control
Currently, YouTube videos are embedded using iframes without utilizing the YouTube IFrame API, which limits control over playback (e.g., pausing and setting the start time). To enable these controls, follow the steps below.
a. Include the YouTube IFrame API in Your HTML
Add the YouTube IFrame API script to your HTML to enable JavaScript control over YouTube videos.
Ensure that the YouTube IFrame API script is loaded before your dashboard.js to ensure that the API is available when your JavaScript runs.
b. Modify the JavaScript to Use the YouTube IFrame API
Update your dashboard.js to integrate the YouTube IFrame API for better control over YouTube video playback.
JavaScript Update (dashboard.js):
Initialize YouTube Players:
Add a global callback function onYouTubeIframeAPIReady which is required by the YouTube IFrame API.
Modify the embedYouTubeIframe Function:
Utilize the YouTube Player object for playback control.
Handle Playback Control:
Update play, pause, and resume functions to control YouTube videos via the API.
Here's the updated JavaScript code incorporating these changes:
javascript
Explanation of Changes:
YouTube IFrame API Integration:
Added window.onYouTubeIframeAPIReady as a global function required by the API.
Modified the embedYouTubeIframe function to create a YouTube YT.Player instance instead of a standard iframe. This allows for control over playback like play, pause, and seek.
Updated handlePlay, handlePause, and handleResume functions to utilize the YouTube Player methods (playVideo, pauseVideo, and seekTo).
Fullscreen Control:
When playing YouTube videos in fullscreen, the getIframe() method retrieves the iframe element associated with the YouTube Player for the requestFullscreen method.
3. Fix Loading Local Audio Files Not Showing the Audio Player
The issue where local audio files do not display the audio player might be due to setting the currentTime before the audio metadata has loaded. To ensure that currentTime is set correctly, update the audio element's loadedmetadata event listener.
JavaScript Update (dashboard.js):
Modify the local audio file loading section in the handleLoadMusic function:
javascript
function handleLoadMusic() {
const url = elements.music.urlInput.value.trim();
const file = elements.music.fileInput.files[0];
const start = parseInt(elements.music.startInput.value) || 0;
// Show loading indicator
showLoading(elements.music.playerContainer);
// Unload existing music if any
if (state.music) {
unloadMedia('music');
}
if (file) {
if (file.size > 10 * 1024 * 1024) { // 10MB limit
showMessage('Audio file size exceeds 10MB limit.', 'error');
hideLoading(elements.music.playerContainer);
return;
}
// Handle local audio file
const fileUrl = URL.createObjectURL(file);
const audioElement = document.createElement('audio');
audioElement.controls = true;
audioElement.src = fileUrl;
audioElement.id = 'loaded-music';
audioElement.setAttribute('aria-label', 'Loaded Audio Player');
audioElement.style.width = '100%';
audioElement.style.height = 'auto';
// Listen for metadata to set start time
audioElement.addEventListener('loadedmetadata', () => {
if (start > 0 && audioElement.duration > start) {
audioElement.currentTime = start;
}
});
elements.music.playerContainer.innerHTML = '';
elements.music.playerContainer.appendChild(audioElement);
state.music = {
type: 'file',
element: audioElement,
start: start
};
showMessage('Local audio file loaded.', 'success');
hideLoading(elements.music.playerContainer);
} else if (url && isValidMediaURL(url)) {
// ... [existing YouTube/Vimeo handling]
} else {
showMessage('Please enter a URL or select a local audio file.', 'error');
hideLoading(elements.music.playerContainer);
}
checkReadyToPlay();
saveSettings();
}
Explanation of Changes:
loadedmetadata Event Listener:
This event fires when the browser has loaded the metadata for the audio, including duration.
By setting currentTime within this event, we ensure that the audio can seek to the desired start time without errors.
4. Remove or Modify the File Size Limits for Local Video and Audio Files
To remove the file size restrictions, adjust the conditions that check for file sizes in both handleLoadMusic and handleLoadVideo functions.
function handleLoadVideo() {
const url = elements.video.urlInput.value.trim();
const file = elements.video.fileInput.files[0];
const start = parseInt(elements.video.startInput.value) || 0;
// Show loading indicator
showLoading(elements.video.playerContainer);
// Unload existing video if any
if (state.video) {
unloadMedia('video');
}
if (file) {
if (file.size > 200 * 1024 * 1024) { // Increased limit to 200MB or remove this condition
showMessage('Video file size exceeds 200MB limit.', 'error');
hideLoading(elements.video.playerContainer);
return;
}
// Handle local video file
const fileUrl = URL.createObjectURL(file);
const videoElement = document.createElement('video');
videoElement.controls = true;
videoElement.src = fileUrl;
videoElement.id = 'loaded-video';
videoElement.setAttribute('aria-label', 'Loaded Video Player');
videoElement.style.width = '100%';
videoElement.style.height = 'auto';
// Listen for metadata to set start time
videoElement.addEventListener('loadedmetadata', () => {
if (start > 0 && videoElement.duration > start) {
videoElement.currentTime = start;
}
});
elements.video.playerContainer.innerHTML = '';
elements.video.playerContainer.appendChild(videoElement);
state.video = {
type: 'file',
element: videoElement,
start: start
};
showMessage('Local video file loaded.', 'success');
hideLoading(elements.video.playerContainer);
} else if (url && isValidMediaURL(url)) {
// ... [existing YouTube/Vimeo handling]
} else {
showMessage('Please enter a URL or select a local video file.', 'error');
hideLoading(elements.video.playerContainer);
}
checkReadyToPlay();
saveSettings();
}
Note: If you wish to allow unrestricted file sizes, you can remove the file size checks entirely. However, be cautious as loading very large files might impact performance.
5. Complete Updated Code Snippets
For your convenience, below are the complete updated sections of your code incorporating all the fixes.
a. Updated dashboard.js
javascript
b. Updated dashboard.html
Ensure that the YouTube IFrame API script is included before your dashboard.js script.
html
Explanation of Changes:
Play Button Label:
Updated the Play button text to "Play from Start" and updated the aria-label accordingly.
YouTube IFrame API:
Included the YouTube IFrame API script before your dashboard.js to ensure it's loaded and accessible.
6. Optional: Adjust Manifest Permissions
If you encounter any permission-related issues after these changes, ensure that your manifest.json includes the necessary permissions. However, based on your current manifest, it should suffice. Here's a quick check:
Ensure that lib/player.js refers to the Vimeo Player API and that all external scripts are properly referenced. If additional permissions are required (e.g., for fullscreen operations), consider adding them cautiously. However, the current permissions should cover the functionalities you've described.
7. Final Testing
After implementing the above changes:
Reload the Extension:
Go to chrome://extensions/.
Enable Developer mode (if not already enabled).
Click Reload on your extension to apply the changes.
Test Each Feature:
Play Button: Ensure the button now reads "Play from Start".
YouTube Videos: Load a YouTube video with a specific start time and verify that it pauses at the designated time.
Local Audio Files: Load a local audio file and confirm that the audio player appears and functions correctly.
Local Video Files: Load a local video file without exceeding the new size limit and verify playback.
Monitor for Errors:
Open the extension's dashboard.
Right-click and select Inspect to open the Developer Tools.
Check the Console for any error messages and address them as needed.
Conclusion
By implementing the above modifications, your Chrome Extension should now:
Display the master play button as "Play from Start".
Properly control YouTube video playback, including pausing and setting to user-defined start times using the YouTube IFrame API.
Display the audio player when loading local audio files correctly.
Allow loading of local video files without the previous size restrictions (based on your adjustments).
Feel free to further customize and enhance the extension based on your requirements. If you encounter additional issues or have further questions, don't hesitate to ask!
Not yet included in a published release.
"use strict";
document.addEventListener('DOMContentLoaded', () => {
// === Element References ===
const elements = {
// ... [existing element references]
};
// === State Management ===
const state = {
music: null, // { type: 'file' | 'youtube' | 'vimeo', element: HTMLAudioElement | YT.Player | Vimeo.Player, start: Number }
video: null, // { type: 'file' | 'youtube' | 'vimeo', element: HTMLVideoElement | YT.Player | Vimeo.Player, start: Number }
isPaused: false,
fullscreenOnPlay: false
};
// === Utility Functions ===
// ... [existing utility functions]
// === Initialization ===
loadSettings();
// === Event Listeners ===
// ... [existing event listeners]
// === Handler Functions ===
// ... [existing handler functions]
// === YouTube IFrame API Integration ===
let ytPlayers = {}; // To keep track of YouTube players
window.onYouTubeIframeAPIReady = function() {
// This function is called by the YouTube IFrame API once it's ready
console.log('YouTube IFrame API is ready.');
// If there are already embedded YouTube videos, you can initialize them here
};
/**
* Embeds a YouTube video using the IFrame API.
* @param {string} videoId - The YouTube video ID.
* @param {number} start - The start time in seconds.
* @param {string} mediaType - 'music' or 'video'.
*/
function embedYouTubeIframe(videoId, start, mediaType) {
const container = elements[mediaType].playerContainer;
container.innerHTML = ''; // Clear previous content
const div = document.createElement('div');
const playerId = `youtube-player-${mediaType}-${videoId}`;
div.id = playerId;
div.style.width = '100%';
div.style.height = '720px'; // Increased height
container.appendChild(div);
const player = new YT.Player(playerId, {
height: '720',
width: '100%',
videoId: videoId,
playerVars: {
autoplay: 0,
controls: 1,
start: start,
rel: 0,
enablejsapi: 1
},
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
ytPlayers[playerId] = player;
state[mediaType] = {
type: 'youtube',
element: player,
start: start
};
}
/**
* YouTube Player onReady event handler.
* @param {Object} event - The event object.
*/
function onPlayerReady(event) {
console.log('YouTube Player is ready.');
// Optionally, you can autoplay or perform other actions here
}
/**
* YouTube Player onStateChange event handler.
* @param {Object} event - The event object.
*/
function onPlayerStateChange(event) {
// Handle state changes if needed
// e.g., buffering, ended, etc.
}
// === Playback Controls Updates ===
/**
* Handles the Play action, including "Play from Start".
*/
function handlePlay() {
// Play Music
if (state.music) {
if (state.music.type === 'file') {
state.music.element.play();
if (state.fullscreenOnPlay) {
enterFullscreen(state.music.element);
}
} else if (state.music.type === 'vimeo') {
state.music.element.play().catch(error => {
console.error('Error playing Vimeo audio:', error);
showMessage('Failed to play Vimeo audio.', 'error');
});
} else if (state.music.type === 'youtube') {
state.music.element.seekTo(state.music.start, true);
state.music.element.playVideo();
if (state.fullscreenOnPlay) {
enterFullscreen(state.music.element.getIframe());
}
}
}
// Play Video
if (state.video) {
if (state.video.type === 'file') {
state.video.element.play();
if (state.fullscreenOnPlay) {
enterFullscreen(state.video.element);
}
} else if (state.video.type === 'vimeo') {
state.video.element.play().catch(error => {
console.error('Error playing Vimeo video:', error);
showMessage('Failed to play Vimeo video.', 'error');
});
} else if (state.video.type === 'youtube') {
state.video.element.seekTo(state.video.start, true);
state.video.element.playVideo();
if (state.fullscreenOnPlay) {
enterFullscreen(state.video.element.getIframe());
}
}
}
state.isPaused = false;
elements.controls.pauseButton.disabled = false;
elements.controls.resumeButton.disabled = true;
elements.controls.pauseButton.textContent = 'Pause';
showMessage('Playback started!', 'success');
}
/**
* Handles the Pause action.
*/
function handlePause() {
if (state.isPaused) return;
// Pause Music
if (state.music) {
if (state.music.type === 'file') {
state.music.element.pause();
} else if (state.music.type === 'vimeo') {
state.music.element.pause().catch(error => {
console.error('Error pausing Vimeo audio:', error);
showMessage('Failed to pause Vimeo audio.', 'error');
});
} else if (state.music.type === 'youtube') {
state.music.element.pauseVideo();
}
}
// Pause Video
if (state.video) {
if (state.video.type === 'file') {
state.video.element.pause();
} else if (state.video.type === 'vimeo') {
state.video.element.pause().catch(error => {
console.error('Error pausing Vimeo video:', error);
showMessage('Failed to pause Vimeo video.', 'error');
});
} else if (state.video.type === 'youtube') {
state.video.element.pauseVideo();
}
}
state.isPaused = true;
elements.controls.resumeButton.disabled = false;
elements.controls.pauseButton.disabled = true;
elements.controls.pauseButton.textContent = 'Pause';
showMessage('Playback paused.', 'info');
}
/**
* Handles the Resume action.
*/
function handleResume() {
if (!state.isPaused) return;
// Resume Music
if (state.music) {
if (state.music.type === 'file') {
state.music.element.play();
if (state.fullscreenOnPlay) {
enterFullscreen(state.music.element);
}
} else if (state.music.type === 'vimeo') {
state.music.element.play().catch(error => {
console.error('Error resuming Vimeo audio:', error);
showMessage('Failed to resume Vimeo audio.', 'error');
});
} else if (state.music.type === 'youtube') {
state.music.element.playVideo();
if (state.fullscreenOnPlay) {
enterFullscreen(state.music.element.getIframe());
}
}
}
// Resume Video
if (state.video) {
if (state.video.type === 'file') {
state.video.element.play();
if (state.fullscreenOnPlay) {
enterFullscreen(state.video.element);
}
} else if (state.video.type === 'vimeo') {
state.video.element.play().catch(error => {
console.error('Error resuming Vimeo video:', error);
showMessage('Failed to resume Vimeo video.', 'error');
});
} else if (state.video.type === 'youtube') {
state.video.element.playVideo();
if (state.fullscreenOnPlay) {
enterFullscreen(state.video.element.getIframe());
}
}
}
state.isPaused = false;
elements.controls.resumeButton.disabled = true;
elements.controls.pauseButton.disabled = false;
elements.controls.pauseButton.textContent = 'Pause';
showMessage('Playback resumed.', 'success');
}
// === Other Existing Functions ===
// ... [other existing functions remain unchanged]
// Initialize ready state
checkReadyToPlay();
// Ensure buttons are correctly enabled/disabled on load
if (state.music || state.video) {
elements.controls.playButton.disabled = false;
}
});
"use strict";
document.addEventListener('DOMContentLoaded', () => {
// === Element References ===
const elements = {
music: {
urlInput: document.getElementById('music-url'),
fileInput: document.getElementById('music-file'),
startInput: document.getElementById('music-start'),
loadButton: document.getElementById('load-music'),
playerContainer: document.getElementById('music-player-container')
},
video: {
urlInput: document.getElementById('video-url'),
fileInput: document.getElementById('video-file'),
startInput: document.getElementById('video-start'),
loadButton: document.getElementById('load-video'),
playerContainer: document.getElementById('video-player-container')
},
controls: {
playButton: document.getElementById('play-button'),
pauseButton: document.getElementById('pause-button'),
resumeButton: document.getElementById('resume-button')
},
messageContainer: document.getElementById('message-container'),
settings: {
button: document.getElementById('settings-button'),
modal: document.getElementById('settings-modal'),
closeButton: document.querySelector('.close-button'),
fullscreenToggle: document.getElementById('fullscreen-toggle')
}
};
// === State Management ===
const state = {
music: null, // { type: 'file' | 'youtube' | 'vimeo', element: HTMLAudioElement | YT.Player | Vimeo.Player, start: Number }
video: null, // { type: 'file' | 'youtube' | 'vimeo', element: HTMLVideoElement | YT.Player | Vimeo.Player, start: Number }
isPaused: false,
fullscreenOnPlay: false
};
// === Utility Functions ===
/**
* Displays a message to the user.
* @param {string} message - The message to display.
* @param {string} type - The type of message ('success', 'error', 'info').
*/
function showMessage(message, type) {
elements.messageContainer.innerHTML = '';
const msgDiv = document.createElement('div');
msgDiv.textContent = message;
msgDiv.classList.add('message', type); // 'success', 'error', 'info'
elements.messageContainer.appendChild(msgDiv);
// Automatically hide message after 5 seconds
setTimeout(() => {
if (elements.messageContainer.contains(msgDiv)) {
elements.messageContainer.removeChild(msgDiv);
}
}, 5000);
}
/**
* Shows a loading spinner in the specified container.
* @param {HTMLElement} container - The container to show the loader in.
*/
function showLoading(container) {
container.innerHTML = '';
const loader = document.createElement('div');
loader.classList.add('loader'); // Define loader styles in CSS
container.appendChild(loader);
}
/**
* Hides the loading spinner from the specified container.
* @param {HTMLElement} container - The container to hide the loader from.
*/
function hideLoading(container) {
const loader = container.querySelector('.loader');
if (loader) {
container.removeChild(loader);
}
}
/**
* Traps keyboard focus within a specified element.
* @param {HTMLElement} element - The element to trap focus within.
*/
function trapFocus(element) {
const focusableElementsString = 'a[href], area[href], input:not([disabled]), select:not([disabled]),' +
' textarea:not([disabled]), button:not([disabled]), iframe, object, embed, [tabindex="0"],' +
' [contenteditable]';
const focusableElements = element.querySelectorAll(focusableElementsString);
const firstTabStop = focusableElements[0];
const lastTabStop = focusableElements[focusableElements.length - 1];
// Listen for and trap the keyboard
element.addEventListener('keydown', trapTabKey);
function trapTabKey(e) {
// Check for TAB key press
if (e.key === 'Tab') {
// SHIFT + TAB
if (e.shiftKey) {
if (document.activeElement === firstTabStop) {
e.preventDefault();
lastTabStop.focus();
}
} else { // TAB
if (document.activeElement === lastTabStop) {
e.preventDefault();
firstTabStop.focus();
}
}
}
}
// Remove trap when modal is closed
function removeTrapKey(e) {
element.removeEventListener('keydown', trapTabKey);
}
// Store the function reference to remove it later
element.removeTrapKey = removeTrapKey;
}
function removeTrapFocus() {
if (elements.settings.modal.removeTrapKey) {
elements.settings.modal.removeTrapKey();
}
}
// === Initialization ===
loadSettings();
// === Event Listeners ===
elements.music.loadButton.addEventListener('click', handleLoadMusic);
elements.video.loadButton.addEventListener('click', handleLoadVideo);
elements.controls.playButton.addEventListener('click', handlePlay);
elements.controls.pauseButton.addEventListener('click', handlePause);
elements.controls.resumeButton.addEventListener('click', handleResume);
// Settings Modal Event Listeners
elements.settings.button.addEventListener('click', openSettingsModal);
elements.settings.closeButton.addEventListener('click', closeSettingsModal);
window.addEventListener('click', (event) => {
if (event.target === elements.settings.modal) {
closeSettingsModal();
}
});
document.addEventListener('keydown', (event) => {
if (event.key === 'Escape' && !elements.settings.modal.hasAttribute('hidden')) {
closeSettingsModal();
}
});
elements.settings.fullscreenToggle.addEventListener('change', (event) => {
state.fullscreenOnPlay = event.target.checked;
saveSettings();
});
// === Handler Functions ===
// Load Music Handler
function handleLoadMusic() {
const url = elements.music.urlInput.value.trim();
const file = elements.music.fileInput.files[0];
const start = parseInt(elements.music.startInput.value) || 0;
// Show loading indicator
showLoading(elements.music.playerContainer);
// Unload existing music if any
if (state.music) {
unloadMedia('music');
}
if (file) {
// Remove or modify the size limit as per your needs
// Example: Remove size limit
/*
if (file.size > SOME_LIMIT) {
showMessage('Audio file size exceeds the limit.', 'error');
hideLoading(elements.music.playerContainer);
return;
}
*/
// Handle local audio file
const fileUrl = URL.createObjectURL(file);
const audioElement = document.createElement('audio');
audioElement.controls = true;
audioElement.src = fileUrl;
audioElement.id = 'loaded-music';
audioElement.setAttribute('aria-label', 'Loaded Audio Player');
audioElement.style.width = '100%';
audioElement.style.height = 'auto';
// Listen for metadata to set start time
audioElement.addEventListener('loadedmetadata', () => {
if (start > 0 && audioElement.duration > start) {
audioElement.currentTime = start;
}
});
elements.music.playerContainer.innerHTML = '';
elements.music.playerContainer.appendChild(audioElement);
state.music = {
type: 'file',
element: audioElement,
start: start
};
showMessage('Local audio file loaded.', 'success');
hideLoading(elements.music.playerContainer);
} else if (url && isValidMediaURL(url)) {
const mediaInfo = extractMediaInfo(url);
if (mediaInfo) {
if (mediaInfo.platform === 'youtube') {
embedYouTubeIframe(mediaInfo.id, start, 'music');
} else if (mediaInfo.platform === 'vimeo') {
embedVimeoPlayer(mediaInfo.id, start, 'music');
}
showMessage(`Loaded ${capitalize(mediaInfo.platform)} audio.`, 'success');
hideLoading(elements.music.playerContainer);
// Implement buffering: play briefly, then pause and set start time
bufferAndPause(mediaInfo.platform, 'music', start);
} else {
showMessage('Invalid URL. Please enter a valid YouTube or Vimeo URL.', 'error');
hideLoading(elements.music.playerContainer);
}
} else {
showMessage('Please enter a URL or select a local audio file.', 'error');
hideLoading(elements.music.playerContainer);
}
checkReadyToPlay();
saveSettings();
}
// Load Video Handler
function handleLoadVideo() {
const url = elements.video.urlInput.value.trim();
const file = elements.video.fileInput.files[0];
const start = parseInt(elements.video.startInput.value) || 0;
// Show loading indicator
showLoading(elements.video.playerContainer);
// Unload existing video if any
if (state.video) {
unloadMedia('video');
}
if (file) {
// Remove or modify the size limit as per your needs
// Example: Remove the file size check
/*
if (file.size > SOME_LIMIT) {
showMessage('Video file size exceeds the limit.', 'error');
hideLoading(elements.video.playerContainer);
return;
}
*/
// Handle local video file
const fileUrl = URL.createObjectURL(file);
const videoElement = document.createElement('video');
videoElement.controls = true;
videoElement.src = fileUrl;
videoElement.id = 'loaded-video';
videoElement.setAttribute('aria-label', 'Loaded Video Player');
videoElement.style.width = '100%';
videoElement.style.height = 'auto';
// Listen for metadata to set start time
videoElement.addEventListener('loadedmetadata', () => {
if (start > 0 && videoElement.duration > start) {
videoElement.currentTime = start;
}
});
elements.video.playerContainer.innerHTML = '';
elements.video.playerContainer.appendChild(videoElement);
state.video = {
type: 'file',
element: videoElement,
start: start
};
showMessage('Local video file loaded.', 'success');
hideLoading(elements.video.playerContainer);
} else if (url && isValidMediaURL(url)) {
const mediaInfo = extractMediaInfo(url);
if (mediaInfo) {
if (mediaInfo.platform === 'youtube') {
embedYouTubeIframe(mediaInfo.id, start, 'video');
} else if (mediaInfo.platform === 'vimeo') {
embedVimeoPlayer(mediaInfo.id, start, 'video');
}
showMessage(`Loaded ${capitalize(mediaInfo.platform)} video.`, 'success');
hideLoading(elements.video.playerContainer);
// Implement buffering: play briefly, then pause and set start time
bufferAndPause(mediaInfo.platform, 'video', start);
} else {
showMessage('Invalid URL. Please enter a valid YouTube or Vimeo URL.', 'error');
hideLoading(elements.video.playerContainer);
}
} else {
showMessage('Please enter a URL or select a local video file.', 'error');
hideLoading(elements.video.playerContainer);
}
checkReadyToPlay();
saveSettings();
}
// Play Handler
function handlePlay() {
// Play Music
if (state.music) {
if (state.music.type === 'file') {
state.music.element.play();
if (state.fullscreenOnPlay) {
enterFullscreen(state.music.element);
}
} else if (state.music.type === 'vimeo') {
state.music.element.play().catch(error => {
console.error('Error playing Vimeo audio:', error);
showMessage('Failed to play Vimeo audio.', 'error');
});
} else if (state.music.type === 'youtube') {
state.music.element.seekTo(state.music.start, true);
state.music.element.playVideo();
if (state.fullscreenOnPlay) {
enterFullscreen(state.music.element.getIframe());
}
}
}
// Play Video
if (state.video) {
if (state.video.type === 'file') {
state.video.element.play();
if (state.fullscreenOnPlay) {
enterFullscreen(state.video.element);
}
} else if (state.video.type === 'vimeo') {
state.video.element.play().catch(error => {
console.error('Error playing Vimeo video:', error);
showMessage('Failed to play Vimeo video.', 'error');
});
} else if (state.video.type === 'youtube') {
state.video.element.seekTo(state.video.start, true);
state.video.element.playVideo();
if (state.fullscreenOnPlay) {
enterFullscreen(state.video.element.getIframe());
}
}
}
state.isPaused = false;
elements.controls.pauseButton.disabled = false;
elements.controls.resumeButton.disabled = true;
elements.controls.pauseButton.textContent = 'Pause';
showMessage('Playback started!', 'success');
}
// Pause Handler
function handlePause() {
if (state.isPaused) return;
// Pause Music
if (state.music) {
if (state.music.type === 'file') {
state.music.element.pause();
} else if (state.music.type === 'vimeo') {
state.music.element.pause().catch(error => {
console.error('Error pausing Vimeo audio:', error);
showMessage('Failed to pause Vimeo audio.', 'error');
});
} else if (state.music.type === 'youtube') {
state.music.element.pauseVideo();
}
}
// Pause Video
if (state.video) {
if (state.video.type === 'file') {
state.video.element.pause();
} else if (state.video.type === 'vimeo') {
state.video.element.pause().catch(error => {
console.error('Error pausing Vimeo video:', error);
showMessage('Failed to pause Vimeo video.', 'error');
});
} else if (state.video.type === 'youtube') {
state.video.element.pauseVideo();
}
}
state.isPaused = true;
elements.controls.resumeButton.disabled = false;
elements.controls.pauseButton.disabled = true;
elements.controls.pauseButton.textContent = 'Pause';
showMessage('Playback paused.', 'info');
}
// Resume Handler
function handleResume() {
if (!state.isPaused) return;
// Resume Music
if (state.music) {
if (state.music.type === 'file') {
state.music.element.play();
if (state.fullscreenOnPlay) {
enterFullscreen(state.music.element);
}
} else if (state.music.type === 'vimeo') {
state.music.element.play().catch(error => {
console.error('Error resuming Vimeo audio:', error);
showMessage('Failed to resume Vimeo audio.', 'error');
});
} else if (state.music.type === 'youtube') {
state.music.element.playVideo();
if (state.fullscreenOnPlay) {
enterFullscreen(state.music.element.getIframe());
}
}
}
// Resume Video
if (state.video) {
if (state.video.type === 'file') {
state.video.element.play();
if (state.fullscreenOnPlay) {
enterFullscreen(state.video.element);
}
} else if (state.video.type === 'vimeo') {
state.video.element.play().catch(error => {
console.error('Error resuming Vimeo video:', error);
showMessage('Failed to resume Vimeo video.', 'error');
});
} else if (state.video.type === 'youtube') {
state.video.element.playVideo();
if (state.fullscreenOnPlay) {
enterFullscreen(state.video.element.getIframe());
}
}
}
state.isPaused = false;
elements.controls.resumeButton.disabled = true;
elements.controls.pauseButton.disabled = false;
elements.controls.pauseButton.textContent = 'Pause';
showMessage('Playback resumed.', 'success');
}
// === Settings Modal Functions ===
function openSettingsModal() {
elements.settings.modal.removeAttribute('hidden');
elements.settings.modal.setAttribute('aria-hidden', 'false');
elements.settings.modal.querySelector('.close-button').focus();
trapFocus(elements.settings.modal);
}
function closeSettingsModal() {
elements.settings.modal.setAttribute('hidden', '');
elements.settings.modal.setAttribute('aria-hidden', 'true');
elements.settings.button.focus();
removeTrapFocus();
}
// === Media Embedding Functions ===
/**
* Embeds a YouTube video using the IFrame API.
* @param {string} videoId - The YouTube video ID.
* @param {number} start - The start time in seconds.
* @param {string} mediaType - 'music' or 'video'.
*/
function embedYouTubeIframe(videoId, start, mediaType) {
const container = elements[mediaType].playerContainer;
container.innerHTML = ''; // Clear previous content
const div = document.createElement('div');
const playerId = `youtube-player-${mediaType}-${videoId}`;
div.id = playerId;
div.style.width = '100%';
div.style.height = '720px'; // Increased height
container.appendChild(div);
const player = new YT.Player(playerId, {
height: '720',
width: '100%',
videoId: videoId,
playerVars: {
autoplay: 0,
controls: 1,
start: start,
rel: 0,
enablejsapi: 1
},
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
ytPlayers[playerId] = player;
state[mediaType] = {
type: 'youtube',
element: player,
start: start
};
}
/**
* Embeds a Vimeo video using the Player API.
* @param {string} videoId - The Vimeo video ID.
* @param {number} start - The start time in seconds.
* @param {string} mediaType - 'music' or 'video'.
*/
function embedVimeoPlayer(videoId, start, mediaType) {
const container = elements[mediaType].playerContainer;
container.innerHTML = ''; // Clear previous content
const iframe = document.createElement('iframe');
const src = `https://player.vimeo.com/video/${videoId}?muted=1&autopause=0&background=0`;
iframe.src = src;
iframe.width = '100%';
iframe.height = '720'; // Increased height
iframe.frameBorder = '0';
iframe.allow = 'autoplay; fullscreen; picture-in-picture';
iframe.setAttribute('title', 'Vimeo video player');
container.appendChild(iframe);
const player = new Vimeo.Player(iframe, {
id: videoId,
width: container.clientWidth,
muted: true,
autoplay: false,
start: start
});
state[mediaType] = {
type: 'vimeo',
element: player,
start: start
};
}
/**
* Handles the YouTube Player ready event.
* @param {Object} event - The event object.
*/
function onPlayerReady(event) {
console.log('YouTube Player is ready.');
// You can perform additional actions here if needed
}
/**
* Handles the YouTube Player state change event.
* @param {Object} event - The event object.
*/
function onPlayerStateChange(event) {
// Handle state changes if needed
}
/**
* Implements the buffering process: plays briefly, pauses, sets to start time.
* @param {string} platform - 'youtube' or 'vimeo'.
* @param {string} mediaType - 'music' or 'video'.
* @param {number} startTime - The start time in seconds.
*/
function bufferAndPause(platform, mediaType, startTime) {
if (platform === 'vimeo') {
// Vimeo Player API allows playback control
const player = state[mediaType].element;
player.play().then(() => {
// Wait for at least 125ms
setTimeout(() => {
player.pause().then(() => {
player.setCurrentTime(startTime).then(() => {
showMessage(`Vimeo ${mediaType} buffered and set to ${startTime} seconds.`, 'success');
}).catch(error => {
console.error(`Error setting start time for Vimeo ${mediaType}:`, error);
showMessage(`Failed to set start time for Vimeo ${mediaType}.`, 'error');
});
}).catch(error => {
console.error(`Error pausing Vimeo ${mediaType}:`, error);
showMessage(`Failed to pause Vimeo ${mediaType}.`, 'error');
});
}, 125);
}).catch(error => {
console.error(`Error playing Vimeo ${mediaType}:`, error);
showMessage(`Failed to play Vimeo ${mediaType}.`, 'error');
});
} else if (platform === 'youtube') {
// Buffering using YouTube IFrame API
const player = state[mediaType].element;
player.playVideo();
// Wait briefly to let the video buffer
setTimeout(() => {
player.pauseVideo();
player.seekTo(startTime, true);
showMessage(`YouTube ${mediaType} set to ${startTime} seconds.`, 'success');
}, 500); // 500ms delay
}
}
// === Settings Modal Functions ===
function openSettingsModal() {
elements.settings.modal.removeAttribute('hidden');
elements.settings.modal.setAttribute('aria-hidden', 'false');
elements.settings.modal.querySelector('.close-button').focus();
trapFocus(elements.settings.modal);
}
function closeSettingsModal() {
elements.settings.modal.setAttribute('hidden', '');
elements.settings.modal.setAttribute('aria-hidden', 'true');
elements.settings.button.focus();
removeTrapFocus();
}
// === Settings Persistence ===
/**
* Loads settings from Chrome storage.
*/
function loadSettings() {
try {
chrome.storage.local.get(['mediaSettings'], (result) => {
if (chrome.runtime.lastError) {
throw new Error(chrome.runtime.lastError);
}
if (result.mediaSettings) {
const { music, video, fullscreenOnPlay: fsPlay } = result.mediaSettings;
if (music) {
if (music.type === 'youtube' || music.type === 'vimeo') {
const url = music.type === 'youtube'
? `https://www.youtube.com/watch?v=${music.id}`
: `https://vimeo.com/${music.id}`;
elements.music.urlInput.value = url;
elements.music.startInput.value = music.start || 0;
// Optionally, auto-load the media by triggering the load button
// handleLoadMusic();
}
// Handle file-based music loading if necessary
}
if (video) {
if (video.type === 'youtube' || video.type === 'vimeo') {
const url = video.type === 'youtube'
? `https://www.youtube.com/watch?v=${video.id}`
: `https://vimeo.com/${video.id}`;
elements.video.urlInput.value = url;
elements.video.startInput.value = video.start || 0;
// Optionally, auto-load the media by triggering the load button
// handleLoadVideo();
}
// Handle file-based video loading if necessary
}
if (typeof fsPlay === 'boolean') {
state.fullscreenOnPlay = fsPlay;
elements.settings.fullscreenToggle.checked = fsPlay;
}
}
});
} catch (error) {
console.error('Error loading settings:', error);
showMessage('Failed to load settings.', 'error');
}
}
/**
* Saves settings to Chrome storage.
*/
function saveSettings() {
const settings = {
music: state.music,
video: state.video,
fullscreenOnPlay: state.fullscreenOnPlay
};
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');
}
}
/**
* Unloads media from the specified type.
* @param {string} mediaType - 'music' or 'video'.
*/
function unloadMedia(mediaType) {
if (state[mediaType]) {
if (state[mediaType].type === 'file') {
if (state[mediaType].element.src) {
URL.revokeObjectURL(state[mediaType].element.src);
state[mediaType].element.src = '';
state[mediaType].element.remove();
}
} else if (state[mediaType].type === 'youtube') {
const iframe = state[mediaType].element.getIframe();
iframe.src = ''; // Reset iframe src to stop the media
const playerId = iframe.id;
if (ytPlayers[playerId]) {
ytPlayers[playerId].destroy();
delete ytPlayers[playerId];
}
} else if (state[mediaType].type === 'vimeo') {
const player = state[mediaType].element;
player.unload().catch(error => {
console.error(`Error unloading Vimeo ${mediaType}:`, error);
});
}
state[mediaType] = null;
}
}
// === Playback Controls ===
/**
* Enables or disables playback controls based on media loading state.
*/
function checkReadyToPlay() {
// Enable buttons only when at least one of audio or video is loaded
const readyAudio = state.music
&& (state.music.type === 'file'
|| state.music.type === 'youtube'
|| state.music.type === 'vimeo');
const readyVideo = state.video
&& (state.video.type === 'file'
|| state.video.type === 'youtube'
|| state.video.type === 'vimeo');
const ready = readyAudio || readyVideo;
elements.controls.playButton.disabled = !ready;
elements.controls.pauseButton.disabled = !ready;
elements.controls.resumeButton.disabled = true; // Start with Resume disabled
}
// === Media Embedding Functions ===
/**
* Validates whether the URL is a valid YouTube or Vimeo URL.
* @param {string} url - The URL to validate.
* @returns {boolean} True if valid, else false.
*/
function isValidMediaURL(url) {
try {
const parsedUrl = new URL(url);
const hostname = parsedUrl.hostname.toLowerCase();
const pathname = parsedUrl.pathname;
// YouTube RegEx Patterns
const youtubeRegex = /^\/(?:watch\/|embed\/|v\/)?([a-zA-Z0-9_-]{11})$/;
// Vimeo RegEx Patterns
const vimeoRegex = /^\/(?:video\/)?(\d+)$/;
if (hostname.includes('youtube.com') || hostname === 'youtu.be') {
// Extract YouTube video ID
let videoId = '';
if (hostname === 'youtu.be') {
videoId = pathname.slice(1);
} else {
videoId = parsedUrl.searchParams.get('v') || '';
}
return youtubeRegex.test(`/${videoId}`);
} else if (hostname.includes('vimeo.com')) {
// Extract Vimeo video ID
const match = pathname.match(vimeoRegex);
return match && match[1].length > 0;
}
return false;
} catch (e) {
return false;
}
}
/**
* Extracts media information from the URL.
* @param {string} url - The media URL.
* @returns {Object|null} An object with platform and id, or null if invalid.
*/
function extractMediaInfo(url) {
try {
const parsedUrl = new URL(url);
const hostname = parsedUrl.hostname.toLowerCase();
const pathname = parsedUrl.pathname;
// YouTube Patterns
if (hostname.includes('youtube.com') || hostname === 'youtu.be') {
let videoId = '';
if (hostname === 'youtu.be') {
videoId = pathname.slice(1);
} else {
videoId = parsedUrl.searchParams.get('v') || '';
}
// Validate videoId length
if (videoId.length === 11) {
return { platform: 'youtube', id: videoId };
}
}
// Vimeo Patterns
if (hostname.includes('vimeo.com')) {
const vimeoMatch = pathname.match(/^\/(?:video\/)?(\d+)$/);
if (vimeoMatch && vimeoMatch[1]) {
return { platform: 'vimeo', id: vimeoMatch[1] };
}
}
return null;
} catch (e) {
return null;
}
}
/**
* Capitalize the first letter of a string.
* @param {string} text - The string to capitalize.
* @returns {string} Capitalized string.
*/
function capitalize(text) {
if (!text) return '';
return text.charAt(0).toUpperCase() + text.slice(1);
}
/**
* Enters fullscreen mode for the specified element.
* @param {HTMLElement} element - The element to enter fullscreen.
*/
function enterFullscreen(element) {
if (element && element.requestFullscreen) {
element.requestFullscreen().then(() => {
showMessage('Entered fullscreen mode.', 'success');
}).catch(err => {
console.error(`Error attempting to enable full-screen mode: ${err.message} (${err.name})`);
showMessage('Failed to enter fullscreen mode.', 'error');
});
} else {
showMessage('Fullscreen not supported on this element.', 'error');
}
}
// === Initialize ready state ===
checkReadyToPlay();
// Ensure buttons are correctly enabled/disabled on load
if (state.music || state.video) {
elements.controls.playButton.disabled = false;
}
});
// === YouTube IFrame API Integration ===
// Global variable to store YouTube players
let ytPlayers = {};
// The YouTube IFrame API calls this function when it's ready
window.onYouTubeIframeAPIReady = function() {
console.log('YouTube IFrame API is ready.');
};