DEV Community

Anuraag Gupta
Anuraag Gupta

Posted on

TamperMonkey Script for Modifying UI of Youtube Using ChatGpt

Disclaimer : This article is created using ChatGpt.
I helped with the prompt, testing and improving the final output and editing final draft of this article. Coz I'm too lazy to google now.

Enhancing YouTube Viewing Experience with a TamperMonkey Script

Introduction:

As an avid consumer of online videos, I have always wished for a seamless viewing experience that includes being able to enjoy comments alongside the videos. YouTube, being one of the most popular video-sharing platforms, provides a vibrant comment section that can often enhance the overall watching experience. However, the default layout of YouTube doesn't allow for a convenient display of both the video and comments simultaneously. Motivated by this desire, I set out to create a TamperMonkey script that would enable me, and others, to enjoy comments alongside videos.

Human Note :

I always was frustrated having to scroll down to read comments while watching any funny videos, probably from a movie, or some old music video which was trending due to TikTok. I wished someway I could watch both Video and the funny comments at the same time.

Admiring TamperMonkey Scripts:

I have always been fascinated by the power and flexibility offered by TamperMonkey scripts. These user scripts allow users to modify the behavior of websites to suit their preferences, unlocking a realm of customization possibilities. Intrigued by the potential of TamperMonkey scripts, I embarked on a journey to develop a solution that would meet my specific requirements and share it with the world.

Human Note :

TamperMonkey is great to run some custom scripts. Its a chrome extension which allows you to add custom scripts to run in background. I personally use it to add Dislikes back in Youtube videos, translate comments in youtube comment section etc.

Challenges Faced:

Human Note:

I was always too lazy to go about developing this. Coz of the efforts, so I decided to make use of ChatGpt, I knew it can spit out code pretty fast, and it will have errors which I'll be able to debug and fix, which is what I did. By first getting initial script and testing using Dev Tools and see if it worked. It also saved me time from googling various Document Related apis. I always get deviated from my main goal when I encounter Documentation as I get too invested in reading what else is there for me to use. So ChatGPT helped me here by saving me time.

During the initial stages of script development, I encountered several challenges that needed to be addressed. One significant hurdle was ensuring that the DOM elements I needed were available when the script executed. Initially, I attempted various approaches such as waiting for the document to load, utilizing mutation observers, and setting timeouts to allow for DOM rendering. However, despite these efforts, some situations still resulted in unreliable element availability.

Waiting for Document to Load:

One of the initial approaches I tried was waiting for the document to fully load before accessing the required DOM elements. This was done using the window.addEventListener function with the 'load' event. However, I found that in certain scenarios, the elements were still not available even after the document had loaded.

javascript

// Wait for the document to be fully loaded
window.addEventListener('load', function() {
    // Attempt to access the DOM elements here
});
Enter fullscreen mode Exit fullscreen mode

Mutation Observer:

In an attempt to address the issue of element availability, I employed a Mutation Observer to detect changes in the DOM and react accordingly. The idea was to observe the parent element of the target elements and trigger the desired actions once the target elements were added. However, this approach didn't consistently ensure that the elements were available when needed.

javascript

// Create a new Mutation Observer
var observer = new MutationObserver(function(mutationsList) {
    for (var mutation of mutationsList) {
        // Check for the desired changes in the DOM and trigger actions
    }
});

// Start observing the parent element
observer.observe(parentElement, { childList: true, subtree: true });
Enter fullscreen mode Exit fullscreen mode

Human Note

I had high hopes for Mutation Observer but it didn't work.

setTimeout:

To provide a delay and allow the DOM to render before accessing the required elements, I initially used setTimeout. This approach involved setting a specific timeout duration and executing the desired code after the specified delay. However, relying solely on setTimeout didn't guarantee that the elements would be available within the given time frame.

javascript

// Wait for a specific duration using setTimeout
setTimeout(function() {
    // Attempt to access the DOM elements here
}, 2000); // Adjust the delay (in milliseconds) as needed
Enter fullscreen mode Exit fullscreen mode

Refining the Solution with Iterative Approaches:

To overcome the issue of element availability, I further refined the script by incorporating an iterative approach. I implemented the use of setInterval, which continuously checked for the presence of the required DOM elements. This iterative approach proved to be effective, ensuring that the script executed only when all necessary elements were available.

javascript

