内容脚本中的addEventListener不起作用 [英] addEventListener in content script not working

查看:148
本文介绍了内容脚本中的addEventListener不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有popup.html和注入内容脚本的Chrome扩展。使用注入的内容脚本,我试图访问YouTube的JavaScript API函数,除了一个:addEventListener外,它都可以正常工作。


$ b Youtube的JavaScript API的事件侦听器侦听视频的状态改变。因此,如果视频结束,状态变为0.

  var currentVideo = document.getElementById('movie_player') ; 
currentVideo.addEventListener(onStateChange,onytplayerStateChange);

函数onytplayerStateChange(){
console.log(玩家状态已更改);

$ / code>

这段代码在正常环境下工作得很好,但无法工作在内容脚本中。为什么我无法在内容脚本中捕捉更改事件?任何想法?

解决方案

内容脚本不在在当前页面的范围内运行。如本答案所述,事件处理程序必须通过另一个< script> 标记注入:

  var actualCode ='function onytplayerStateChange(){'
+'console.log(玩家状态改变了);'
+'}';

var script = document.createElement('script');
script.textContent = actualCode;
(document.head || document.documentElement).appendChild(script);
script.parentNode.removeChild(script);

PS。 DOM可用于内容脚本,因此绑定事件处理程序确实有效。


I've got a chrome extension with a popup.html and an injected content script. With the injected content script I'm trying to access youtube's javascript API functions and it all works fine except for one: addEventListener.

The event listener of Youtube's javascript API listens for the state of the video to change. So if the end of the video is reached the state changes 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 just fine in a normal environment but it fails to work in content script. Why can't I catch changing events in my content script? Any ideas?

解决方案

Content scripts do not run in the scope of the current page. The event handler has to be injected via another <script> tag, as described in this answer: Building 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 to the content script, so binding the event handler does work.

这篇关于内容脚本中的addEventListener不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