ember-cli-head icon indicating copy to clipboard operation
ember-cli-head copied to clipboard

Escaping HTML characters in fastboot

Open knownasilya opened this issue 4 years ago • 5 comments

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?

knownasilya avatar Nov 11 '19 14:11 knownasilya

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

rwjblue avatar Nov 11 '19 16:11 rwjblue

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

knownasilya avatar Nov 11 '19 16:11 knownasilya

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...

rwjblue avatar Nov 11 '19 16:11 rwjblue

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 avatar Nov 11 '19 16:11 knownasilya

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.

knownasilya avatar Nov 11 '19 18:11 knownasilya