Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Single Page Applications and Open Graph

I'm writing a SPA that uses underscore templating. The app searches for and rates music albums and returns the result via ajax. If facebook open graph metatags cannot be altered dynamically and the url of the page is constant regardless of search result, how can i make it so users can share that they rated a certain album.

ie)

<meta property="fb:app_id"      content="118454308341351" /> 
<meta property="og:url"         content="http://www.appurl.com" /> 
<meta property="og:title"       content="Fleetwood Mac's Rumors" /> 
<meta property="og:image"       content="AppImg.jpg" /> 

and update those properties to reflect a given search result.

like image 662
AesopWaits Avatar asked Apr 17 '13 20:04

AesopWaits


2 Answers

The way I handle this is to create a dynamic page which I use as my open graph object, which is simply populated from the url parameters and redirects back to my SPA using the meta redirect.

<meta http-equiv="refresh" content="0;URL=http://YOUR_WEBSITE_WITH_DYNAMIC_CONTENT">

like image 170
Joe T Avatar answered Nov 02 '22 19:11

Joe T


Thanks to this tutorial I found a solution: https://speakerdeck.com/sienatime/facebook-sharing-for-single-page-apps?slide=15

I send only meta tags if the user-agent of the http request includes "facebookexternalhit".

Here is some code for a backend with node and express:

app.get('/', (req,res) => {
  if(req.header('user-agent').includes('facebookexternalhit'){
    res.send(`
      <meta property="og:title" content="The Slits' Cut" />
    `);
  } else {
    res.sendFile(index.html);
  }  
})

You could also write your own middleware for that.

like image 35
dyedwiper Avatar answered Nov 02 '22 18:11

dyedwiper