我正尝试在我的window 8.1应用程序中播放youtube视频,代码如下。
var videoPlayer = document.getElementById("videoPlayer");
var content = '<iframe width="480" height="270" src="http://www.youtube.com/embed/XGSy3_Czz8k?rel=0" frameborder="0" allowfullscreen></iframe>';
WinJS.Utilities.setInnerHTMLUnsafe(videoPlayer, content);
其中视频播放器是视频播放器出现的div的名称,但我无法播放视频。我还尝试使用中的示例代码https://developers.google.com/youtube/iframe_api_reference#Examples但效果不太好。所以请任何人帮我做这件事。
提前感谢
我设法让这个场景为我工作,但我必须克服一些困难才能使它工作。
首先,为了加载他们需要与iframe通信的外部脚本,我不得不在播放器自己的外部iframe中对其进行沙盒处理,该外部iframe:
<div class="playerContainer">
<iframe class="playerFrame" src="ms-appx-web:///pages/video/iframe.html" style="visibility: hidden" scrolling="no"></iframe>
</div>
然后我不得不编辑我的APPXMANIFEST,将YouTube域作为ContentURI规则包括在内:
https://*.youtube.com
我的iframe.html非常简单:
<!DOCTYPE html>
<html>
<head>
<title>Video Player Iframe</title>
<link href="/pages/video/iframe.css" rel="stylesheet" />
<script src="/pages/video/iframe.js"></script>
</head>
<body>
<iframe id="player"
src="https://www.youtube.com/embed/?enablejsapi=1"
frameborder="0"
style="visibility: hidden"></iframe>
</body>
</html>
然后在iframe.js内部,我大量地从https://developers.google.com/youtube/iframe_api_reference#Examples
(function () {
"use strict";
window.addEventListener('message', function (e) {
if (e.data.op === 'load') {
loadVideo(e.data.args)
} else if (e.data.op === 'resize') {
resize(e.data.args);
} else if (e.data.op === 'destroy') {
destroy();
}
});
var player;
var videoId;
function loadVideo(args) {
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var playerEl = document.getElementById('player');
playerEl.height = window.innerHeight;
playerEl.width = window.innerWidth;
videoId = args.videoId;
window.onYouTubeIframeAPIReady = function onYouTubeIframeAPIReady() {
playerEl.style.visibility = 'visible';
player = new YT.Player('player', {
events: {
'onReady': onPlayerReady
}
});
}
}
function resize(args) {
player && player.setSize(window.innerWidth, window.innerHeight);
}
function destroy() {
player && player.destroy();
player = null;
}
function onPlayerReady(event) {
event.target.loadVideoById(videoId);
}
})();
正如你从上面看到的,我正在使用iframe的postMessage来告诉包装iframe加载我想要的videoId:
iframe.addEventListener("load", function () {
iframe.style.visibility = 'visible';
if (iframe.contentWindow) {
iframe.contentWindow.postMessage({ op: "load", args: { videoId: video.id} }, "*");
}
});
希望对一些人有所帮助。YouTube IFrame API非常挑剔,当以任何其他方式加载时,对我来说都不太好用。