MediaWiki:YouTube.js

From VRChat Wiki

Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Internet Explorer / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Press Ctrl-F5.
// This could be replaced with https://www.mediawiki.org/wiki/Extension:YouTube, but it
// was easier to just implement it myself instead of asking & waiting for it to be added.

[...document.querySelectorAll(".youtube")].map((element) => {
	const { videoId, ...attributes } = element.dataset;

	const iframe = document.createElement("iframe");

	iframe.setAttribute("width", 560);
	iframe.setAttribute("height", 315);
	iframe.setAttribute("frameborder", 0);
	// As suggested by YouTube's embed copy.
	iframe.setAttribute(
		"allow",
		[
			"accelerometer",
			"autoplay",
			"clipboard-write",
			"encrypted-media",
			"gyroscope",
			"picture-in-picture",
			"web-share"
		].join("; ")
	);
	iframe.setAttribute("referrerpolicy", "strict-origin-when-cross-origin");
	iframe.setAttribute("allowfullscreen", true);

	// Set the attributes from the data-* attributes, overwriting the default ones.
	Object.entries(attributes).map(([key, value]) =>
		iframe.setAttribute(key, value)
	);

	iframe.src = `https://www.youtube-nocookie.com/embed/${videoId}?rel=0`;

	element.replaceWith(iframe);
});