簡體   English   中英

Angular 2 - 在Facebook上共享頁面URL,標題和描述

[英]Angular 2 - Share page URL, Title, and Description on Facebook

我的最終目標很簡單:

  1. 用戶單擊UI上的某個按鈕。
  2. 通過所謂的打字稿功能click打開在Facebook上的用戶一個新的共享選項卡。
  3. 共享頁面的“標題”和“描述”均由我的網站提供。

我們在鏈接的頁面上有一個包含元標記的帖子,fb知道包括作為標題/描述( 如何自定義Facebook的sharer.php )。 問題是我使用的是Angular 2,所以我必須以某種方式在facebook看到它之前為頁面動態添加元標記。

我很難想象它是如何工作的,因為我假設FB服務器將點擊我的NG2應用程序並搜索元標記(因此在瀏覽器中打開共享鏈接的元數據是沒有意義的,因為FB API會有所不同html的實例)。

tl; dr:如何從NG2應用程序打開fb url共享對話框並提供標題/說明?

注意:“在fb上分享”頁面可以像這樣打開: window.open('http://www.facebook.com/sharer/sharer.php?u=www.google.com'); 這有效,但沒有參數。


可選附錄(動態添加元標記的示例代碼,有效,但無效):

var titleMeta = document.createElement('meta');
var descMeta = document.createElement('meta');

titleMeta.setAttribute('property', 'og:title');
titleMeta.setAttribute('content', 'The Rock');

descMeta.setAttribute('property', 'og:description');
descMeta.setAttribute('content', 'Foo Description');

document.getElementsByTagName('head')[0].appendChild(titleMeta);
document.getElementsByTagName('head')[0].appendChild(descMeta);

附錄2:共享者曾經允許您在網址中輸入標題和說明,但根據https://developers.facebook.com/x/bugs/357750474364812/不再是這種情況。 看起來它必須從元標記中提取。

你應該看看@ Share Buttons可能有所幫助

npm install --save ngx-sharebuttons

的AppModule

import {ShareButtonsModule} from 'ngx-sharebuttons';
@NgModule({
  imports: [
   //...
   HttpModule, 
   ShareButtonsModule.forRoot(),
  // ...
  ]
})

模板

<share-buttons></share-buttons>

問題是Facebook爬蟲只會看到服務器端渲染的HTML,Facebook不會執行客戶端javascript。 這就是您更新Meta標簽的代碼根本無濟於事的原因。

選項 -

1)查看服務器端渲染的選項,如phantom.js

2)如果整個應用程序中只有一個標題和描述,那么將meta標簽直接放到root index.html(我們指定Base Href並加載app,供應商javascript包)。 正如@Stuart所評論的那樣

請嘗試以下代碼 -

var windowObj = window.open();
windowObj.document.head.innerHTML='<meta property="og:title" content="The Rock"/><meta property="og:type" content="movie"/><meta property="og:url" content="http://www.imdb.com/title/tt0117500/"/><meta property="og:image" content="http://ia.media-imdb.com/rock.jpg"/><meta property="og:site_name" content="IMDb"/><meta property="fb:admins" content="USER_ID"/><meta property="og:description"      content="A group of U.S. Marines, under command of               a renegade general, take over Alcatraz and               threaten San Francisco Bay with biological               weapons."/>'

如果您使用客戶端渲染,Facebook爬蟲無法在頁面上執行js,因此它獲取從服務器返回的HTML並搜索OG元標記。

  • 如果它是動態呈現的內容,則需要在服務器端將這些元標記添加到您要返回的index.html (我不確定你在后端使用什么來提供/生成索引,但你可以使用例如handlebars.js
  • 否則只需將這些元標記直接放入index.html

  • 然后你可以在這里測試→ https://developers.facebook.com/tools/debug/sharing

如果這可以幫助您修改標題說明? 角-2- SEO

如果您使用的是Angular 2,則無法使用Angular 2進行HTML渲染之前的動態元標記進行客戶端渲染。 使用Angular 2,只能在服務器端渲染。

它在Angular 4中得到解決。您可以在此鏈接上看到 -

點擊這里

暫無
暫無

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

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