Detailed Explanation of the Code’s Functionality on YouTube
This JavaScript code is a bookmarklet designed to work on YouTube video pages. When you visit a YouTube video and activate this code, it performs a series of actions to gather specific details about the video and its associated content. After gathering this information, it formats it into a BBCode format, which is often used for forum posts or other platforms that support BBCode tags. The code then automatically copies the formatted BBCode to your clipboard, so you can easily paste it elsewhere (e.g., in a forum post).
Here’s a step-by-step breakdown of what the code does:
1. Selectors for Extracting YouTube Metadata:
The code starts by defining a set of
selectors. These are CSS-style rules that target specific elements on a YouTube video page to extract data such as:
- Title: The title of the video.
- Channel Name: The name of the channel that uploaded the video.
- Channel URL: A link to the channel.
- Subscribers: The number of subscribers the channel has.
- Likes: The number of likes the video has.
- Description: The description text of the video.
The selectors are an array of possible CSS selectors because YouTube’s page layout might change over time, so there are different possible locations for the information.
2. Functions to Extract Data:
The code defines various functions to gather the required data:
- getElement(selectors): This function takes a selector (or an array of selectors) and tries to find the matching element on the page. If it finds the element, it returns it.
- getText(selectors): This function retrieves the text content of the element(s) found by getElement().
- getNumber(text): This function extracts and cleans up numbers from a string (used to extract things like the number of subscribers or likes).
- getVideoId(): This function grabs the video ID from the URL (which is needed to construct the video’s URL in BBCode format).
- getDescription(): This function retrieves the video description from the page. If the description is not available, it attempts to find it from a backup source (YouTube's internal data).
3. Watching for Dynamic Content:
YouTube pages are often dynamically loaded (content is updated as you interact with the page), so the script uses a
MutationObserver. This keeps an eye on changes in the page and automatically runs the script to extract metadata whenever the page’s elements (like the video title) are loaded or updated.
4. Format Data into BBCode:
Once the data is gathered, it is formatted into
BBCode, a simple markup language used for formatting text. The BBCode string includes:
- The video title inside
[b]
(bold) tags.
- A URL to the video inside
[url]
tags.
- The channel name and a link to the channel inside
[u]
(underlined) and [url]
tags.
- Subscriber count and like count are also included.
- The description is included inside a
[spoiler]
tag, so it’s hidden by default (spoiler tags allow you to hide content until the user decides to reveal it).
5. Copying to Clipboard:
After creating the BBCode string, the code automatically copies it to your clipboard using a temporary <textarea> element (instead of an <input>, which would flatten newlines into spaces). This allows you to paste the BBCode anywhere, preserving the structure and line breaks.
6. Displaying a Toast Notification:
After the BBCode is copied, a small
toast notification appears on the screen, telling you that the data has been copied successfully. This message typically disappears after a few seconds.
7. Conditions:
The code checks if you are on a YouTube video page (window.location.hostname === '
www.youtube.com'). If you’re not on a YouTube page, it will show an alert prompting you to use the bookmarklet on a valid YouTube video.
8. Fallback for Missing Description:
If the video description is missing or the primary method of extracting it fails, the code tries to fetch the description from YouTube’s internal JSON response (ytInitialPlayerResponse). This ensures that even if the normal description is unavailable, the code still has a chance to get it.
What Does the Code Do?
- Collects Metadata from YouTube Video:
- The script looks for the title, channel name, channel URL, number of subscribers, likes, and description of the video.
- Formats Information in BBCode:
- It then puts all of this information into a pre-defined BBCode format. This includes bold and underlined tags, URLs, and a spoiler tag for the description.
- Copies to Clipboard:
- After formatting the data, the script automatically copies it to your clipboard so that you can paste it into a forum, chat, or anywhere else that supports BBCode.
- Notifications & Feedback:
- A small notification (toast) tells you when the data has been successfully copied.
Example Output (BBCode):
Assuming you run the bookmarklet on a YouTube video page, the BBCode generated would look like this:
Code:
[b]Video Title[/b]
[url=https://www.youtube.com/watch?v=abcd1234]https://www.youtube.com/watch?v=abcd1234[/url]
[b]Channel Info[/b]
[u][url=https://www.youtube.com/channel/xyz]Channel Name[/url][/u]
Subscribers: 1,234
[b]Engagement[/b]
👍 Likes: 5,678
[b]Description[/b]
[spoiler]First paragraph of description.
Second paragraph of description.
Third paragraph of description.[/spoiler]
Summary:
This script is a helpful tool for quickly extracting detailed metadata from a YouTube video page and formatting it in a BBCode format. It simplifies the process of collecting and sharing information about YouTube videos, particularly useful for forums or online platforms that use BBCode for post formatting. By wrapping the description in a
[spoiler]
tag, it ensures that long descriptions are hidden by default and only revealed when the user clicks to view them.
edit:
3/23/2025
UPDATE to V2
Here's a changelog detailing the differences between V1 and V2 of the bookmarklet:
- getElement function:
- Changed from using Array.from().reduce() to a simple for loop for better readability and potentially better performance.
- Added new utility functions:
- sanitizeBBCode: Removes dollar signs from text to prevent BBCode formatting issues.
- truncate: Limits text length to prevent overly long descriptions.
- getDescription function:
- Changed line break handling to replace multiple consecutive line breaks with a single double line break.
- Added trim() to remove leading/trailing whitespace.
- Applied truncate function to the final description.
- Added getChannelUrl function:
- Provides a more robust method to extract and validate channel URLs.
- Added waitForElement function:
- Replaces observeElement with a more flexible function that includes a timeout.
- processMetadata function:
- Wrapped in a try-catch block for better error handling.
- Applied sanitizeBBCode to title, channel name, and description.
- Used getChannelUrl function for channel URL extraction.
- Added fallback "Not available" for subscribers if not found.
- Changed BBCode formatting:
- Removed extra spaces and newlines for cleaner output.
- Stopped splitting and rejoining description lines, using the cleaned-up description directly.
- Main execution:
- Replaced observeElement with waitForElement for title detection.
- Added error handling if the title element fails to load.
These changes aim to improve the robustness, error handling, and output formatting of the bookmarklet, addressing potential issues with different YouTube page layouts and content types.
edit:
update
V2.1
doesn't truncate title or description to 500 characters