0

i want to edit the font style of youtube videos i saw in inspect mode of youtube.com that a span tag with ytp-caption-segment wrappes the text file of subtitle.so i use below code to capture this element:

 var subtitle=document.getElementsByClassName('ytp-caption-segment');

but it always returns undefined,so i can not get the other attributes of it? what can i do? i think the reason is subtitle appears 1 sec after starting of video,so the visibility or display of it maybe none.any idea?

moein
  • 21
  • 2

1 Answers1

0

The span.ytp-caption-segment element is not a persistent part of the video player, it exists in the DOM only when you see a line of subtitle displayed. When the subtitle disappears, the element is removed from the DOM and it's created again with the next subtitle line.

So basically you have two strategies:

1. Insert a CSS rule for .ytp-caption-segment

This is the simplest way but unfortunately this won't work perfectly in this case because Youtube generates a lot of inline style rules into ytp-caption-element, and that cannot be overwritten from CSS.

These are the inline styles used by Youtube (at least for currently):

display: inline-block;
white-space: pre-wrap;
background: rgba(8, 8, 8, 0.75);
font-size: 20.7556px;
color: rgb(255, 255, 255);
fill: rgb(255, 255, 255);
font-family: "YouTube Noto", Roboto, "Arial Unicode Ms", Arial, Helvetica, Verdana, "PT Sans Caption", sans-serif;

These are mostly the parameters you can set in Youtube UI (subtitle options).

CSS still can be used in limited ways, depending on your goal. For example if you want to make bigger fonts, you can use 'transform: scale(2);' instead of the font-size (the transform property is not overwritten with inline CSS).

2. Rewrite the .ytp-caption-segment element

If you want full control, you have to delete the style attribute from ytp-caption-segment or rewrite with your own style. This is not trivial, I describe the main steps:

  1. Insert a CSS rule which hides the subtitle so when a new line is created by the player, it won't appear immediately on the screen. (This could be done with transform or opacity rules.)

  2. Listen for any new lines! (Using a MutationObserver is the preferred way, but a 100msec polling will work also as an easy hack.)

  3. When you got the line, rewrite it's style attribute to your preferred style.

  4. Don't forget to override the CSS rule from point 1. used for hiding the new line! It's easy, as you rewrite the style attribute anyway.

I can create a code snippet for this if you clarify exactly what do you want to change on the subtitle.

blumi
  • 190
  • 2
  • 6