AddEventListener in script content not working

I have a chrome extension with popup.html and nested script content. With nested script content I'm trying to access the javascript javascript functions for youtube and everything works fine except for one: addEventListener.

Youtube event listener javascript API listens for video state changes. Therefore, if the end of the video is reached, the state will change to 0.

var currentVideo = document.getElementById('movie_player'); currentVideo.addEventListener("onStateChange", "onytplayerStateChange"); function onytplayerStateChange() { console.log("The state of the player has changed"); } 

This piece of code works fine in a normal environment, but it does not work in script content. Why can't I catch changing events in my script content? Any ideas?

+6
source share
1 answer

Content scripts are not executed in the current page area. The event handler should be injected through another <script> , as described in this answer: Creating a Chrome extension with Youtube events :

 var actualCode = 'function onytplayerStateChange() {' + ' console.log("The state of the player has changed");' + '}'; var script = document.createElement('script'); script.textContent = actualCode; (document.head||document.documentElement).appendChild(script); script.parentNode.removeChild(script); 

PS. The DOM is available for script content, so event handler binding works.

+7
source

Source: https://habr.com/ru/post/911135/


All Articles