简体   繁体   中英

How to update the meta tag in ionic dynamically? So that it can work in facebook social sharing

In the ionic project, there is only one head section where we write all the meta tag that is in the index.html page. For example, to make the Facebook sharing work perfectly we need this meta tag given bleow:

<meta property="og:title" content="Title">
<meta property="og:description" content="description">
<meta property="og:image" content="Image Url you want to show">
<meta property="og:url" content="http://yourUrl.com">

So how can we update this meta tag from other pages? For example, if we go to a news detail page the meta tag of that page will be changed accordingly. So how can I achieve this in my Ionic4 with angular project?

I believe that you can do it in a way similar to this:

var link = document.createElement('meta');
  link.setAttribute('property', 'og:url');
  link.content = document.location;
  document.getElementsByTagName('head')[0].appendChild(link);

In my existing Ionic 4 project, I want to use Angular Universal but I got into so many errors. So I created a new project using Ionic 5 . And move all my previous work to the new Ionic 5 . I follow these steps to add Angular Universal to my project. At first, create an app and update it to the latest version of Angular using these commands.

ionic start myApp blank --type angular
cd myApp
ng update @angular/core @angular/cli
npm install @angular/animations

Then add Express engine for Angular Universal using this command.

ng add @nguniversal/express-engine

Then you need to install the @ionic/angular-server module using this command.

npm install @ionic/angular-server@dev

For testing in the localhost, your server-side rendering is working correctly you need to use this command.

npm run dev:ssr

For more detailed information on how to setup Angular Universal for server-side-rendering you can see the ionic blog link SSR with Angular Universal And Ionic .

After setting, angular universal you need to add title , add , or update meta tag . You can follow my sample code given below:

import { Component, OnInit} from '@angular/core';
import { Title, Meta } from '@angular/platform-browser';
@Component({
  selector: 'app-sample',
  templateUrl: './sample.page.html',
  styleUrls: ['./sample.page.scss'],
})
export class SamplePage implements OnInit {
  constructor(private titleService: Title, private meta: Meta) { }

  ngOnInit() {
    this.titleService.setTitle("Your Title");
    this.meta.updateTag({ property: 'og:url', content:'http://yoururl.com'});
    this.meta.updateTag({ property: 'og:title', content:"Your Title" });
    this.meta.updateTag({ property: 'og:image', content: "your image link"});
    this.meta.updateTag({ property: 'og:description', content:  "description"});
  }

}

Now your social share will work perfectly. Because when it crawls not it will get the metatag with data. You need to update the meta tag based on the social share you want to add.

I got this working last week using Renderton as described in this post by Jeff Delaney. You'll still need to setup server side rendering (SSR) through this artcle . Lastly, make sure none of your code references the window, which will break SSR and Rendetron.

One can use ionic's pre build hooks to modify the index.html after building. Add hooks in your ionic.config.json file

{
  "name": "xxxx",
  "integrations": {
    "capacitor": {}
  },
  "type": "vue",
  "id": "xxxxx",
  "hooks": {
     "build:after": "./deploy/after-build.js"
   }
}

and then in your project folder (top level) create folder deploy with file after-build.js with following content:

var fs = require('fs')
module.exports = (ctx) => {
   const index = `${ctx.project.dir}/dist/index.html`;
   fs.readFile(index , 'utf8', (err, html) => {
      const meta = '<meta name="NEW-META" />';
      html = html.replace(/<meta name="OLD-META".*?">/, meta);
      fs.writeFile(index, html, 'utf8', err => err && console.log( err ));
   });
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM