Skip to content
This repository has been archived by the owner on Apr 4, 2019. It is now read-only.

Commit

Permalink
Adds Node-compatible protocolForURL
Browse files Browse the repository at this point in the history
The current implementation of the DOM helper’s `protocolForURL` relies
on the implicit parsing and normalization that the browser’s DOM does
when setting the A element’s `href` property.

However, the DOM helper is often used with subset DOM implementations
like simple-dom. In those cases, we cannot rely on this normalization.

This commit detects when URL parsing doesn’t happen when setting the
`href` property on an `A` element and falls back to using Node’s
`URL` package.
  • Loading branch information
tomdale committed Dec 6, 2015
1 parent 64dc2b0 commit 38019b6
Showing 1 changed file with 28 additions and 2 deletions.
30 changes: 28 additions & 2 deletions packages/dom-helper/lib/main.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
/*globals module*/

import Morph from "./htmlbars-runtime/morph";
import AttrMorph from "./morph-attr";
import {
Expand Down Expand Up @@ -565,15 +567,39 @@ prototype.parseHTML = function(html, contextualElement) {
};

var parsingNode;
var URL;

// Used to determine whether a URL needs to be sanitized.
prototype.protocolForURL = function(url) {
// Test to see if our DOM implementation parses
// and normalizes URLs.
var protocol = browserProtocolForURL.call(this, 'foobar:baz');
if (protocol === 'foobar:') {
// Swap in the method that doesn't do this test now that
// we know it works.
prototype.protocolForURL = browserProtocolForURL;
} else {
// Otherwise, we need to fall back to our own URL parsing.
// Global `require` is shadowed by Ember's loader so we have to use the fully
// qualified `module.require`.
URL = module.require('url');
prototype.protocolForURL = nodeProtocolForURL;
}

return this.protocolForURL(url);
};

function browserProtocolForURL(url) {
if (!parsingNode) {
parsingNode = this.document.createElement('a');
}

parsingNode.href = url;
return parsingNode.protocol;
};
}

function nodeProtocolForURL(url) {
var protocol = URL.parse(url).protocol;
return (protocol === null) ? ':' : protocol;
}

export default DOMHelper;

0 comments on commit 38019b6

Please sign in to comment.