Search code examples
javascripthtmldomgoogle-chrome-extension

How to disable click event on video element in youtube


I am currently working on a chrome extention for youtube and I want to disable the option for the user to pause/play the video by clicking on it.

I saw some posts that say "video.off('click');" but it dosent work.

I tried this one also :

video.addEventListener('click', function(event){
    console.log("preventing?")
    event.preventDefault();
});

but still it doesn't do nothing.

I would love some help if possible - Thank you all in advance!

here is the video element of youtube

Edit:

I saw the comments and I want to sharpen my question. I need a solution to disabling just the click event to stop the play/pause from there.

I also need the answer to be written in a javascript file because I want to control whether or not the user can click on the video.

I've also looked in: Javascript code for disabling mouse click for youtube videos but I haven't managed to find a corrent solution to my spesific question. I saw one solution that recommend to add a transparent overlay on top of the video element but I have no idea how to do so and how to make it resize as the video player itself resizes


Solution

  • Attach a click listener on window + use the capture phase by specifying true for the third parameter of addEventListener + use stopPropagation, so that your listener will be the first target in the event propagation chain i.e. it'll run before the site's handlers because sites usually don't use the capture phase.

    window.addEventListener('click', event => {
      if (event.target.matches('video')) {
        event.stopPropagation();
      }
    }, true);
    

    Note that if some rare site uses the exact same trick, you can still override it by declaring your content script with "run_at": "document_start".