search
HomeWeb Front-endVue.jsHow to use Facebook embedded video player API in vue3

Text

The Facebook embedded video player API is a client function provided by the JavaScript version of the Facebook SDK. You can play Facebook videos on your website.

Get started

First introduce Facebook SDK

<script async defer src="https://connect.facebook.net/en_US/sdk.js"></script>

Encapsulate it into the component FacebookPlayer

<script setup>
import { onMounted, onBeforeUnmount } from "vue";
const props = defineProps({
  id: { type: String, default: "" },
  src: { type: String, required: true },
  autoplay: { type: Boolean, default: false }
});
const emit = defineEmits(["onEnded", "onPlay", "onPause"]);
onMounted(() => {
  fbAsyncInit();
  loadPlayer();
});
onBeforeUnmount(() => {
  removePlay();
  removePaused();
  removeEnded();
  player = null;
});
// Load Facebook SDK for JavaScript
const fbAsyncInit = () => {
  try {
    window.FB.init({ autoLogAppEvents: true, xfbml: true, version: "v3.2" });
  } catch (error) {
    console.error("FB.init Error", error);
  }
};
// Get Embedded Video Player API Instance
let player = null;
const loadPlayer = () => {
  try {
    window.FB.Event.subscribe("xfbml.ready", (msg) => {
      if (msg.type === "video" && msg.id === `fb-${props.id}`) {
        if (!player) player = msg.instance;
        onPlay(msg.instance);
        onPaused(msg.instance);
        onEnded(msg.instance);
      }
    });
  } catch (error) {
    console.error("FB.Event Error", error);
  }
};
// 播放器方法
const play = () => player && player.play();
const pause = () => player && player.pause();
// 播放器事件
let playListener;
const onPlay = (instance) => {
  playListener = instance.subscribe("startedPlaying", () => emit("onPlay"));
};
const removePlay = () => {
  try {
    if (playListener) playListener.release("startedPlaying");
  } catch (error) {}
};
let pausedListener;
const onPaused = (instance) => {
  pausedListener = instance.subscribe("paused", () => emit("onPause"));
};
const removePaused = () => {
  try {
    if (pausedListener) pausedListener.release("paused");
  } catch (error) {}
};
let endedListener;
const onEnded = (instance) => {
  endedListener = instance.subscribe("finishedPlaying", () => emit("onEnded"));
};
const removeEnded = () => {
  try {
    if (endedListener) endedListener.release("finishedPlaying");
  } catch (error) {}
};
</script>
<template>
  <div
    :id="&#39;fb-&#39; + id"
    class="fb-video"
    :data-href="props.src" rel="external nofollow" 
    :data-autoplay="props.autoplay"
    :data-allowfullscreen="false"
  ></div>
</template>

How to use

<facebook-player id="10153231379946729" src="https://www.facebook.com/facebook/videos/10153231379946729/"></facebook-player>

Notes

class="fb-video" This class name cannot be removed.

If multiple players are used on a page, a unique ID must be passed to identify the player.

Properties

Settings Description Default value
data-href The absolute URL of the video. n/a
data-allowfullscreen Allow the video to play in full screen mode. Can be false or true. false
data-autoplay Automatically start playing the video when the page loads. The video will play without sound (muted). Users can turn on sound through the video player controls. This setting doesn't work on mobile devices. Can be false or true. false
data-lazy true means you can use the browser's lazy loading mechanism by setting the loading="lazy" iframe attribute. The effect is that if the plug-in is not near the viewport, the browser will not display the plug-in, and you may never see the plug-in. Can be one of true or false (default). false
data-width The width of the video container. The minimum value is 220px. auto
data-show-text If there is any text in the Facebook post associated with the video, set to true to add that text . Applies to desktop sites only. false
data-show-captions Set to true to display subtitles by default (if applicable). Subtitles are only available on desktop devices. false

Method

##FunctionDescriptionParameters (type)play()Play the video. pause()Pause the video. seek(seconds)Search for the specified location. seconds (number)mute()Set the video to mute. unmute()Unmute the video. ##isMuted()setVolume(volume)getVolume()getCurrentPosition()getDuration()subscribe(event, eventCallback)##Event




