openaire-library/sharedComponents/SEO/SEO.service.ts

45 lines
1.3 KiB
TypeScript

import { Injectable, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';
// @Injectable({
// providedIn: 'root'
// })
@Injectable()
export class SEOService {
constructor( @Inject(DOCUMENT) private doc) {
}
createLinkForCanonicalURL(addParameters:boolean=true) {
var url = "";
if(this.doc ){
if(addParameters || !this.doc.URL || this.doc.URL.indexOf("?") == -1){
url = this.doc.URL;
}else{
url = this.doc.URL.substring(0,this.doc.URL.indexOf("?"));
}
console.log("createLinkForCanonicalURL");
if (typeof this.doc.getElementById === "function") {
let currentLink: HTMLLinkElement = this.doc.getElementById("relcan");
if(currentLink ){
currentLink.setAttribute('href', url);
console.log("update canonical url:" + url);
return ;
}
}
if (typeof this.doc.createElement === "function") {
let link: HTMLLinkElement = this.doc.createElement('link');
link.setAttribute('id', 'relcan');
link.setAttribute('rel', 'canonical');
this.doc.head.appendChild(link);
console.log("create new canonical url:" + url);
link.setAttribute('href', url);
}
}
}
}