// Start checking for element availability
var checkElementsInterval = setInterval(function() {
    var element1 = document.querySelector(selector1);
    var element2 = document.querySelector(selector2);

    if (element1 && element2) {
        switchElements(element1, element2);
        clearInterval(checkElementsInterval); // Stop the interval once elements are found
    }
}, 200); // Adjust the interval (in milliseconds) as needed
Enter fullscreen mode Exit fullscreen mode

Tackling CSS Challenges:

In the process of developing the script, I encountered additional challenges related to CSS. The YouTube user interface employs hardcoded pixel values, which can complicate modifications. However, I persevered and devised my own hacks to work around these challenges. By leveraging various techniques and experimenting with CSS modifications, I was able to overcome the limitations imposed by the YouTube UI and make the necessary adjustments to enhance the viewing experience.

javascript

// Ensure Secondary element occupies available width
secondary.style = "width:100%";
// Youtube uses hardcoded px for video tags. This seemed easier for Mac's screen
comments.style = "width:426px; height: 100vh;overflow: auto;";
Enter fullscreen mode Exit fullscreen mode

Human Note

I expected a bit better from YT devs than to use hardcoded Pixel values for Video and VideoMenu. It messes up with Responsiveness and you have to rely on using hardcoded values again to fix 1 mess. I always preach this wherever possible avoid using hardcoded values in CSS.

Conclusion:

Developing a TamperMonkey script to facilitate a seamless integration of comments alongside videos on YouTube has been a rewarding experience. By combining my admiration for TamperMonkey scripts, determination to overcome challenges, and exploration of CSS modifications, I was able to create a script that enhances the YouTube viewing experience. The challenges I faced, including unreliable element availability, led me to employ iterative approaches such as using setInterval to ensure element readiness. Additionally, I tackled CSS challenges by incorporating custom style modifications to overcome hardcoded pixel values in the YouTube UI.

I look forward to sharing this solution with fellow video enthusiasts, empowering them to customize their YouTube experience and enjoy the best of both worlds - engaging comments and captivating videos. Through the power of TamperMonkey scripts and perseverance in overcoming obstacles, we can truly elevate our online video viewing experiences.

Human Note:

ChatGpt is nowhere near there as many are fear mongering about its capabilities, but it will soon reach there for sure. I have personally used it for various stuff and found it wrong many times. Its just like how one of my seniors used to say about Googling and using other tech forums like Stackoverflow to solve a problem, to use a copied solution you still need to use your brain. Same applies to this tool. Its basically a tool for you to utilise and fail fast so you can stumble onto right solution and deliver more value. I had been thinking of building this for a very long time but putting off due to other work. Finally I could. I'm still getting used to it to be honest, I still accidentally scroll down at the end of each video on Youtube.

Final Script -
https://github.com/anu1097/userscripts

// ==UserScript==
// @name         Youtube Comments And Secondary Video Recommender Element Switcher
// @version      1.0.5
// @description  Switches the positions of two elements on a web page
// @match        *://*.youtube.com/*
// @grant        none
// @author       Anuraag Gupta
// @license      MIT
// ==/UserScript==

(function() {
    'use strict';
    let checkElementsInterval;
    function switchElements(element1, element2) {
        // Get the parent node of both elements
        var parent1 = element1.parentNode;
        var parent2 = element2.parentNode;

        // Get the next sibling of both elements
        var next1 = element1.nextSibling;
        var next2 = element2.nextSibling;

        // Swap the positions of the elements by inserting them in their new positions
        parent1.insertBefore(element2, next1);
        parent2.insertBefore(element1, next2);
        clearInterval(checkElementsInterval);
    }
    // Wait for the document to be fully loaded
    window.addEventListener('load', function() {
        checkElementsInterval = setInterval(function() {
            var comments = document.getElementById('comments'); // Replace 'element1' with the ID of your first element
            var secondary = document.getElementById('secondary'); // Replace 'element2' with the ID of your second element

            if (comments && secondary) {
                switchElements(comments, secondary);
                secondary.style = "width:100%";
                // Youtube uses hardcoded px for video tags. This seemed easier for Mac's screeen
                comments.style = "width:426px; height: 100vh;overflow: auto;";

            }
        }, 500); // Adjust the delay (in milliseconds) as needed
    })
})();
Enter fullscreen mode Exit fullscreen mode

Final Output -

Image description

To Install from GreasyFork Easily
https://greasyfork.org/en/scripts/467477-youtube-comments-and-secondary-video-recommender-element-switcher

Resources -

  1. TamperMonkey - https://www.tampermonkey.net/
  2. ChatGpt - https://chat.openai.com/

Top comments (0)