Disappearing Facebook share button: A common occurrence when navigating in Nuxt.js (Vue.js)

Within my nuxt.js web app, utilizing version 2.15.7, I have integrated a Facebook share button by following the instructions outlined in this comprehensive code example.

Upon initial load of the application, the Facebook share button appears as expected. However, upon navigating to another route and subsequently returning, the button mysteriously vanishes. What could be causing this issue and how can it be resolved?

I've experimented with various solutions provided by individuals such as @Cbroe and @kissu:

  1. Facebook share button disappear after updatePanel
  2. How to add a 3rd party script code into Nuxt
  3. Facebook social plug-in not showing up when added dynamically

Regrettably, none of the aforementioned approaches have successfully resolved the issue at hand.

Interestingly, Chrome's Vue developer tools indicate that the component <FbShareButton> is present, yet it remains invisible on the page.

The original code snippet is presented below:

To incorporate the Facebook SDK into the application, I crafted a nuxt plugin named loadFacebookSdk.js which contains the following code snippet:

Vue.prototype.$loadFacebookSDK = async (d, s, id) => {
    var js = d.getElementsByTagName(s)[0]
    var fjs = d.getElementsByTagName(s)[0]
    if (d.getElementById(id)) {
        return
    }
    js = d.createElement(s)
    js.id = id
    js.src = "https://connect.facebook.net/en_US/sdk.js#xfbml=1&version=v3.0"
    fjs.parentNode.insertBefore(js, fjs)
}

Subsequently, the above plugin was registered within the nuxt.config.js file as demonstrated below:

plugins: [
    { src: "~/plugins/loadFacebookSdk.js", mode: 'client' }
  ]

Finally, a FbShareButton.vue component was developed to handle the loading of the facebook SDK and render the facebook share button:

<template>
    <div>
        <div id="fb-root"></div>
        <div class="fb-share-button" 
                data-href="https://developers.facebook.com/docs/plugins/" 
                data-layout="button" 
                data-size="small"
                >
        </div>
    </div>    
</template>

<script>
export default {
    async created () {
        if (process.client) {
            await this.$loadFacebookSDK(document, 'script', 'facebook-jssdk')
        }
    }
}
</script>

Answer №1

In case you are working with NUXT3 and Typescript, check out the code snippet below for the equivalent setup.

<template>
  <div id="1">
    <div id="fb-root"></div>
    <div
      class="fb-share-button"
      :data-href="articleUrl"
      data-layout="button"
      data-size="small"
    ></div>
  </div>
</template>

<script lang='ts' setup>
const props = defineProps({
  articleUrl: String,
  articleTitle: String,
  articleImage: String,
  articleDescription: String,
});

useHead({
  meta: [
    { property: "og:url", content: props.articleUrl },
    { property: "og:type", content: "website" },
    { property: "og:title", content: props.articleTitle },
    { property: "og:description", content: props.articleDescription },
    { property: "og:image", content: props.articleImage },
    { property: "fb:app_id", content: "YOUR_FB_APP_ID" },
  ],
  script: [
    {
      hid: "fb",
      src: "https://connect.facebook.net/en_US/sdk.js#xfbml=1&version=v3.0",
      defer: true,
      onload: () => {
        (window as any).FB.XFBML.parse();
      },
    },
  ],
});
</script>

Credits to Mindas for providing this solution!

Answer №2

There is a resolution that successfully addressed an issue.

I have developed a distinct component called FbShareButton.vue

All the logic (including the loading of Facebook SDK) is contained within that component as discussed in this and this posts.

Therefore:

<template>
    <div id="1">
        <div id="fb-root"></div>
        <div class="fb-share-button" 
                :data-href="this.articleUrl"
                data-layout="button" 
                data-size="small"
                >
        </div>
    </div>    
</template>

<script>
export default {
    props: ['articleUrl', 'articleTitle', 'articleImage', 'articleDescription'],
    head () {
        return {
            meta: [
                { property: "og:url", content: this.articleUrl },
                { property: "og:type", content: "website" },
                { property: "og:title", content: this.articleTitle },
                { property: "og:description", content: this.articleDescription },
                { property: "og:image", content: this.articleImage },
                { property:"fb:app_id", content:"YOUR_FB_APP_ID" }
            ],
            script: [
                {
                    hid: 'fb',
                    src: 'https://connect.facebook.net/en_US/sdk.js#xfbml=1&version=v3.0',
                    defer: true,
                    // modified after script load
                    callback: () => {
                        FB.XFBML.parse()
                    }
                }
            ]
        }
    }
}
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Disabling buttons in a Fiori UI5 application using HTML: A step-by-step guide

I don't have much experience with scripting languages. I am attempting to hide buttons within a SAP Fiori app by using the "Inspect element" tool in the Mozilla browser. When I delete the HTML code, the button disappears, but I would like to accomplis ...

Exploring the use of @HostListener in Angular for handling drop events

