Set dynamic Meta Tags and Open Graph tags using jQuery

那年仲夏 提交于 2019-12-10 10:06:50

问题


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.


回答1:


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/




回答2:


As Alan stated, most web crawlers do not run JavaScript, they simply just download the HTML and read it as it is. As of today, FB crawler doesn't.

A good solution for this is having a server (nginx is enough) to detect the User Agent of the visitor and if it is Facebook's UA (https://developers.facebook.com/docs/sharing/webmasters/crawler/) serve a simple HTML with the OG tags. Else, serve the web-app.



来源:https://stackoverflow.com/questions/44241258/set-dynamic-meta-tags-and-open-graph-tags-using-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!