addEventListener in content script not working(内容脚本中的 addEventListener 不起作用)
问题描述
我有一个带有 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 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:内容脚本中的 addEventListener 不起作用


基础教程推荐
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01