I am currently working on developing a directive for drag and drop functionality with files. I have successfully implemented the dragenter and dragleave events, but for some reason, the drop event is not being recognized. @HostListener('drop', [ ...

What is the best way to manage errors and responses before passing them on to the subscriber when using rxjs lastValueFrom with the pipe operator and take(1

I'm seeking advice on the following code snippet: async getItemById(idParam: string): Promise<any> { return await lastValueFrom<any>(this.http.get('http://localhost:3000/api/item?id=' + idParam).pipe(take(1))) } What is the ...

Using Node.js to return JSON data containing base64 encoded images

In my database, I store all images as base64 with additional data (creation date, likes, owner, etc). I would like to create a /pictures GET endpoint that returns a JSON object containing the image data, for example: Image Data [{ "creation": 1479567 ...

Adjust the styling with jQuery according to the selected value from the dropdown menu

Check out this Fiddle I have a jQuery script that is supposed to change the style of an input box to display:block if the selected value is "<>" (Between). However, currently it is changing the css for all selected items instead of just the target i ...

Is there an equivalent to Tomcat specifically designed for Node.js applications?

Looking for an application server that offers an administration interface to deploy node.js applications, access log files, and manage running applications with options to start, stop, restart, and monitor? ...

Having difficulty incorporating multiple "if" statements into my code

I'm currently working on creating an IE9 specific if statement. Basically, I want to check if the menu is collapsed and then move 3 classes from the left if it is true, or in the opposite direction if it is false. However, I'm struggling to get t ...

When using the `Document.write()` method, an error is returned stating, "Uncaught TypeError: Cannot read property 'document' of null"

I am currently integrating Angular2 into a website as the front-end framework, and it will be displayed on another website using an iframe. When working with the HTTP post method, I am able to receive a JSON response. Here is the API Post method that retu ...

The browser fails to render an EJS-generated page when responding to a Fetch request

Today, I encountered a strange issue that has left me puzzled. In summary, I have been sending a PUT request from a user form to the backend. Since forms do not natively support PUT/DELETE requests, I had to use a script to handle this task for me. let for ...

Vue's parent-child components interact through asynchronous lifecycles

Even though I'm directed to 'myFavouritePage', the message 'Hi, I'm child' is displayed after the redirection. Is there a parent function that creates the child components upon completion? Parent: beforeCreate () { var or ...

Spinning html/css content using JavaScript

Greetings! I am currently working on a demo site using just HTML, CSS, and JavaScript. Typically, I would use Ruby and render partials to handle this issue, but I wanted to challenge myself with JavaScript practice. So far, I have created a code block that ...

Having trouble troubleshooting this issue where the object data is displaying in the console, but encountering an error when trying to use the resetValue

Index.html I am facing an issue while reading data from an object and the seek bar is giving a null error. The images and songs are stored locally, and I am trying to access them. <div class="music-player"> <div class="song&qu ...

Transferring a zipped file from the backend of SailsJS to the frontend of React Redux via

My SailsJS Backend is responsible for generating a zip File when requested by my React App with Redux on the Frontend. I am utilizing Sagas for asynchronous calls and fetch to make the request. In the backend, I have attempted various methods such as: //z ...

What methods can I utilize to transmit Global variable data from a view to a controller?

In my Angular view file, I have the following code snippet. <!DOCTYPE html> <video id="myVideo" class="video-js vjs-default-skin"></video> <script> var dataUri; var videoData; var player = videojs("myVideo", { controls ...

data in Vue not updating after setting value in session storage

I recently encountered an issue with setting values to session storage in my main.ts file after making an axios call. Despite successfully saving the data, I found that accessing it in another component resulted in 'undefined' values. It seems li ...

The storage capacity of localStorage is insufficient for retaining data

While I was trying to troubleshoot an error, I encountered another issue. var save_button = document.getElementById('overlayBtn'); if(save_button){ save_button.addEventListener('click', updateOutput);} This led to the following ...

The problem with 'Access-Control-Allow-Origin' on themoviedb

Is anyone else experiencing an issue with the themoviedb api? When trying to load , I receive the error message: "XMLHttpRequest cannot load. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '' is th ...

The condition of the variable not being bound

<button id="btn1"> Button 1 </button> <button id="btn2" v-if="state == 2"> Button 2 </button> export default { data() { return { emailPreferences: { isLoading: false ...

Tips for ensuring that the headers remain fixed in both the horizontal and vertical directions while allowing the data

I have been trying to create a table with a fixed header (meaning the header must be visible both vertically and horizontally). The table should be scrollable It should have a horizontal header The vertical header should match the horizontal header When ...

Errors encountered: Navigation guard causing infinite redirection due to unhandled runtime issue

My Vue3 router is set up with the following routes: export const routes: Array<RouteRecordRaw> = [ { path: "/", name: "Browse Questions", component: HomeView, meta: { access: "canAdmin", }, ...