ember-fastboot / ember-cli-head

Ember Cli Addon for Adding Content to HTML Head
MIT License
98 stars 34 forks source link

Escaping HTML characters in fastboot #67

Open knownasilya opened 4 years ago

knownasilya commented 4 years ago

In the browser I'd do something like:

export default function htmlDecode(input) {
  let doc = new DOMParser().parseFromString(input, 'text/html');
  return doc.documentElement.textContent;
}

and escape the opengraph text, but the DOMParser is not available in fastboot, what to do?

rwjblue commented 4 years ago

I'm not really sure what you are asking, can you explain? What HTML characters need escaping?

knownasilya commented 4 years ago

Things like apostrophes (&#8217) or quotes (&#8220 and &#8221), etc.

rwjblue commented 4 years ago

Can you give more info, possibly a demo repo or something? I'm really struggling to understand why this is an issue in your scenario...

knownasilya commented 4 years ago

Basically we are pulling in content from Wordpress via graphql and dynamically set opengraph data.

Something like this:

 afterModel(result) {
    this.set('headData.ogDescription', result.post.excerpt);
    this.set(
      'headData.ogImage',
      result.post.featuredImage && result.post.featuredImage.sourceUrl
        ? result.post.featuredImage.sourceUrl
        : null
    );
    this.set('headData.ogType', 'article');
  }

Where result.post.excerpt and others have these characters escaped and when using in Twitter you see things like &#8217

knownasilya commented 4 years ago

Looks like something along the lines of

import { htmlSafe } from '@ember/template';

export function decodeHtmlEntities(encodedString) {
  let isFastBoot = typeof FastBoot !== 'undefined';
  if (isFastBoot) {
    return htmlSafe(
      FastBoot.require('html-entities').AllHtmlEntities.decode(encodedString)
    );
  }
  let doc = new DOMParser().parseFromString(encodedString, 'text/html');
  return htmlSafe(doc.documentElement.textContent);
}

export default helper(([encodedString]) => decodeHtmlEntities(encodedString));

and

"fastbootDependencies": [
    "html-entities"
]

in package.json along with the regular dependency and used as helper or function. Seems like this could be provided via fastboot service with an async import when used or something.