True when the video is set to mute, false otherwise.
Sets the volume to the specified number (float, ranging from 0 to 1). volume (float)
Returns the current volume of the video (float, ranging from 0 to 1).
Returns the current video time position, accurate to seconds.
Returns the video duration, accurate to seconds.
Add a listening function for the specified event. For more information about events, see the Events section. Returns a password containing a release method, calling this method will remove the listener from the event again. event (string), eventCallback (function)

##EventDescriptionFired when the video starts playing. Fires when the video is paused. Triggered when the video is finished playing. Fired when the video starts buffering. Fired when the video resumes from buffering. Triggered when an error occurs in the video.
startedPlaying
paused
finishedPlaying
startedBuffering
finishedBuffering
error

The above is the detailed content of How to use Facebook embedded video player API in vue3. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
Vue.js vs. React: Scalability and MaintainabilityVue.js vs. React: Scalability and MaintainabilityMay 10, 2025 am 12:24 AM

Vue.js and React each have their own advantages in scalability and maintainability. 1) Vue.js is easy to use and is suitable for small projects. The Composition API improves the maintainability of large projects. 2) React is suitable for large and complex projects, with Hooks and virtual DOM improving performance and maintainability, but the learning curve is steeper.

The Future of Vue.js and React: Trends and PredictionsThe Future of Vue.js and React: Trends and PredictionsMay 09, 2025 am 12:12 AM

The future trends and forecasts of Vue.js and React are: 1) Vue.js will be widely used in enterprise-level applications and have made breakthroughs in server-side rendering and static site generation; 2) React will innovate in server components and data acquisition, and further optimize the concurrency model.

Netflix's Frontend: A Deep Dive into Its Technology StackNetflix's Frontend: A Deep Dive into Its Technology StackMay 08, 2025 am 12:11 AM

Netflix's front-end technology stack is mainly based on React and Redux. 1.React is used to build high-performance single-page applications, and improves code reusability and maintenance through component development. 2. Redux is used for state management to ensure that state changes are predictable and traceable. 3. The toolchain includes Webpack, Babel, Jest and Enzyme to ensure code quality and performance. 4. Performance optimization is achieved through code segmentation, lazy loading and server-side rendering to improve user experience.

Vue.js and the Frontend: Building Interactive User InterfacesVue.js and the Frontend: Building Interactive User InterfacesMay 06, 2025 am 12:02 AM

Vue.js is a progressive framework suitable for building highly interactive user interfaces. Its core functions include responsive systems, component development and routing management. 1) The responsive system realizes data monitoring through Object.defineProperty or Proxy, and automatically updates the interface. 2) Component development allows the interface to be split into reusable modules. 3) VueRouter supports single-page applications to improve user experience.

What are the disadvantages of VueJs?What are the disadvantages of VueJs?May 05, 2025 am 12:06 AM

The main disadvantages of Vue.js include: 1. The ecosystem is relatively new, and third-party libraries and tools are not as rich as other frameworks; 2. The learning curve becomes steep in complex functions; 3. Community support and resources are not as extensive as React and Angular; 4. Performance problems may be encountered in large applications; 5. Version upgrades and compatibility challenges are greater.

Netflix: Unveiling Its Frontend FrameworksNetflix: Unveiling Its Frontend FrameworksMay 04, 2025 am 12:16 AM

Netflix uses React as its front-end framework. 1.React's component development and virtual DOM mechanism improve performance and development efficiency. 2. Use Webpack and Babel to optimize code construction and deployment. 3. Use code segmentation, server-side rendering and caching strategies for performance optimization.

Frontend Development with Vue.js: Advantages and TechniquesFrontend Development with Vue.js: Advantages and TechniquesMay 03, 2025 am 12:02 AM

Reasons for Vue.js' popularity include simplicity and easy learning, flexibility and high performance. 1) Its progressive framework design is suitable for beginners to learn step by step. 2) Component-based development improves code maintainability and team collaboration efficiency. 3) Responsive systems and virtual DOM improve rendering performance.

Vue.js vs. React: Ease of Use and Learning CurveVue.js vs. React: Ease of Use and Learning CurveMay 02, 2025 am 12:13 AM

Vue.js is easier to use and has a smooth learning curve, which is suitable for beginners; React has a steeper learning curve, but has strong flexibility, which is suitable for experienced developers. 1.Vue.js is easy to get started with through simple data binding and progressive design. 2.React requires understanding of virtual DOM and JSX, but provides higher flexibility and performance advantages.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft