Skip to content

Instantly share code, notes, and snippets.

@JCloudYu
Last active May 1, 2021 05:31
Show Gist options
  • Save JCloudYu/ea1a89bb6e0d106495b962677b7d719b to your computer and use it in GitHub Desktop.
Save JCloudYu/ea1a89bb6e0d106495b962677b7d719b to your computer and use it in GitHub Desktop.
/**
* Author: JCloudYu
* Create: 2020/05/07
**/
(()=>{
"use strict";
const _PUSH_STATE = window.history.pushState;
const _REPLACE_STATE = window.history.replaceState;
window.addEventListener('pushstate', function(e){
if ( typeof window.onpushstate !== "function" ) return;
window.onpushstate(e);
});
window.history.pushState = function(state, title, url) {
const args = Array.prototype.slice.call(arguments, 0);
_PUSH_STATE.call(window.history, ...args);
const event = new Event("pushstate", { bubbles:false, composed:false });
event.state = state;
window.dispatchEvent(event);
};
window.history.replaceState = function(state, title, url) {
const args = Array.prototype.slice.call(arguments, 0);
_REPLACE_STATE.call(window.history, ...args);
const event = new Event("pushstate", { bubbles:false, composed:false });
event.state = state;
window.dispatchEvent(event);
};
const configurable=true, enumerable=true, writable=false;
Object.defineProperties(window.location, {
push: {
configurable, writable, enumerable,
value:function(url='/', state=null) {
if ( Object(url) === url ) {
const {pathname='', search='', hash=''} = url;
let params;
if ( Object(search) === search ) {
params = new URLSearchParams();
for(let key in search) {
params.set(key, search[key]);
}
}
else {
params = new URLSearchParams(''+search);
}
const query_str = params.toString();
url = (''+pathname) + (query_str===""?"":"?") + query_str + (hash===""?"":"#") + hash;
}
return window.history.pushState(state, '', ''+url);
}
},
overwrite: {
configurable, writable, enumerable,
value:function(url='/', state=null) {
if ( Object(url) === url ) {
const {pathname='', search='', hash=''} = url;
let params;
if ( Object(search) === search ) {
params = new URLSearchParams();
for(let key in search) {
params.set(key, search[key]);
}
}
else {
params = new URLSearchParams(''+search);
}
const query_str = params.toString();
url = (''+pathname) + (query_str===""?"":"?") + query_str + (hash===""?"":"#") + hash;
}
return window.history.replaceState(state, '', ''+url);
}
},
pop: {
configurable, writable, enumerable,
value:function() {
const current_state = window.history.state;
window.history.go(-1);
return current_state;
}
},
state: {
configurable, enumerable,
get:function() {
return window.history.state;
}
}
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment