背景
如果你FaceBook和twitter的分享机制就知道,当你分享数据到他们的网站,会有爬虫机器人一直在读取并解析你的数据(meta里面的),所以怎么让你的meta数据被抓到?
问题
Vue的页面公用一个HTML,所以动态的meta标签就不行了,而且FaceBook官网已经声明,页面动态创建的meta是抓取不成功的 ,所以怎么动态生成数据,并让FaceBook或者Twitter抓到呢,这里给大家提供一种方法,并且实际项目中已经在跑了。
解决方式
独立生成静态页面的方式
具体实现
文章发布的时候,同时生成一个静态html页面
后台使用模板的方式实现
<!DOCTYPE html>
<html>
<head>
<meta property="og:type" content="article" />
<meta property="og:title" content="${title}"/>
<meta property="og:image" content="${imagePath}"/>
<meta property="og:image:width" content="1200" />
<meta property="og:image:height" content="628" />
<meta property="og:image:type" content="image/jpeg" />
<meta property="og:description" content="${summary}"/>
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:title" content="${title}"/>
<meta name="twitter:site" content="website" />
<meta name="twitter:description" content="${summary}"/>
<meta name="twitter:image" content="${imagePath}"/>
</head>
<body>
<script type="text/javascript">
window.location.href="${articleUrl}"
</script></body>
</html>
@SneakyThrows
public void writeHtml(String imagePath, String title, String articleUrl, String summary,String articleId,String localPath){
Template template = configurer.getConfiguration().getTemplate("articleDetail.ftl");
Map<String,Object> model =new HashMap<>();
model.put("articleUrl",articleUrl==null?"":articleUrl);
model.put("title",title==null?"":title);
model.put("imagePath",imagePath==null?"":imagePath);
model.put("summary",summary==null?"":summary);
String text = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
//log.info("text::"+text);
String htmlFilePath = localPath+articleId+".html";
log.info("htmlFilePath::"+htmlFilePath);
FileWriter writer =null;
File file = new File(htmlFilePath);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
if (!file.exists()) {
writer = new
FileWriter(htmlFilePath);
}else{
file.delete();
writer = new
FileWriter(htmlFilePath);
}
writer.write(text);
writer.flush();
writer.close();
}
nginx配置转发路径 服务器存放html页面的路径
location /share/article {
alias /data/share;
}
新的问题
1、个别图片不能正常显示
解决:Linedin对图片大小做了一些规定
参考网站
Make your website shareable on LinkedIn | LinkedIn Help
Post Inspector
2、分享链接有缓存
解决:在url后 添加 时间戳参数
参考文章
vue.js - facebook twitter 领英 在web中 分享 - 个人文章 - SegmentFault 思否
The Simplest (and Most Performant) Way to Offer Sharing Links for Social Media | CSS-Tricks - CSS-Tricks