Skip to content

CSS plugin does not maintain relative URLs #308

@eoneill

Description

@eoneill

When using the CSS plugin, Inject should adjust non-qualified URLs to make sure they're pointing to the correct path.

e.g. if my CSS file contains a relative image page, the Injected CSS file should respect the relative path of the origin CSS file, not the page it's being injected into.

// where:
// `resolvedPath` is the path to the CSS module we XHR
//    e.g. `http://www.licdn.com/scds/concat/common/css?f=scss/some/file`
// `content` is the body of the CSS module

// matches non-qualified `url()` notations within the content
//  includes AlphaImageLoader(src="...")
//  excludes any fully qualified URLs, scheme-less URLs, or URIs with valid protocols
var rNonQualifiedUrl = /((?:url\s*\(|AlphaImageLoader\s*\(\s*src\s*=)\s*['"]?(?!\/\/|[a-z]+\:))(.)/igm;

// matches up to the pathname of the URL
var rBasePath = /(?:^(?:https?\:)?\/\/[^\/\?\#]+)/i;

// matches any extraneous query/hash info that isn't relevant to URL path resolution
var rQueryOrHash = /\/?[\?\#].*/;

// strip off any query or hash on the file path string
var basePath = resolvedPath.replace(rQueryOrHash, '');
// the fully qualified path to the host (excluding any pathname, hash, query)
var hostPath = rBasePath.exec(resolvedPath)[0];

// adjust any non-qualified URLs in the content
content.replace(rNonQualifiedUrl, function() {
  var result = arguments[1];
  if (arguments[2][0] === '/') {
    result += hostPath + arguments[2];
  }
  else {
    result += basePath + '/' + arguments[2]
  }
  return result;
});

some expectations, assuming the resolvedPath to the CSS module was: http://cdn.server.com/path/to/my.css

url(/images/some/image.png)
 -> url(http://cdn.server.com/images/some/image.png)

url("../../relative.png")
 -> url("http://cdn.server.com/path/to/my.css/../../relative.png")

url('http://www.cdn.com/image.png')
 -> url('http://www.cdn.com/image.png') // untouched

url(data:image/png;base64,abcdEFG)
 -> url(data:image/png;base64,abcdEFG) // untouched

progid:DXImageTransform.Microsoft.AlphaImageLoader(src='/path/to/image.png',sizingMethod='scale')
 -> progid:DXImageTransform.Microsoft.AlphaImageLoader(src='http://cdn.server.com/path/to/image.png',sizingMethod='scale')

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions