如何正确使用Facebook嵌入视频Player API实现JS控制(播放/暂停)
Hey there! Let's break down why your video player controls (like play()/pause()) aren't working after page load, even though the initial seek() works.
The Root Cause
Looking at your code, the ssp_video_player variable is defined inside the fbAsyncInit function—that makes it a local variable, which means it's not accessible outside of that function scope once the initial setup runs. The initial seek() works because it's called immediately within the xfbml.ready event handler, but any later attempts to call ssp_video_player.play() from elsewhere can't find the variable.
Fix 1: Move the Player Instance to Global Scope
To make the player instance accessible globally, attach it to the window object. Here's your modified code:
// Define the player variable globally so external code can access it window.ssp_video_player = null; window.fbAsyncInit = function() { FB.init({ appId : "17xxxxxxxxxx", xfbml : true, version : "v3.5" }); FB.Event.subscribe('xfbml.ready', function(msg) { if (msg.type === 'video') { // Assign the instance to the global variable window.ssp_video_player = msg.instance; // Initial seek still works here window.ssp_video_player.seek(600); } }); };
Fix 2: Test Controls with User Interaction
Now you can call the API methods from anywhere in your code. For example, add buttons to test play/pause:
<button onclick="handleVideoControl('play')">Play Video</button> <button onclick="handleVideoControl('pause')">Pause Video</button> <script> function handleVideoControl(action) { // Check if the player instance is ready before calling methods if (window.ssp_video_player) { switch(action) { case 'play': window.ssp_video_player.play(); break; case 'pause': window.ssp_video_player.pause(); break; default: console.log('Invalid control action'); } } else { console.log('Video player instance not initialized yet!'); } } </script>
Bonus: Handle Multiple Video Players
If your page has multiple embedded videos, use the msg.id property from the xfbml.ready event to map each player instance to its unique ID:
window.videoPlayers = {}; FB.Event.subscribe('xfbml.ready', function(msg) { if (msg.type === 'video') { // Store each player by its HTML element ID window.videoPlayers[msg.id] = msg.instance; // Example: Seek only on a specific video if (msg.id === 'my-main-video') { window.videoPlayers[msg.id].seek(600); } } }); // Call controls for a specific video later window.videoPlayers['my-main-video'].play();
Key Takeaways
- Always ensure your player instance is in a scope accessible to the code that needs to control it (global scope works for most cases).
- Verify the
xfbml.readyevent has fully initialized the player before calling any API methods. - For multiple videos, use unique IDs to track individual player instances.
内容的提问来源于stack exchange,提问作者Mohammad Umer

