From 91ccb4ba6e203f1b80a1aa7187d8773434948fc2 Mon Sep 17 00:00:00 2001 From: Vojta Jina Date: Tue, 19 Jul 2011 15:52:27 +0200 Subject: feat($browser): add $browser.baseHref() This method abstracts in document.head - returns the value. If absolute href set, it converts the href to relative. --- src/Browser.js | 11 +++++++++++ src/angular-mocks.js | 5 +++++ test/BrowserSpecs.js | 36 ++++++++++++++++++++++++++++++++++++ 3 files changed, 52 insertions(+) diff --git a/src/Browser.js b/src/Browser.js index 8e8f511a..62e5b116 100644 --- a/src/Browser.js +++ b/src/Browser.js @@ -509,4 +509,15 @@ function Browser(window, document, body, XHR, $log, $sniffer) { return script; }; + + /** + * Returns current + * (always relative - without domain) + * + * @returns {string=} + */ + self.baseHref = function() { + var href = document.find('base').attr('href'); + return href ? href.replace(/^https?\:\/\/[^\/]*/, '') : href; + }; } diff --git a/src/angular-mocks.js b/src/angular-mocks.js index 8410dc8c..f533bee0 100644 --- a/src/angular-mocks.js +++ b/src/angular-mocks.js @@ -302,6 +302,11 @@ function MockBrowser() { self.deferredFns.shift().fn(); } }; + + self.$$baseHref = ''; + self.baseHref = function() { + return this.$$baseHref; + }; } MockBrowser.prototype = { diff --git a/test/BrowserSpecs.js b/test/BrowserSpecs.js index f92a21af..de4354a0 100644 --- a/test/BrowserSpecs.js +++ b/test/BrowserSpecs.js @@ -691,4 +691,40 @@ describe('browser', function(){ expect(script).toBe(scripts[0]); }); }); + + describe('baseHref', function() { + var jqDocHead; + + function setDocumentBaseHrefTo(href) { + clearDocumentBaseHref(); + jqDocHead.append(''); + } + + function clearDocumentBaseHref() { + jqDocHead.find('base').remove(); + } + + beforeEach(function() { + jqDocHead = jqLite(document).find('head'); + }); + + afterEach(clearDocumentBaseHref); + + it('should return value from ', function() { + setDocumentBaseHrefTo('/base/path/'); + expect(browser.baseHref()).toEqual('/base/path/'); + }); + + it('should return undefined if no ', function() { + expect(browser.baseHref()).toBeUndefined(); + }); + + it('should remove domain from ', function() { + setDocumentBaseHrefTo('http://host.com/base/path/'); + expect(browser.baseHref()).toEqual('/base/path/'); + + setDocumentBaseHrefTo('http://host.com/base/path/index.html'); + expect(browser.baseHref()).toEqual('/base/path/index.html'); + }); + }); }); -- cgit v1.2.3