问题描述
我有一个带有 popup.html 和注入内容脚本的 chrome 扩展.使用注入的内容脚本,我试图访问 youtube 的 javascript API 函数,除了一个:addEventListener.
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.
Youtube 的 javascript API 的事件监听器监听视频状态的变化.因此,如果到达视频的结尾,状态将变为 0.
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?
推荐答案
内容脚本不在当前页面范围内运行.事件处理程序必须通过另一个 <script>
标记注入,如以下答案所述:使用 Youtube 事件构建 Chrome 扩展:
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.DOM 可用于内容脚本,因此绑定事件处理程序确实有效.
这篇关于内容脚本中的 addEventListener 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!