You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Support adding rel=canonical link tags using an included service #15776
[ ] bug report => search github for a similar issue or PR before submitting
[ X ] feature request
[ ] support request => Please do not submit support request here, instead see https://github.com/angular/angular/blob/master/CONTRIBUTING.md#question
Current behavior
MetaService, or any other service, doesn't support setting/adding <link rel="canonical" href="..."> tags.
Expected behavior
Like the HEAD services that allow addition of <title> and <meta> tags, adding <link> tags should be supported as well.
Minimal reproduction of the problem with instructions
N/A
What is the motivation / use case for changing the behavior?
In the universal/server context, it is often useful to be able to set a rel="canonical" link element to prevent search engines from duplicating results. See Canonical Link Element for more details.
Please tell us about your environment:
Angular version: 2.0.X
4.0.1
Browser:
All
Language: [all | TypeScript X.X | ES6/7 | ES5]
All
Eventually there will be some DocumentService part of Core that will handle both Meta/Link elements, for now you can use this one below, which should get you going! (This works with Universal/platform-server as well of course)
Modeled after the Meta service, can use it the same way.
/* * -- LinkService -- [Temporary] * @MarkPieszak * * Similar to Meta service but made to handle <link> creation for SEO purposes * -- NOTE: Soon there will be an overall DocumentService within Angular that handles Meta/Link everything */import{Injectable,Optional,RendererFactory2,ViewEncapsulation,Inject}from'@angular/core';import{DOCUMENT}from'@angular/platform-browser';
@Injectable()exportclassLinkService{constructor(privaterendererFactory: RendererFactory2,
@Inject(DOCUMENT)privatedocument){}/** * Inject the State into the bottom of the <head> */addTag(tag: LinkDefinition,forceCreation?: boolean){try{constrenderer=this.rendererFactory.createRenderer(this.document,{id: '-1',encapsulation: ViewEncapsulation.None,styles: [],data: {}});constlink=renderer.createElement('link');consthead=this.document.head;constselector=this._parseSelector(tag);if(head===null){thrownewError('<head> not found within DOCUMENT.');}Object.keys(tag).forEach((prop: string)=>{returnrenderer.setAttribute(link,prop,tag[prop]);});// [TODO]: get them to update the existing one (if it exists) ?renderer.appendChild(head,link);}catch(e){console.error('Error within linkService : ',e);}}private_parseSelector(tag: LinkDefinition): string{// Possibly re-work thisconstattr: string=tag.rel ? 'rel' : 'hreflang';return`${attr}="${tag[attr]}"`;}}exportdeclaretypeLinkDefinition={charset?: string;crossorigin?: string;href?: string;hreflang?: string;media?: string;rel?: string;rev?: string;sizes?: string;target?: string;type?: string;}&{[prop: string]: string;};
Reacted by Justin Appler, Oleksandr Tytskyi, Vijay Goel, Cory Rylan , salcam, Ivan Camilo Vásquez, Jonas G de Medeiros, Josh S., Marian Stoica, Heriyanto Binduni and 22 more
Reacted by Rasulbeeek, Rasool Jahani, Maryna, dryRay, Joe, Arseniy Shelestyuk and Sofiène Djebali
Reacted by Justin Appler, Heriyanto Binduni, alua1612, Pablo Reinoso, Rex, Rasool Jahani, Maryna, dryRay, Yunfei Li, Arseniy Shelestyuk and 2 more
Thanks @MarkPieszak ! The plan is to fold all this into a unified DocumentService that you can use to manipulate different tags in head. I expect this to land in 4.1 time frame.
@MarkPieszak Thanks for this! I had some trouble with the addTag function creating multiple rel canonicals as navigation occurred. I created a removeCanonicalLink function to pair with it (I just run it ahead of calling the addTag({ rel: 'canonical', href: 'http://blogs.example.com/blah/nice' }) in my function (for me it's in ngOnChanges).
Do you see any issues with this approach I should be aware of/ testing for?
removeCanonicalLink() {
try {
const renderer = this.rendererFactory.createRenderer(this.document, {
id: '-1',
encapsulation: ViewEncapsulation.None,
styles: [],
data: {}
});
const canonical = document.querySelector("link[rel='canonical']")
const head = this.document.head;
if (head === null) {
throw new Error('<head> not found within DOCUMENT.');
}
if (!!canonical) {
renderer.removeChild(head, canonical);
}
} catch (e) {
console.error('Error within linkService : ', e);
}
}
@MarkPieszak do you mean for a universal site? Whats a better workaround? I haven't deployed Universal yet, so it seems to be working in the browser for a normal static site.
Hi to all,
thanks @MarkPieszak for script code. I added a workaround that work (apparently) in prod. Not use document directly. but read head children and if there is selector, then remove before add.
We started out with a DocumentService but realized we don't want to special case every single meta tag like this. So we went down the route of just provding a good subset of DOM API on the server using domino - 2f2d5f3
So the answer in 5.0 is just use the DOM API.
Reacted by pgnonick, Ivan Camilo Vásquez, Adam Wamai Egesa and Rafa SA
@vikerman any pointers regarding the DOM API? Looking through the docs, searching the api for dom doesn't say anything (even tried on 5.1.0-beta.1).
Is this DOM API present in 5+ ? If yes, any pointers on how to use it would be appreciated!
Thanks!
P.S. I've tried @salcam 's example above on a small app with a few material components.
It takes about 1.2 seconds until I see the html rendered server-side, as opposed to ~200ms when not traversing all children of the document's head in order to remove all styles/links[rel="stylesheet"].
My use case is AMP: need to remove all style/link[rel="stylesheet"] + all script tags and only insert amp specific scripts (sidebar etc.) and one <style> tag with what's needed for the current page (still haven't figured out how to do that, barely struggling to remove style/link tags for now).
And I hope that this DOM Api would come in handy for other things as well, like adding amp on the <html> tag.
Agree that rel=canonical example would be super helpful (and a strange omission for a product supported by google).
Rob wormald highlighted early progress toward AMP last year at Ng-conf. Between universal, meta/ canonical, and AMP it would seem google webmaster guidance for content ranking would be something that would be a common enough use case that development path and documentation would be super helpful.
Reacted by Douglas Henri, Raphael, Rafa SA and Mykhailo Kovetskyi
@vikerman, as @MrCroft I didn't find any docs or details about the new server side rendering life saver Domino. All the news about angular 5 highlight the fact that Dom manipulations will be available out of the box. However even after our recent migration to angular 5, I still have issues like document is not defined. So I end up using the same workaround as before.
Am I missing something ? Any docs or info we can turn to to get more usecase ?
In the meantime thanks @MarkPieszak for the example 👍
So now that there is DOCUMENT (think the Document you already have in your browser / same API) from @angular/common, you can simply query the DOM and add/edit/remove any link items you'd want. You don't even need the Renderer anymore for it. 👍
Another approach to handle link, meta and anything that should be placed in head, without verbose services to cover all options, is a simple moveToHead directive like this:
This way you can use data bindings and all other stuff, and treat that meta, link, etc., just like any other element in your template.
Reacted by Vishal Singh, Vijay Goel, jmolnarbimobject, Stephan Rauh, Dilantha, Reza Kajbaf, Eman Jasarevic, Konstantin Köppe, Karl Clement, Adam and 2 more
@m98 seems like a lot of people are still having issues with this. As mentioned by @vikerman above already, just use the DOCUMENT / DOM API wrapper, which has been moved to @angular/common in 5.0 and thus now works with SSR. There is no need to mess with the renderer anymore and using DOCUMENT is recommended.
It mimics the regular browser document api.
Here is a boiled down example:
import {DOCUMENT} from "@angular/common";
...
constructor(@Inject(DOCUMENT) private document: Document) {...}
...
ngOnInit() {
...
// WARNING ngOnInit is actually NOT the right place to do this, as it won't be called on back button presses etc.
// for more see below
const link = <HTMLLinkElement> this.document.head.querySelector("link[rel='canonical']")
|| this.document.head.appendChild(this.document.createElement("link"));
link.rel = "canonical";
link.href = "https://www.example.com/url";
}
NOTE about ngOnInit: depending on your RouteReuseStrategy this won't be always called and therefore shouldn't be used to update the canonical links, there seem to be no appropriate lifecycle hooks for these cases yet. Here are some alternatives:
(recommended) listen for url changes and change the canonicals accordingly
(overkill if this is your only issue, my solution) use a customized router-outlet, which adds additional lifecycle hooks onAttach and onDetach
I needed a service that adds a canonical tag on every page. However the ability to change/remove the canonical tag in certain components was also required. I combined all the examples into one single LinkService with a option to start a route listener.
If you see something that can be improved please tell me.
import{Injectable,OnDestroy,Inject}from'@angular/core';import{DOCUMENT}from'@angular/common';import{Router,NavigationEnd}from'@angular/router';import{Subscription}from'rxjs';import{filter}from'rxjs/operators';import{LinkDefinition}from'./link-definition';
@Injectable({providedIn: 'root'})exportclassLinkServiceimplementsOnDestroy{privaterouteListener: Subscription;constructor(
@Inject(DOCUMENT)privatereadonlydocument: Document,privatereadonlyrouter: Router,){}/** * Start listening on NavigationEnd router events */publicstartRouteListener(): void{this.routeListener=this.router.events.pipe(filter(event=>eventinstanceofNavigationEnd)).subscribe(()=>{leturl='';consturlTree=this.router.parseUrl(this.router.url);if(urlTree.root.hasChildren()){constsegments=urlTree.root.children['primary'].segments;if(segments&&segments.length>0){url=segments.map(segment=>segment.path).join('/');}}this.updateTag({rel: 'canonical',href: `/${url}`});});}/** * Create or update a link tag * @param {LinkDefinition} tag */publicupdateTag(tag: LinkDefinition): void{constselector=this._parseSelector(tag);constlinkElement=<HTMLLinkElement>this.document.head.querySelector(selector)||this.document.head.appendChild(this.document.createElement('link'));if(linkElement){Object.keys(tag).forEach((prop: string)=>{linkElement[prop]=tag[prop];});}}/** * Remove a link tag from DOM * @param tag */publicremoveTag(tag: LinkDefinition): void{constselector=this._parseSelector(tag);constlinkElement=<HTMLLinkElement>this.document.head.querySelector(selector);if(linkElement){this.document.head.removeChild(linkElement);}}/** * Get link tag * @param tag * @return {HTMLLinkElement} */publicgetTag(tag: LinkDefinition): HTMLLinkElement{constselector=this._parseSelector(tag);returnthis.document.head.querySelector(selector);}/** * Get all link tags * @return {NodeListOf<HTMLLinkElement>} */publicgetTags(): NodeListOf<HTMLLinkElement>{returnthis.document.head.querySelectorAll('link');}/** * Parse tag to create a selector * @param tag * @return {string} selector to use in querySelector */private_parseSelector(tag: LinkDefinition): string{constattr: string=tag.rel ? 'rel' : 'hreflang';return`link[${attr}="${tag[attr]}"]`;}/** * Destroy route listener when service is destroyed */ngOnDestroy(): void{this.routeListener.unsubscribe();}}
@MarkPieszak I followed your guide and something is broken. When I check the header through chrome browser developer console, it looks good but when I check the header using View page source, the href of link went wrong. The reason was server didn't recognize window.location in the Angular universal, is there any way to know the hostname on the server side in the Angular universal?
@m98 seems like a lot of people are still having issues with this. As mentioned by @vikerman above already, just use the DOCUMENT / DOM API wrapper, which has been moved to @angular/common in 5.0 and thus now works with SSR. There is no need to mess with the renderer anymore and using DOCUMENT is recommended.
It mimics the regular browser document api.
@suau It looks like DOCUMENT has been deprecated in Angular 7 - doing a quick google I can't seem to find what one would use instead? Do you or anyone have any ideas?
import {DOCUMENT} from '@angular/common';
import {Inject, Injectable, inject} from '@angular/core';
import {
ɵDomAdapter as DomAdapter,
ɵgetDOM as getDOM
} from '@angular/platform-browser';
removeTagElement(meta: HTMLLinkElement): void {
if (meta) {
this._dom.remove(meta);
}
}
private _getOrCreateElement(meta: LinkDefinition, forceCreation: boolean = false):
HTMLLinkElement {
if (!forceCreation) {
const selector: string = this._parseSelector(meta);
const elem: HTMLLinkElement = this.getTag(selector) !;
// It's allowed to have multiple elements with the same name so it's not enough to
// just check that element with the same name already present on the page. We also need to
// check if element has tag attributes
if (elem && this._containsAttributes(meta, elem)) return elem;
}
const element: HTMLLinkElement = this._dom.createElement('link') as HTMLLinkElement;
this._setMetaElementAttributes(meta, element);
const head = this._dom.getElementsByTagName(this._doc, 'head')[0];
this._dom.appendChild(head, element);
return element;
}
Activity
MarkPieszak commentedon Apr 5, 2017
Eventually there will be some DocumentService part of Core that will handle both Meta/Link elements, for now you can use this one below, which should get you going! (This works with Universal/platform-server as well of course)
Modeled after the Meta service, can use it the same way.
LinkService:
vikerman commentedon Apr 5, 2017
Thanks @MarkPieszak ! The plan is to fold all this into a unified DocumentService that you can use to manipulate different tags in head. I expect this to land in 4.1 time frame.
justinappler commentedon Apr 5, 2017
@MarkPieszak Exactly the example I was looking for in lieu of built-in support. Thanks!
goelinsights commentedon Apr 8, 2017
@MarkPieszak Thanks for this! I had some trouble with the addTag function creating multiple rel canonicals as navigation occurred. I created a removeCanonicalLink function to pair with it (I just run it ahead of calling the addTag({ rel: 'canonical', href: 'http://blogs.example.com/blah/nice' }) in my function (for me it's in ngOnChanges).
Do you see any issues with this approach I should be aware of/ testing for?
MarkPieszak commentedon Apr 12, 2017
@goelinsights Yes that won't work since you're using
documentwhich doesn't exist on the servergoelinsights commentedon Apr 12, 2017
@MarkPieszak do you mean for a universal site? Whats a better workaround? I haven't deployed Universal yet, so it seems to be working in the browser for a normal static site.
samvloeberghs commentedon May 9, 2017
the same thing should be able for the
<html>tag putting the lang attributesalcam commentedon May 30, 2017
Hi to all,
thanks @MarkPieszak for script code. I added a workaround that work (apparently) in prod. Not use document directly. but read head children and if there is selector, then remove before add.
Then replace your [TODO] with:
pgnonick commentedon Jun 19, 2017
Hi,
exists a roadmap/plan for this DocumentService?
Is it a topic for 4.3?
vikerman commentedon Sep 6, 2017
We started out with a DocumentService but realized we don't want to special case every single meta tag like this. So we went down the route of just provding a good subset of DOM API on the server using domino - 2f2d5f3
So the answer in 5.0 is just use the DOM API.
NgxDev commentedon Nov 21, 2017
@vikerman any pointers regarding the DOM API? Looking through the docs, searching the api for dom doesn't say anything (even tried on
5.1.0-beta.1).Is this DOM API present in 5+ ? If yes, any pointers on how to use it would be appreciated!
Thanks!
P.S. I've tried @salcam 's example above on a small app with a few material components.
It takes about 1.2 seconds until I see the html rendered server-side, as opposed to ~200ms when not traversing all children of the document's head in order to remove all styles/links[rel="stylesheet"].
My use case is AMP: need to remove all style/link[rel="stylesheet"] + all script tags and only insert amp specific scripts (sidebar etc.) and one
<style>tag with what's needed for the current page (still haven't figured out how to do that, barely struggling to remove style/link tags for now).And I hope that this DOM Api would come in handy for other things as well, like adding
ampon the<html>tag.goelinsights commentedon Nov 21, 2017
Agree that rel=canonical example would be super helpful (and a strange omission for a product supported by google).
Rob wormald highlighted early progress toward AMP last year at Ng-conf. Between universal, meta/ canonical, and AMP it would seem google webmaster guidance for content ranking would be something that would be a common enough use case that development path and documentation would be super helpful.
julienR2 commentedon Nov 27, 2017
@vikerman, as @MrCroft I didn't find any docs or details about the new server side rendering life saver Domino. All the news about angular 5 highlight the fact that Dom manipulations will be available out of the box. However even after our recent migration to angular 5, I still have issues like
document is not defined. So I end up using the same workaround as before.Am I missing something ? Any docs or info we can turn to to get more usecase ?
In the meantime thanks @MarkPieszak for the example 👍
4 remaining items
rafa-suagu commentedon May 9, 2018
Any notice if it's included on release 6 ?
MarkPieszak commentedon May 10, 2018
So now that there is
DOCUMENT(think the Document you already have in your browser / same API) from@angular/common, you can simply query the DOM and add/edit/remove any link items you'd want. You don't even need the Renderer anymore for it. 👍@rafa-as
alirezamirian commentedon May 16, 2018
Another approach to handle
link,metaand anything that should be placed in head, without verbose services to cover all options, is a simplemoveToHeaddirective like this:Usage:
This way you can use data bindings and all other stuff, and treat that
meta,link, etc., just like any other element in your template.m98 commentedon Jun 9, 2018
@MarkPieszak would you please provide an example using DOCUMENT?
anymos commentedon Jun 12, 2018
Trying to find any side effect regarding @alirezamirian solution, and I can not find any.
Thank you
suau commentedon Sep 17, 2018
@m98 seems like a lot of people are still having issues with this. As mentioned by @vikerman above already, just use the DOCUMENT / DOM API wrapper, which has been moved to
@angular/commonin 5.0 and thus now works with SSR. There is no need to mess with the renderer anymore and using DOCUMENT is recommended.It mimics the regular browser document api.
Here is a boiled down example:
NOTE about
ngOnInit: depending on yourRouteReuseStrategythis won't be always called and therefore shouldn't be used to update the canonical links, there seem to be no appropriate lifecycle hooks for these cases yet. Here are some alternatives:onAttachandonDetachalexisbmills commentedon Oct 3, 2018
@MrCroft did you manage to get a final solution for AMP?
RFreij commentedon Nov 8, 2018
I needed a service that adds a canonical tag on every page. However the ability to change/remove the canonical tag in certain components was also required. I combined all the examples into one single LinkService with a option to start a route listener.
Thank you @suau @MarkPieszak @DominicBoettger for your examples
If you see something that can be improved please tell me.
Starting routerListener
Big-Silver commentedon Mar 1, 2019
@MarkPieszak I followed your guide and something is broken. When I check the header through chrome browser developer console, it looks good but when I check the header using View page source, the href of link went wrong. The reason was server didn't recognize window.location in the Angular universal, is there any way to know the hostname on the server side in the Angular universal?
Big-Silver commentedon Mar 1, 2019
I just found the way how to get the hostname on server side in the Angular universal.
refer this article
floodedcodeboy commentedon Mar 7, 2019
@suau It looks like
DOCUMENThas been deprecated in Angular 7 - doing a quick google I can't seem to find what one would use instead? Do you or anyone have any ideas?RFreij commentedon Mar 7, 2019
@floodedcodeboy The @angular/platform-browser DOCUMENT is deprecated, you should use the @angular/common DOCUMENT
https://angular.io/api/platform-browser/DOCUMENT << Deprecated
https://angular.io/api/common/DOCUMENT << Correct one
msp-codes commentedon May 22, 2019
Angular Version: 7
AoT: Yes
import {DOCUMENT} from '@angular/common';
import {Inject, Injectable, inject} from '@angular/core';
import {
ɵDomAdapter as DomAdapter,
ɵgetDOM as getDOM
} from '@angular/platform-browser';
/**
*/
export type LinkDefinition = {
charset?: string;
crossorigin?: string;
href?: string;
hreflang?: string;
media?: string;
rel?: string;
rev?: string;
sizes?: string;
target?: string;
type?: string;
} & {
[prop: string]: string;
};
/**
*/
export function createLink() {
return new Link(inject(DOCUMENT));
}
/**
*/
@Injectable({providedIn: 'root', useFactory: createLink, deps: []})
export class Link {
private _dom: DomAdapter;
constructor(@Inject(DOCUMENT) private _doc: any) { this._dom = getDOM(); }
addTag(tag: LinkDefinition, forceCreation: boolean = false): HTMLLinkElement|null {
if (!tag) return null;
return this._getOrCreateElement(tag, forceCreation);
}
addTags(tags: LinkDefinition[], forceCreation: boolean = false): HTMLLinkElement[] {
if (!tags) return [];
return tags.reduce((result: HTMLLinkElement[], tag: LinkDefinition) => {
if (tag) {
result.push(this._getOrCreateElement(tag, forceCreation));
}
return result;
}, []);
}
getTag(attrSelector: string): HTMLLinkElement|null {
if (!attrSelector) return null;
return this._dom.querySelector(this._doc,
link[${attrSelector}]) || null;}
getTags(attrSelector: string): HTMLLinkElement[] {
if (!attrSelector) return [];
const list /NodeList/ = this._dom.querySelectorAll(this._doc,
link[${attrSelector}]);return list ? [].slice.call(list) : [];
}
updateTag(tag: LinkDefinition, selector?: string): HTMLLinkElement|null {
if (!tag) return null;
selector = selector || this._parseSelector(tag);
const meta: HTMLLinkElement = this.getTag(selector) !;
if (meta) {
return this._setMetaElementAttributes(tag, meta);
}
return this._getOrCreateElement(tag, true);
}
removeTag(attrSelector: string): void { this.removeTagElement(this.getTag(attrSelector) !); }
removeTagElement(meta: HTMLLinkElement): void {
if (meta) {
this._dom.remove(meta);
}
}
private _getOrCreateElement(meta: LinkDefinition, forceCreation: boolean = false):
HTMLLinkElement {
if (!forceCreation) {
const selector: string = this._parseSelector(meta);
const elem: HTMLLinkElement = this.getTag(selector) !;
// It's allowed to have multiple elements with the same name so it's not enough to
// just check that element with the same name already present on the page. We also need to
// check if element has tag attributes
if (elem && this._containsAttributes(meta, elem)) return elem;
}
const element: HTMLLinkElement = this._dom.createElement('link') as HTMLLinkElement;
this._setMetaElementAttributes(meta, element);
const head = this._dom.getElementsByTagName(this._doc, 'head')[0];
this._dom.appendChild(head, element);
return element;
}
private _setMetaElementAttributes(tag: LinkDefinition, el: HTMLLinkElement): HTMLLinkElement {
Object.keys(tag).forEach((prop: string) => this._dom.setAttribute(el, prop, tag[prop]));
return el;
}
private _parseSelector(tag: LinkDefinition): string {
const attr: string = tag.name ? 'name' : 'property';
return
${attr}="${tag[attr]}";}
private _containsAttributes(tag: LinkDefinition, elem: HTMLLinkElement): boolean {
return Object.keys(tag).every((key: string) => this._dom.getAttribute(elem, key) === tag[key]);
}
}
Usage:
constructor(private linkService: Link) {}
this.linkService.updateTag({rel: 'canonical', href: data.rel});
angular-automatic-lock-bot commentedon Sep 15, 2019
This issue has been automatically locked due to inactivity.
Please file a new issue if you are encountering a similar or related problem.
Read more about our automatic conversation locking policy.
This action has been performed automatically by a bot.