Google chrome extension 如何在本地加载YouTube API?
我需要在本地加载YouTube API(谷歌扩展不允许外部脚本)。因此,我将这些文件下载到我的目录中:Google chrome extension 如何在本地加载YouTube API?,google-chrome-extension,youtube-api,Google Chrome Extension,Youtube Api,我需要在本地加载YouTube API(谷歌扩展不允许外部脚本)。因此,我将这些文件下载到我的目录中: https://www.youtube.com/player_api https://s.ytimg.com/yts/jsbin/www-widgetapi-vfl4qCmf3.js 但是,当我尝试通过内容脚本以编程方式注入时,会出现以下错误: Uncaught ReferenceError: YTConfig is not defined 对OP说:你就快到了!我要感谢MSDN作者Jon
https://www.youtube.com/player_api
https://s.ytimg.com/yts/jsbin/www-widgetapi-vfl4qCmf3.js
但是,当我尝试通过内容脚本以编程方式注入时,会出现以下错误:
Uncaught ReferenceError: YTConfig is not defined
对OP说:你就快到了!我要感谢MSDN作者Jonathan Waldman在他的一次培训课程中提到了这项技术 要查看,YTConfig的定义如下: 在这里: iframe_api是首选的链接 总而言之,您在每个JS代码链接上方提供的链接: 您还需要一个id为“player”的Div标记和另一个脚本标记,用于指定要观看的视频。因此总共有四个脚本标记:
<div id="player"></div>
<script>...place the player Div here</script>
<script>...place code from www-widgetapi-vfl4qCmf3.js here...</script>
<script>...place code from iframe_api here...</script>
<script>...place the code below here</script>
…将播放器Div放在这里
…将来自www-widgetapi-vfl4qCmf3.js的代码放在此处。。。
…将iframe_api中的代码放在此处。。。
…将代码放在下面
以下是最终脚本标记的代码(请注意,您可能希望更改videoId属性,以便它指向YouTube站点上所需视频的ID):
var播放器;
函数onyoutubeiframeapiredy(){
player=新的YT.player('player'{
高度:“390”,
宽度:“640”,
videoId:'M7lc1UVf VE',
活动:{
“onReady”:onPlayerReady,
“onStateChange”:onPlayerStateChange
}
});
}
// 4. 当视频播放器准备就绪时,API将调用此函数。
函数onPlayerReady(事件){
event.target.playVideo();
}
// 5. 当播放器的状态改变时,API调用此函数。
//该功能指示播放视频时(状态=1),
//玩家应该玩六秒钟,然后停下来。
var done=false;
函数onPlayerStateChange(事件){
如果(event.data==YT.PlayerState.PLAYING&&!done){
设置超时(停止视频,6000);
完成=正确;
}
}
函数stopVideo(){
player.stopVideo();
}
当我执行上述操作时,页面工作正常,我的开发机器本地有所有YouTube代码。在内容脚本中,或者在内容脚本的扩展页面中。我使用内容脚本在页面底部附加YT视频。现在我想在内容脚本中使用加载YT库来控制它。这将有点困难,因为YT API使用
标记来加载依赖项。您可以检查需要哪些依赖项,并将它们包含在扩展中,或者使用。是的,我翻遍了代码,似乎只需要这两个文件。这很奇怪,因为YTConfig是在第二个文件中定义的。我不确定它为什么显示YTConfig未定义。也许我装错了?
<script>
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
}
// 5. The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
</script>