Skip to content

Instantly share code, notes, and snippets.

@dvingerh
Last active June 16, 2023 18:15
Show Gist options
  • Save dvingerh/dbaa4d0d1b3dee95b6a76f03b1e3f128 to your computer and use it in GitHub Desktop.
Save dvingerh/dbaa4d0d1b3dee95b6a76f03b1e3f128 to your computer and use it in GitHub Desktop.
Discord Userscript: Embed MP4 and WebM videos in Discord. (Discord Direct Video Embed)
// ==UserScript==
// @name Discord Direct Video Embed
// @description Embed MP4 and WebM videos in Discord.
// @namespace Violentmonkey Scripts
// @require http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js
// @match *://discordapp.com/*
// @grant GM_addStyle
// @grant GM_getResourceText
// ==/UserScript==
(function($) {
"use strict";
$(document.body).on('click', '.video' ,function(){
if (this.paused === false) {
this.pause();
} else {
this.play();
}
});
$.fn.embedVideo = function() {
$(".attachment").each(
function() {
var toAttach = $(this);
$(this).find('a').each(function() {
var src = $(this).attr('href');
if (toAttach.next().is('video') === false)
{
if (src.endsWith(".mp4") || src.endsWith(".webm"))
{
//alert($(this).attr('href'));
var videoPlayer = document.createElement('video');
videoPlayer.src = src;
// enable controls: give class so Discord can style it and we can check it later
videoPlayer.setAttribute('controls', 'controls');
videoPlayer.setAttribute('class', 'video');
videoPlayer.setAttribute('loop', true);
// style the player so it doesn't get 2hueg
videoPlayer.setAttribute('style', 'max-width: 500px; max-height: 500px; border-radius: 5px;');
// attach player to message
toAttach.after(videoPlayer);
}
}
});
}
);
return this;
};
// Helper function for finding all elements matching selector affected by a mutation
var mutationFind = function(mutation, selector) {
var target = $(mutation.target),
addedNodes = $(mutation.addedNodes);
var mutated = target.add(addedNodes).filter(selector);
var descendants = addedNodes.find(selector);
var ancestors = target.parents(selector);
return mutated.add(descendants).add(ancestors);
};
// Watch for new messages in chat
new MutationObserver(function(mutations, observer) {
mutations.forEach(function(mutation) {
mutationFind(mutation, ".message").embedVideo();
});
}).observe(document, {
childList: true,
subtree: true
});
})(jQuery.noConflict(true));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment