监听浏览器地址栏变化、改变浏览器地址栏url

2019-09-23 19:25:55

监听变化

if( ('onhashchange' in window) && ((typeof document.documentMode==='undefined') || document.documentMode==8)) {
	// 浏览器支持onhashchange事件
	window.onhashchange = function () {
		// TODO,对应的操作
	};
}else{
	// TODO 通过定时器进行检测
	var old_hash = '';
	setInterval(function() {
		if(window.location.hash != old_hash){
			old_hash = window.location.hash;
			// TODO,对应的操作
		}
	}, 300)
}

·

改变地址栏

function updateUrlParameter(url, key, value) {
	if (!value) {
		return url;
	}
	var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
	var separator = url.indexOf('?') !== -1 ? "&" : "?";
	if (url.match(re)) {
		return url.replace(re, '$1' + key + "=" + value + '$2');
	} else {
		return url + separator + key + "=" + value;
	}
}

// 可以根据需要自行改变
var newUrl = updateUrlParameter(window.location.href,'page', '5');
window.history.replaceState({path: newUrl}, '', newUrl);

·

以上方法可以配合使用 http://www.putyy.com/article/11 中的parseURL函数

本文由"putyy"原创,转载无需和我联系,但请注明来自putyy
您的浏览器不支持canvas标签,请您更换浏览器