Skip to content

Commit

Permalink
Add parsing when using SSR. Fixes developit#6.
Browse files Browse the repository at this point in the history
  • Loading branch information
te-online committed Apr 13, 2018
1 parent 034c4c6 commit 2126bfd
Show file tree
Hide file tree
Showing 3 changed files with 4,355 additions and 11 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@
"babel-preset-stage-0": "^6.5.0",
"chai": "^3.5.0",
"diff": "^2.2.2",
"dom-parser": "^0.1.5",
"eslint": "^3.1.1",
"gzip-size-cli": "^1.0.0",
"karma": "^1.1.1",
Expand Down
39 changes: 28 additions & 11 deletions src/parse-markup.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
let parserDoc;
import DomParser from 'dom-parser';
const parser = new DomParser();

/** Parse markup into a DOM using the given mimetype.
* @param {String} markup
Expand All @@ -19,18 +21,22 @@ export default function parseMarkup(markup, type) {
}

// if available (browser support varies), using DOMPaser in HTML mode is much faster, safer and cleaner than injecting HTML into an iframe.
try {
doc = new DOMParser().parseFromString(wrappedMarkup, mime);
} catch (err) {
parserError = err;
}
if (isNode()) {
doc = parser.parseFromString(wrappedMarkup);
} else {
try {
doc = new DOMParser().parseFromString(wrappedMarkup, mime);
} catch (err) {
parserError = err;
}

// fall back to using an iframe to parse HTML (not applicable for XML, since DOMParser() for XML works in IE9+):
if (!doc && type==='html') {
doc = parserDoc || (parserDoc = buildParserFrame());
doc.open();
doc.write(wrappedMarkup);
doc.close();
// fall back to using an iframe to parse HTML (not applicable for XML, since DOMParser() for XML works in IE9+):
if (!doc && type==='html') {
doc = parserDoc || (parserDoc = buildParserFrame());
doc.open();
doc.write(wrappedMarkup);
doc.close();
}
}

if (!doc) return;
Expand Down Expand Up @@ -67,3 +73,14 @@ function buildParserFrame() {
document.body.appendChild(frame);
return frame.contentWindow.document;
}

/** Determines if we are in node environment or browser.
* Adopted from https://github.com/iliakan/detect-node.
*/
function isNode() {
return (
Object.prototype.toString.call(
typeof process !== 'undefined' ? process : 0 // eslint-disable-line no-undef
) === '[object process]')
;
}
Loading

0 comments on commit 2126bfd

Please sign in to comment.