Search code examples
javascripthtmldomyoutubebrowser-extension

How to focus/click on YouTube's Comment Box with JS (DOM)


1. Context

I'm creating a browser extension to enhance YouTube's keyboard navigation. One of the shortcuts I have in mind is for commenting1.

1: I'm currently using Dart, but it mimics JS and later gets transpiled to it anyway.

2. What I've Tried

YouTube uses a lot of custom HTML elements, so it hasn't been clear to me what works and when, I end up having to reverse-engineer what's going on every time I'm faced with a custom tag.

I've basically tried mostly something like this:

document.querySelector('#labelAndInputContainer > div').click();

Should I use focus() instead?

The div#labelAndInputContainer element gets a new class called focused once it is focused.

3. Other Optional Challenge

The discussion of this last section has been redirected to this other question.

At first, YouTube doesn't load the comment section below a video. Only when you scroll down does the comment section appear2. So how can I find out which event is triggering the comment section to load? And how can I artificially dispatch it? — Otherwise the HTML element for the comment box will be nonexistent.

I've been using getEventListeners() to figure out which events work on which elements.

2: Another example is when a YouTube page reloads/navigates to another one, which is triggered by yt-navigate-start.


As you've probably noticed, I'm not a JS expert, so feel free to go down to the basics or give me noob tips.


Solution

  • Currently you can focus on the comment input using its Id:

    document.getElementById("simplebox-placeholder").focus();
    

    However, it is not loaded until you page-down and wait for it to load. So, page-down and wait a while.

    Also, depending on the width of the window, you might need to multiple page-downs.