JavaScript入门教程区别技术点优化安全高级JS

JavaScript Location和History

2021-10-24  本文已影响0人  微语博客

和上篇文章的screen和navigator一样,location和history也是window下的对象,location对象包含当前页面的导航信息,history对象包含历史记录。

Location对象

window.location 对象用于获得当前页面的地址 (URL),也可以把浏览器重定向到新的页面,使用的时候可以不带window。下面代码我们在控制台打印一下location

console.log(location);//Location{...}

一些常见属性:

console.log(location.hostname);//
console.log(location.pathname);//
console.log(location.port);//
console.log(location.protocol);//
console.log(location.href);//

如果是本地静态文件,则可能没有上述数据,我们可以打开一个网站,再从控制台输出上面的数据。

加载重定向

使用location对象,我们可以将当前页面定向到别的页面,这只需设置location.href = "url"。另外location.assign(url)location.replace(url)两个方法也可以加载新的页面

location.href = "https://www.baidu.com/";
//location.assign("https://www.baidu.com/");
//location.replace("https://www.baidu.com/");

location.assign(url)相当于链接跳转,location.replace(url)则是取代当前页面。

History对象

window.history 对象包含浏览器的历史,window.history对象在编写时可不使用 window 这个前缀。

console.log(history);//History{...}

属性和方法:

console.log(history.length);//历史记录长度
history.back();//后退一页
//history.forward();//前进一页
//history.go(-1);//后退一页
上一篇 下一篇

猜你喜欢

热点阅读