stamat/youtube-background

[Request] Hard Paused State

Opened this issue · 3 comments

There is a "Hard Playing" state which is described as:

doesn't change on video being paused via IntersectionObserver.

It would be nice if there was also a "Hard Paused" state that did the same thing.

I've noticed that this is more noticeable when you pause a video and switch browser tabs - it causes the video to resume playing when you switch back.

Have the same problem. The creator of this package doesn't give support anymore. That said it's possible to disable the observer since it's registered to the VideoBackgrounds-instance.

Initialize the player as such (just make sure you assign the class to a variable):
const ytPlayer = new VideoBackgrounds('[data-vbg]', {});

You can do this to unregister the observer:
ytPlayer.intersectionObserver.disconnect()

I'm currently working on code that enabled hard-pause state (with the observer as source). So basically I'm replacing the default observer with mine.

This my entire code, as you can see it makes a new observer and checks if autoplay is enabled.
So basically when you use a player that has autostart disabled you won't be observing the players.

let videos, ytObserver; 

const youtube = class youtubeClass {
	selector = '[data-vbg]'

	constructor() {
		let _ = this
		window.addEventListener("load", e => _.onLoad())
	}

	createObserver() {
		if (!ytObserver) {
			ytObserver = new IntersectionObserver(entries => {
				entries.forEach(function (entry) {
					let player = videos.get(entry.target)
					if (entry.isIntersecting) {
						player.isIntersecting = true
						try {
							if (player.currentState != 'playing')
								player.softPlay()
						} catch (e) { }
					} else {
						player.isIntersecting = false
						try {
							player.softPause()
						} catch (e) { }
					}
				})
			})
		}
	}

	observe(nodes) {
		let _ = this
		if ('IntersectionObserver' in window) {

			// Create the actual IntersectionObserver
			_.createObserver();

			// Loop the nodes/players
			[].forEach.call(nodes, function (node, index, arr) {
				if (node.getAttribute('data-vbg-autoplay') == "true") {
					ytObserver.observe(node)
				}
			})
		}
	}

	onLoad() {
		let _ = this,
			nodes = document.querySelectorAll(_.selector)

		if (nodes.length > 0) {
			(async () => {
				// Load the base module
				await import('youtube-background').then(module => {
					setTimeout(() => {
						// Initiate the instance
						videos = new VideoBackgrounds(nodes, {
							'lazyloading': true
						});
						// Disconnect the default observer
						videos.intersectionObserver.disconnect()
						// Enable intersectionObserver for nodes
						_.observe(nodes)
					}, 1000)
				})
			})();
		}
	}
}

export default new youtube();

This my entire code, as you can see it makes a new observer and checks if autoplay is enabled. So basically when you use a player that has autostart disabled you won't be observing the players.

Thx. it's work