【问题标题】:Dynamic og:image angular2动态 og:image angular2
【发布时间】:2017-01-04 01:44:53
【问题描述】:

我们想在社交网络上分享一个指向 Angular 2 的 url。例如 Facebook 和 Skype。

在我们的网站上,根据我们设置的实际 URL 参数和查询字符串,在这个 url 上会显示一张动态图片。

例如,转到http://oursite.com/#/show/5448sd84f8d4sf8 将显示/images/5448sd84f8d4sf8.png

通过共享链接,Facebook 和 Skype 似乎都使用 Open Graph 元 og:image 来显示网站的缩略图或快照:

<meta name="og:image" content="http://example.com/image.png">

有没有办法根据 url 设置动态 og:image,如下所述:链接我们的 url 会显示

<meta name="og:image" content="http://oursite.com/images/5448sd84f8d4sf8.png">

然后如何确保例如 Facebook 和 Skype 实际解析动态图像?

【问题讨论】:

标签: angular facebook-opengraph


【解决方案1】:

我也遇到了同样的问题。 Angular 2 浏览器应用程序在客户端运行。为了解决这个问题,当请求来自客户端时,我们需要处理这个表单服务器端。 (带有 og 元标记的简单更新响应)

有几种选择:

  • 选择 Angular Universal:有点困难的方法

  • 通过 URL 重写(Web 服务器)简单处理:这是我使用的

这是我用于 url 重写的 web 配置:我从查询参数 (..og=[filename]) 中获取了动态 og 图像名称

  <rewrite>  
	<outboundRules rewriteBeforeCache="true">
	<rule name="Add tracking script" preCondition="" patternSyntax="ECMAScript">
   <match filterByTags="None" pattern="ogimagepath" />
    <conditions>
    <add input="{QUERY_STRING}" pattern="[^]*og=([0-9]+)" />
  </conditions>
   <action type="Rewrite" value="{C:1}" />
  </rule>
</outboundRules>
</rewrite>

【讨论】:

    【解决方案2】:

    您可以使用 Angular 的Meta 服务来修改元标记:

    import { Title, Meta } from '@angular/platform-browser';
    
    export class MyClass {
      constructor(
        private metaService: Meta
      ) {
        // Build and change the og:image meta
        const baseUrl = window.location.protocol + '//' + window.location.hostname;
        const imageUrl = baseUrl + '/path/to/image.png';
    
        this.metaService.addTag( { property: 'og:image', content: imageUrl } );
        // or it it already exists, use this 'updateTag'
        // this.metaService.updateTag( { property: 'og:image', content: imageUrl } );
      }
    }
    

    【讨论】:

    • 问题是,在加载 javascript 之前,html 页面上的原始 og:image 将保持不变,因此 Facebook、Skype 或任何爬虫都不会看到它。
    【解决方案3】:

    你可以使用ng2-metadata,很容易实现。

    https://www.npmjs.com/package/ng2-metadata

    【讨论】:

    • 链接不是答案。您应该添加一些使用示例。
    • 目前 ng2-metadata 不能与谷歌以外的爬虫结合使用。
    • 作为附录。这是仅提及 google 正在解析 js 的链接。 github.com/fulls1z3/ng2-metadata/issues/4
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-24
    • 2017-11-17
    • 2016-08-21
    • 2017-02-06
    • 2017-09-01
    • 1970-01-01
    相关资源
    最近更新 更多