I want to create a Chrome Extension and I need to get the details of the music that is being played on YouTube Music. Is there any way to do that (maybe using JS to get the name of the music or whatever). Any kind of help is appreciated
You can run content scripts on the Youtube Music website & app and parse the HTML to get the info you need. Here's a quick script with lazy code. You should obviously do the detection and error-handling better.
Manifest:
{
"manifest_version": 3,
"name": "Youtube Music Info",
"version": "1.0",
"description": "Gets information from YT Music.",
"content_scripts": [
{
"matches": [ "https://music.youtube.com/*" ],
"js": [ "content.js" ],
"all_frames": false,
"run_at": "document_start"
}
]
}
Content Script:
let ytmusicPlayerBar
let waitForPlayerBarInterval = setInterval(() => {
if (document.querySelector("ytmusic-player-bar")) {
ytmusicPlayerBar = document.querySelector("ytmusic-player-bar")
clearInterval(waitForPlayerBarInterval)
getInfo()
}
}, 1000)
function getInfo() {
let getInfoInterval = setInterval(() => {
if (ytmusicPlayerBar.querySelector(".title").innerText) {
let info = {
song: ytmusicPlayerBar.querySelector(".title").innerText,
artist: ytmusicPlayerBar.querySelectorAll("a")[0].innerText,
albumName: ytmusicPlayerBar.querySelectorAll("a")[1].innerText,
albumCover: ytmusicPlayerBar.querySelector(".image").src,
time: ytmusicPlayerBar.querySelector(".time-info").innerText
}
console.log(info)
} else {
console.log("Nothing is playing.")
}
}, 1000)
}