I want to use the "YouTube iframe API" in a "content script" Google Chrome extension. How should I require the Youtube iframe API in my extension?
URL for Youtube iFrame API: https://www.youtube.com/iframe_api.
You usually include scripts in a Google Chrome extension in the manifest file, however Chrome's extension page throws an error since the URL does not end in .js.
Also, it looks like the script at this URL tries to inject <script>
tags, which won't work with a content_script plugin since it doesn't have access to the page's 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
}
});
}
What should I be doing differently? How can I correctly include this script?