diff --git a/fixUrls.js b/fixUrls.js index baa43657..843f1183 100644 --- a/fixUrls.js +++ b/fixUrls.js @@ -12,51 +12,52 @@ * */ -module.exports = function (css, currentUrl) { - - // get current url - currentUrl = currentUrl || (typeof window !== "undefined" && window.location && window.location.href) || null; - if (typeof currentUrl != "string") { - throw new Error("fixUrls requires a current url"); - } - - //blank or null? - if (!css || typeof css !== "string") +module.exports = function (css) { + // get current location + var location = typeof window !== "undefined" && window.location; + + if (!location) { + throw new Error("fixUrls requires window.location"); + } + + // blank or null? + if (!css || typeof css !== "string") { return css; + } - //base url - var baseUrl = currentUrl.match(/^([a-z]+:)?(\/\/)?[^\/]+/)[0]; - var protocol = baseUrl.split(":")[0]; - var currentUrlPath = baseUrl + (currentUrl.replace(baseUrl, "")).replace(/\/[^\/]+$/, "") + "/"; + var baseUrl = location.protocol + location.host; + var currentDir = baseUrl + location.pathname.replace(/\/[^\/]*$/, "/"); - //convert each url(...) - var fixedCss = css.replace(/url *\( *(.+?) *\)/g, function(fullMatch, origUrl){ - //strip quotes (if they exist) + // convert each url(...) + var fixedCss = css.replace(/url *\( *(.+?) *\)/g, function(fullMatch, origUrl) { + // strip quotes (if they exist) var unquotedOrigUrl = origUrl - .replace(/^"(.*)"$/, function(o,$1){ return $1; }) - .replace(/^'(.*)'$/, function(o,$1){ return $1; }); + .replace(/^"(.*)"$/, function(o, $1){ return $1; }) + .replace(/^'(.*)'$/, function(o, $1){ return $1; }); - //already a full url? no change - if (/^(data:|http:\/\/|https:\/\/|file:\/\/\/)/i.test(unquotedOrigUrl)) + // already a full url? no change + if (/^(#|data:|http:\/\/|https:\/\/|file:\/\/\/)/i.test(unquotedOrigUrl)) { return fullMatch; - - //convert the url to a full url - var newUrl = unquotedOrigUrl; - if (newUrl.indexOf("//") === 0) { - //add protocol - newUrl = protocol + ":" +newUrl; - }else if (newUrl.indexOf("/") === 0){ - //path should be relative to the base url - newUrl = baseUrl + newUrl; - }else{ - //path should be relative to the current directory - newUrl = currentUrlPath + newUrl.replace(/^\.\//, ""); + } + + // convert the url to a full url + var newUrl; + + if (unquotedOrigUrl.indexOf("//") === 0) { + // add protocol + newUrl = location.protocol + unquotedOrigUrl; + } else if (unquotedOrigUrl.indexOf("/") === 0) { + // path should be relative to the base url + newUrl = baseUrl + unquotedOrigUrl; // already starts with '/' + } else { + // path should be relative to current directory + newUrl = currentDir + unquotedOrigUrl.replace(/^\.\//, "") // Strip leading './' } - //send back the fixed url(...) - return "url("+JSON.stringify(newUrl)+")"; + // send back the fixed url(...) + return "url(" + JSON.stringify(newUrl) + ")"; }); - //send back the fixed css + // send back the fixed css return fixedCss; };