Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set dynamic Meta Tags and Open Graph tags using jQuery

I'm trying to add dynamic tags using jQuery but it seems not to work. I load my script directly after loading the page.

This is my HTML

<!DOCTYPE html>
<html lang="en">
  <head>
    <script type="text/javascript" src="script.js"></script>
  </head>
  <body>
  </body>
</html>

This is how I add the tags on jQuery.

$(function() {
      $('head').append('<meta property="og:type" content="profile"/>'); 
      $('head').append('<meta property="og:url" content=""/>');
      $('head').append("<meta property='og:title' content="+text+"'/>");
      $('head').append("<meta property='og:image' content="+imageUrl+"'/>");
  });

Why I'm doing this? After the user is visiting the page example.com/?link=HDI635 I would like to present a small overview of the content. So I make a API call using jQuery after that I would like to add the values from the API response to the Open Graph tags.

like image 371
BilalReffas Avatar asked May 29 '17 11:05

BilalReffas


1 Answers

If the purpose of your tags is for generating content previews on sites like Facebook, then using jQuery will probably not work because most web crawlers do not run JavaScript, they simply just download the HTML and read it as it is.

For it to work correctly, you would need to generate the tags on server side.

You can debug your tags using Facebook's sharing debugger: https://developers.facebook.com/tools/debug/

like image 162
alan0xd7 Avatar answered Oct 06 '22 01:10

alan0xd7