2017-01-10 68 views

回答

0

我只使用YouTube的「iframe API」,所以我無法評論Vimeo流程。

下面的代碼片段大部分都是從api文檔逐字記錄的,除了承諾部分。當API加載時,它會調用一個可以做任何需要的函數,在這種情況下解決一個承諾,所以我們確信一切都被加載。

var tag = document.createElement('script'), 
    firstScriptTag = document.getElementsByTagName('script')[0]; 

tag.src = 'https://www.youtube.com/iframe_api'; 
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); 

function apiLoaded() { 
    var apiPromise = new Promise((resolve) => { 
    window.onYouTubeIframeAPIReady = function() { 
     resolve(); 
    }; 
    }); 

    return apiPromise; 
} 

務必試圖執行API調用時總是使用由apiLoaded()返回的承諾,例如:

apiLoaded().then(function() { 
    var player = new window.YT.Player('iVideoFrame', { 
    events: { 
     ... 
    } 
    }); 
}); 

這是假設在某個地方你的HTML你定義一個iframe(注意查詢視頻網址中的參數):

<iframe id="iVideoFrame" type="text/html" width="..." height="..." frameborder="0" src="http://www.youtube.com/embed/videoId?enablejsapi=1&amp;controls=1&amp;showinfo=1"></iframe>