13

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

Youtube 的 javascript API 的事件监听器监听视频状态的变化。因此,如果到达视频的结尾,状态将变为 0。

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

function onytplayerStateChange() {
   console.log("The state of the player has changed");
}

这段代码在正常环境中运行良好,但在内容脚本中无法运行。为什么我无法在内容脚本中捕捉到不断变化的事件?有任何想法吗?

4

1 回答 1

13

内容脚本不在当前页面范围内运行。事件处理程序必须通过另一个<script>标签注入,如本答案所述: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。DOM 可用于内容脚本,因此绑定事件处理程序确实有效。

于 2012-03-19T20:35:26.823 回答