我想在“内容脚本” Google Chrome扩展程序中使用“ YouTube iframe API”。我应该如何在扩展程序中使用Youtube iframe API?
YouTube iFrame API的网址:https : //www.youtube.com/iframe_api。
通常,您会在清单文件的Google Chrome扩展程序中包含脚本,但是Chrome扩展程序页面会引发错误,因为URL并非以.js结尾。
另外,看起来该URL处的脚本试图注入<script>
标签,该标签不适用于content_script插件,因为它无法访问页面的javascript。
manifest.json
{
...
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["main.js"],
"all_frames": true
}
]
}
main.js
// Inject the script, but this won't work since content scripts can't access the page's javascript (which is where this script is injected).
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/player_api";
(document.head || document.documentElement).appendChild(tag);
// Create our own player
var player;
var videoID = 'e7Px2yJA6S4';
// When the YouTube API is loaded, it calls this function.
function onYouTubeIframeAPIReady() {
player = new YT.Player('movie_player', {
height: '390',
width: '640',
videoId: videoID,
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
我应该怎么做?如何正确包含此脚本?
Rob W的答案涵盖了这种情况:使用内容脚本将代码插入页面上下文中,请参见方法1和方法2。
通常,由于内容脚本以孤立的单词执行,因此,如果<script>
在内容脚本(位于孤立的世界)中初始化youtube播放器时,如果将youtube api作为标签(位于网页世界中)包含在内,则它将失败,因为内容脚本和<script>
标签无法访问彼此定义的变量/函数。
一种解决方法是同时通过<script>
标签注入这些代码,请参见以下示例。
manifest.json
{
...
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["inject.js"],
"all_frames": true
}
],
"web_accessible_resources": ["https://www.youtube.com/player_api"]
}
inject.js
function insertScriptFile(callback) {
// Inject the script
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/player_api";
tag.onload = function () {
callback();
};
(document.head || document.documentElement).appendChild(tag);
}
function insertEmmedCode() {
var actualCode = `// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
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();
}
`;
var script = document.createElement('script');
script.textContent = actualCode;
(document.head || document.documentElement).appendChild(script);
}
var div = document.createElement("div");
div.id = "player";
document.body.appendChild(div);
insertScriptFile(function () {
insertEmmedCode();
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句