Project

General

Profile

1
/**
2
 * @license
3
 * Copyright Google Inc. All Rights Reserved.
4
 *
5
 * Use of this source code is governed by an MIT-style license that can be
6
 * found in the LICENSE file at https://angular.io/license
7
 */
8

    
9
import {Injectable, Inject} from '@angular/core';
10
// es6-modules are used here
11
import {DomAdapter, getDOM} from '@angular/platform-browser/src/dom/dom_adapter';
12
import {DOCUMENT} from '@angular/platform-browser';
13
/**
14
 * Represent meta element.
15
 *
16
 * ### Example
17
 *
18
 * ```ts
19
 * { name: 'application-name', content: 'Name of my application' },
20
 * { name: 'description', content: 'A description of the page', id: 'desc' }
21
 * // ...
22
 * // Twitter
23
 * { name: 'twitter:title', content: 'Content Title' }
24
 * // ...
25
 * // Google+
26
 * { itemprop: 'name', content: 'Content Title' },
27
 * { itemprop: 'description', content: 'Content Title' }
28
 * // ...
29
 * // Facebook / Open Graph
30
 * { property: 'fb:app_id', content: '123456789' },
31
 * { property: 'og:title', content: 'Content Title' }
32
 * ```
33
 *
34
 * @experimental
35
 */
36
export interface MetaDefinition {
37
  charset?: string;
38
  content?: string;
39
  httpEquiv?: string;
40
  id?: string;
41
  itemprop?: string;
42
  name?: string;
43
  property?: string;
44
  scheme?: string;
45
  url?: string;
46
  [prop: string]: string;
47
}
48

    
49
/**
50
 * A service that can be used to get and add meta tags.
51
 *
52
 * @experimental
53
 */
