|
| 1 | +let videoElement = null; |
| 2 | +let image = null; |
| 3 | + |
| 4 | +const observer = new MutationObserver((mutations, observer) => { |
| 5 | + if (!videoElement) { |
| 6 | + videoElement = document.querySelector("video"); |
| 7 | + } |
| 8 | + |
| 9 | + if (!image) { |
| 10 | + image = document.querySelector(".ytmusic-player-bar.image"); |
| 11 | + } |
| 12 | + |
| 13 | + if (videoElement !== null && image !== null) { |
| 14 | + observer.disconnect(); |
| 15 | + let notificationImage = null; |
| 16 | + |
| 17 | + videoElement.addEventListener("play", () => { |
| 18 | + notify({ |
| 19 | + title: getTitle(), |
| 20 | + artist: getArtist(), |
| 21 | + image: notificationImage, |
| 22 | + }); |
| 23 | + }); |
| 24 | + |
| 25 | + image.addEventListener("load", () => { |
| 26 | + notificationImage = null; |
| 27 | + const imageInBase64 = convertImageToBase64(image); |
| 28 | + if (image && image.complete && image.naturalHeight !== 0) { |
| 29 | + notificationImage = imageInBase64; |
| 30 | + } |
| 31 | + }); |
| 32 | + } |
| 33 | +}); |
| 34 | + |
| 35 | +// Convert an image (DOM element) to base64 string |
| 36 | +const convertImageToBase64 = (image, size = 256) => { |
| 37 | + image.setAttribute("crossorigin", "anonymous"); |
| 38 | + |
| 39 | + const c = document.createElement("canvas"); |
| 40 | + c.height = size; |
| 41 | + c.width = size; |
| 42 | + |
| 43 | + const ctx = c.getContext("2d"); |
| 44 | + ctx.drawImage( |
| 45 | + image, |
| 46 | + 0, |
| 47 | + 0, |
| 48 | + image.naturalWidth, |
| 49 | + image.naturalHeight, |
| 50 | + 0, |
| 51 | + 0, |
| 52 | + c.width, |
| 53 | + c.height |
| 54 | + ); |
| 55 | + |
| 56 | + const imageInBase64 = c.toDataURL(); |
| 57 | + return imageInBase64; |
| 58 | +}; |
| 59 | + |
| 60 | +const getTitle = () => { |
| 61 | + const title = document.querySelector(".title.ytmusic-player-bar").textContent; |
| 62 | + return title; |
| 63 | +}; |
| 64 | + |
| 65 | +const getArtist = () => { |
| 66 | + const bar = document.querySelectorAll(".subtitle.ytmusic-player-bar")[0]; |
| 67 | + let artist; |
| 68 | + |
| 69 | + if (bar.querySelectorAll(".yt-simple-endpoint.yt-formatted-string")[0]) { |
| 70 | + artist = bar.querySelectorAll(".yt-simple-endpoint.yt-formatted-string")[0] |
| 71 | + .textContent; |
| 72 | + } else if (bar.querySelectorAll(".byline.ytmusic-player-bar")[0]) { |
| 73 | + artist = bar.querySelectorAll(".byline.ytmusic-player-bar")[0].textContent; |
| 74 | + } |
| 75 | + |
| 76 | + return artist; |
| 77 | +}; |
| 78 | + |
| 79 | +const observeVideoAndThumbnail = () => { |
| 80 | + observer.observe(document, { |
| 81 | + childList: true, |
| 82 | + subtree: true, |
| 83 | + }); |
| 84 | +}; |
| 85 | + |
| 86 | +module.exports = observeVideoAndThumbnail; |
0 commit comments