簡體   English   中英

如何在 LInkedin / FB 上共享單頁應用程序子頁面上動態生成的標題的標題和元數據?

[英]How do i share title and metadata on LInkedin / FB of dynamically generated titles on sub-pages of Single page application?

我在 Angular 中設置了一個單頁應用程序,目前根據路由動態設置頁面標題和 OG/ 元參數。 即,例如每次在應用程序中使用此更改路線時。 titleService 還會更新頁面的頁面標題和元標記:

import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/mergeMap';

import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd, ActivatedRoute } from '@angular/router';
import { Title } from '@angular/platform-browser';

@Component({...})
export class AppComponent implements OnInit {
  constructor(
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private titleService: Title
  ) {}
  ngOnInit() {
    this.router.events
      .filter((event) => event instanceof NavigationEnd)
      .map(() => this.activatedRoute)
      .map((route) => {
        while (route.firstChild) route = route.firstChild;
        return route;
      })
      .filter((route) => route.outlet === 'primary')
      .mergeMap((route) => route.data)
      .subscribe((event) => this.titleService.setTitle(event['title']));
  }
}

現在的問題是,當我在 Linkedin 上共享我的應用程序的一個子頁面時,它不會根據我在我的應用程序中動態生成的參數更新 URL 的標題和 OG 項目,而是顯示在我的應用預路由。

如何分享到 Linkedin / Facebook 以便它根據我頁面上動態更新的標題顯示標題和描述?

使用單頁 web 應用程序更新元數據僅在客戶端更新它。 LinkedIn、Facebook 和其他社交共享網站不會加載和解釋 JavaScript。 他們只需抓取從服務器返回的 HTML 文件並使用其中包含的任何元數據。 因此,在 JavaScript 中實現的自定義路由和相關數據將永遠不會被讀取,而是始終顯示默認值。

雖然有許多可能的解決方案,但所有解決方案都需要大量的工作,並且根據項目的 scope 各有利弊。 您可以查看在服務器上預先構建 HTML 以進行初始頁面加載,或在發送之前在服務器上調整 HTML 文件的元數據。

一個簡單的預渲染方法:

預渲染元數據的一種方法是在您構建代碼后運行一個腳本,該代碼使用調整后的元數據創建單獨的 html 頁面。 (免責聲明:我主要使用 React 而不是很多 Angular,因此示例可能略有偏差,但總體思路在框架之間應該是相同的)

以這個文件為例 -
https://github.com/cid-harvard/growth-lab-app-front-end/blob/master/prerender-metadata.js

在這里,我讀入了構建的index.html文件,通過使用正則表達式來查找和替換一組關鍵字符(放置在 HTML 模板文件中)修改每條路線的元數據,然后將其保存為單獨的 Z4C4AD5FCA2E07A3F74DBBED 文件 C將使用正確的元數據提供服務(但在頁面完全加載時會以相同方式運行 SPA)。

為了便於搜索和替換,HTML 模板包含如下“默認”元數據:

<title>$OG_TITLE</title>
<meta name="description" content="$OG_DESCRIPTION" />

我在構建腳本之后使用簡單的node prerender-metadata.js運行上述腳本

一個簡單的服務器端渲染方法:

使用相同的樣式構建帶有可搜索字符串的 HTML 模板,您還可以在服務器上執行類似的搜索和替換以獲取更多動態內容。 每次有對特定 url 的請求時,您都將在服務器上運行它,而不是在構建步驟之后立即運行腳本。 這是一個在服務器上使用 express 和 Node 的示例:

app.get('/terms-of-use', (req, res) => {
  const filePath = path.resolve(__dirname, '../../client', 'build', 'index.html');
  // read in the index.html file
  fs.readFile(filePath, 'utf8', function(err, data) {
    if (err) {
      return console.error(err);
    }
    // replace the special strings with server generated strings
    data = data.replace(/\$OG_TITLE/g, 'Terms of Use');
    const result  = data.replace(/\$OG_DESCRIPTION/g, "Terms of Use.");
    res.send(result);
  });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM