我当时在玩Youtube API,想创建一个Chrome扩展程序,将iframe注入当前网站。
起初,我会简单地尝试一下,它可以按预期工作:
(function() {
// https://developers.google.com/youtube/iframe_api_reference
console.log('loaded');
const anchorPlay = document.createElement('a');
anchorPlay.id = 'play-button';
anchorPlay.innerHTML = 'Play';
const anchorPause = document.createElement('a');
anchorPause.id = 'pause-button';
anchorPause.innerHTML = 'Pause';
const iFrameElement = document.createElement('iframe');
iFrameElement.setAttribute('id', 'video');
iFrameElement.setAttribute(
'src',
'https://www.youtube.com/embed/krVkvyQjyBQ?enablejsapi=1&html5=1'
);
iFrameElement.setAttribute('allowfullscreen', '');
iFrameElement.setAttribute('frameborder', '0');
iFrameElement.setAttribute('height', '315');
iFrameElement.setAttribute('width', '560');
document.body.appendChild(anchorPlay);
document.body.appendChild(anchorPause);
document.body.appendChild(iFrameElement);
// global variable for the player
var player;
// this function gets called when API is ready to use
window.onYouTubePlayerAPIReady = function() {
alert('called onYouTubePlayerAPIReady');
// create the global player from the specific iframe (#video)
player = new YT.Player('video', {
events: {
// call this function when player is ready to use
onReady: onPlayerReady
}
});
};
function onPlayerReady(event) {
// bind events
var playButton = document.getElementById('play-button');
playButton.addEventListener('click', function() {
player.playVideo();
});
var pauseButton = document.getElementById('pause-button');
pauseButton.addEventListener('click', function() {
// player.pauseVideo();
const currTime = player.getCurrentTime();
alert(currTime);
});
}
// Inject YouTube API script
var tag = document.createElement('script');
tag.src = 'https://www.youtube.com/player_api';
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
})();
https://codepen.io/thadeuszlay/pen/gQwwoZ
但是一旦我将其创建为chrome扩展名,就不会调用函数window.onYouTubePlayerAPIReady
。当所有元素都正确加载后(按钮和iFrame在那,我可以看到控制台日志)。
控制台没有错误。我还可以看到YT-API脚本已正确插入<head>
中。我也停用了广告拦截器。
在我的Chrome扩展程序中,内容脚本看起来与上面的代码笔代码完全相同。我的manifest.json
看起来像这样:
{
"name": "test",
"version": "1.0.0",
"offline_enabled": true,
"description": "test.",
"permissions": ["activeTab", "tabs"],
"browser_action": {
"default_popup": "popup.html",
"default_icon": {
"16": "images/get_started16.png",
"32": "images/get_started32.png",
"48": "images/get_started48.png",
"128": "images/get_started128.png"
}
},
"icons": {
"16": "images/get_started16.png",
"32": "images/get_started32.png",
"48": "images/get_started48.png",
"128": "images/get_started128.png"
},
"content_scripts": [{
"css": ["styles.css"],
"js": ["content.js"],
"run_at": "document_idle",
"all_frames": true,
"matches": ["https://*/*", "http://*/*"]
}],
"manifest_version": 2
}