Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
80684 views
1
"use strict";
2
3
var URL = require("url");
4
var NOT_IMPLEMENTED = require("./utils").NOT_IMPLEMENTED;
5
6
module.exports = Location;
7
8
function Location(urlString, window) {
9
this._url = URL.parse(urlString);
10
this._window = window;
11
}
12
13
Location.prototype = {
14
constructor: Location,
15
reload: function () {
16
NOT_IMPLEMENTED(this._window, "location.reload")();
17
},
18
get protocol() { return this._url.protocol || ":"; },
19
get host() { return this._url.host || ""; },
20
get auth() { return this._url.auth; },
21
get hostname() { return this._url.hostname || ""; },
22
get origin() { return ((this._url.protocol !== undefined && this._url.protocol !== null) ? this._url.protocol + "//" : this._url.protocol) + this._url.host || ""; },
23
get port() { return this._url.port || ""; },
24
get pathname() { return this._url.pathname || ""; },
25
get href() { return this._url.href; },
26
get hash() { return this._url.hash || ""; },
27
get search() { return this._url.search || ""; },
28
29
set href(val) {
30
var oldUrl = this._url.href;
31
var oldProtocol = this._url.protocol;
32
var oldHost = this._url.host;
33
var oldPathname = this._url.pathname;
34
var oldHash = this._url.hash || "";
35
36
this._url = URL.parse(URL.resolve(oldUrl, val));
37
var newUrl = this._url.href;
38
var newProtocol = this._url.protocol;
39
var newHost = this._url.host;
40
var newPathname = this._url.pathname;
41
var newHash = this._url.hash || "";
42
43
if (oldProtocol === newProtocol && oldHost === newHost && oldPathname === newPathname && oldHash !== newHash) {
44
this._signalHashChange(oldUrl, newUrl);
45
} else {
46
NOT_IMPLEMENTED(this._window, "location.href (no reload)")();
47
}
48
},
49
50
set hash(val) {
51
var oldUrl = this._url.href;
52
var oldHash = this._url.hash || "";
53
54
if (val.lastIndexOf("#", 0) !== 0) {
55
val = "#" + val;
56
}
57
58
this._url = URL.parse(URL.resolve(oldUrl, val));
59
var newUrl = this._url.href;
60
var newHash = this._url.hash || "";
61
62
if (oldHash !== newHash) {
63
this._signalHashChange(oldUrl, newUrl);
64
}
65
},
66
67
set search(val) {
68
var oldUrl = this._url.href;
69
var oldHash = this._url.hash || "";
70
if (val.length) {
71
if (val.lastIndexOf("?", 0) !== 0) {
72
val = "?" + val;
73
}
74
this._url = URL.parse(URL.resolve(oldUrl, val + oldHash));
75
} else {
76
this._url = URL.parse(oldUrl.replace(/\?([^#]+)/, ""));
77
}
78
},
79
80
replace: function (val) {
81
this.href = val;
82
},
83
84
toString: function () {
85
return this._url.href;
86
},
87
88
_signalHashChange: function (oldUrl, newUrl) {
89
if (this._window.document) {
90
var ev = this._window.document.createEvent("HTMLEvents");
91
ev.initEvent("hashchange", false, false);
92
ev.oldUrl = oldUrl;
93
ev.newUrl = newUrl;
94
process.nextTick(function () {
95
this._window.dispatchEvent(ev);
96
}.bind(this));
97
}
98
}
99
};
100
101