54
@Injectable()
55
export class Meta {
56
  private _dom: DomAdapter = getDOM();
57
  constructor( @Inject(DOCUMENT) private _document: any) { }
58
  /**
59
   * Sets the title of the page
60
   */
61
  setTitle(title: string) {
62
    this._document.title = title
63
  }
64
  /**
65
   * Adds a new meta tag to the dom.
66
   *
67
   *  ### Example
68
   *
69
   * ```ts
70
   * const name: MetaDefinition = {name: 'application-name', content: 'Name of my application'};
71
   * const desc: MetaDefinition = {name: 'description', content: 'A description of the page'};
72
   * const tags: HTMLMetaElement[] = this.meta.addTags([name, desc]);
73
   * ```
74
   *
75
   * @param tags
76
   * @returns {HTMLMetaElement[]}
77
   */
78
  addTags(...tags: Array<MetaDefinition|MetaDefinition[]>): HTMLMetaElement[] {
79
    const presentTags = this._flattenArray(tags);
80
    if (presentTags.length === 0) return [];
81
    return presentTags.map((tag: MetaDefinition) => this._addInternal(tag));
82
  }
83

    
84
  /**
85
   * Gets the meta tag by the given selector. Returns element or null
86
   * if there's no such meta element.
87
   *
88
   *  ### Example
89
   *
90
   * ```ts
91
   * const meta: HTMLMetaElement = this.meta.getTag('name=description');
92
   * const twitterMeta: HTMLMetaElement = this.meta.getTag('name="twitter:title"');
93
   * const fbMeta: HTMLMetaElement = this.meta.getTag('property="fb:app_id"');
94
   * ```
95
   *
96
   * @param selector
97
   * @returns {HTMLMetaElement}
98
   */
99
  getTag(selector: string): HTMLMetaElement {
100
    if (!selector) return null;
101
    return this._dom.query(`meta[${selector}]`);
102
  }
103

    
104
  /**
105
   * Updates the meta tag with the given selector.
106
   *
107
   * *  ### Example
108
   *
109
   * ```ts
110
   * const meta: HTMLMetaElement = this.meta.updateTag('name=description', {name: 'description',
111
   * content: 'New description'});
112
   * console.log(meta.content); // 'New description'
113
   * ```
114
   *
115
   * @param selector
116
   * @param tag updated tag definition
117
   * @returns {HTMLMetaElement}
118
   */
119
  updateTag(selector: string, tag: MetaDefinition): HTMLMetaElement {
120
    const meta: HTMLMetaElement = this.getTag(selector);
121
    if (!meta) {
122
      // create element if it doesn't exist
123
      return this._addInternal(tag);
124
    }
125
    return this._prepareMetaElement(tag, meta);
126
  }
127

    
128
  updateMeta(name, content) {
129
       const head = this._document.head;
130
       let childNodesAsList = this._dom.childNodesAsList(head);
131
       let metaEl = childNodesAsList.find(el => el['attribs'] ?  el['attribs'].name == name : false);
132
       if (metaEl) metaEl['attribs'].content = content;
133
    }
134
    updateProperty(property, content) {
135
         const head = this._document.head;
136
         let childNodesAsList = this._dom.childNodesAsList(head);
137
         let metaEl = childNodesAsList.find(el => el['attribs'] ?  el['attribs'].property == property : false);
138
         if (metaEl) metaEl['attribs'].content = content;
139
      }
140

    
141
  /**
142
   * Removes meta tag with the given selector from the dom.
143
   *
144
   *  ### Example
145
   *
146
   * ```ts
147
   * this.meta.removeTagBySelector('name=description');
148
   * ```
149
   *
150
   * @param selector
151
   */
152
  removeTagBySelector(selector: string): void {
153
    const meta: HTMLMetaElement = this.getTag(selector);
154
    this.removeTagElement(meta);
155
  }
156

    
157
  /**
158
   * Removes given meta element from the dom.
159
   *
160
   *  ### Example
161
   *  ```ts
162
   * const elem: HTMLMetaElement = this.meta.getTag('name=description');
163
   * this.meta.removeTagElement(elem);
164
   * ```
165
   *
166
   * @param meta meta element
167
   */
168
  removeTagElement(meta: HTMLMetaElement): void {
169
    if (meta) {
170
      this._removeMetaElement(meta);
171
    }
172
  }
173

    
174
  private _addInternal(tag: MetaDefinition): HTMLMetaElement {
175
    const meta: HTMLMetaElement = this._createMetaElement();
176
    this._prepareMetaElement(tag, meta);
177
    this._appendMetaElement(meta);
178
    return meta;
179
  }
180

    
181
  private _createMetaElement(): HTMLMetaElement {
182
    return this._dom.createElement('meta') as HTMLMetaElement;
183
  }
184

    
185
  private _prepareMetaElement(tag: MetaDefinition, el: HTMLMetaElement): HTMLMetaElement {
186
    Object.keys(tag).forEach((prop: string) => this._dom.setAttribute(el, prop, tag[prop]));
187
    return el;
188
  }
189

    
190
  // private _appendMetaElement(meta: HTMLMetaElement): void {
191
  //   const head = this._dom.getElementsByTagName(this._dom.defaultDoc(), 'head')[0];
192
  //   this._dom.appendChild(head, meta);
193
  // }
194
  private _appendMetaElement(meta: HTMLMetaElement): void {
195
    const head = this._document.head;
196
    this._dom.appendChild(head, meta);
197
  }
198
  private _removeMetaElement(meta: HTMLMetaElement): void {
199
    const head = this._dom.parentElement(meta);
200
    this._dom.removeChild(head, meta);
201
  }
202

    
203
  private _flattenArray(input: any[], out: any[] = []): any[] {
204
    if (input) {
205
      for (let i = 0; i < input.length; i++) {
206
        const item: any = input[i];
207
        if (Array.isArray(item)) {
208
          this._flattenArray(item, out);
209
        } else if (item) {
210
          out.push(item);
211
        }
212
      }
213
    }
214
    return out;
215
  }
216
}
(3-3/12)