访问历史记录:
在JavaScript中,浏览器的历史记录用window.history对象表示的,它是访问过的URL列表。history对象的方法可以让我们访问这个列表,但是不能修改这些URL地址。
history对象只有一个属性,是length长度,表示用户访问过的页面的数量:
window.history.length;
history对象有三个方法,分别是forward(),backward()和go();
history.forward();
相当于单击浏览器的前进按钮,在历史列表中向前寻找一个URL;
history.backward();
相当于单击浏览器的后腿按钮,在历史列表中向后寻找一个URL;
history.go(x);
x表示步数,可以前进或者后腿相应的步数,比如
history.go(1); //前进1页
history.go(-3); //后腿3页
location对象:
它包含当前加载页面的URL信息。页面的URL是由多个部分组成的:
[协议]//[主机名]:[端口]/[路径][搜索][hash]
下面是一个URL范例:
http://www.xxx.com:8080/tools/display.php?id=002#list
协议是http,
主机名是www.xxx.com,
端口是8080,
路径是/tools/display.php,
搜索是?id=002,
hash是#list。
与location对象的对应属性有:
属性 | 说明 |
location.href | "http://www.xxx.com:8080/tools/display.php?id=002#list" |
location.protocol | "http:" |
location.host | "www.xxx.com:8080" |
location.hostname | "www.xxx.com" |
location.port | "8080" |
location.pathname | "/tools/display.php" |
location.search | "?id=002" |
location.hash | "#list" |
location对象导航:
第一种是直接使用href属性,
location.href = "www.newPage.com";
用这种方法转移至新页面后,原始页面的记录会保留在浏览器历史记录里,可以使用back按钮回退。如果希望使用新的URL替换当前页面,可以使用location对象的replace方法:
location.replace("www.newPage.com");
刷新页面:
location.reload();
使用没有参数的reload,浏览器会从缓存中加载页面,如果需要浏览器从服务器加载数据,可以带参数true:
location.reload(true);
获取浏览器信息navigator对象:
先看个示例代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>window.navigator</title>
<style>
td {
border: 1px solid gray;
padding: 3px 5px;
}
</style>
</head>
<body>
<script>
document.write("<table>");
document.write("<tr><td>appName</td><td>" + navigator.appName +"</td>");
document.write("<tr><td>addCodeName</td><td>" + navigator.appCodeName + "</td>");
document.write("<tr><td>appVersion</td><td>" + navigator.appVersion + "</td>");
document.write("<tr><td>language</td><td>"+ navigator.language +"</td>");
document.write("<tr><td>cookieEnabled</td><td>"+ navigator.cookieEnabled +"</td>");
document.write("<tr><td>cpuClass</td><td>"+ navigator.cpuClass +"</td>");
document.write("<tr><td>onLine</td><td>"+ navigator.onLine +"</td>");
document.write("<tr><td>platform</td><td>"+ navigator.platform +"</td>");
document.write("<tr><td>Plugins</td><td>"+ navigator.plugins +"</td>");
document.write("</table>");
</script>
</body>
</html>
浏览器预览后,你会发现很多配置信息不是你想象中的。
navigator对象向我们展示了丰富的历史背景和复杂的行业竞争。以上这些信息并不可靠,但也算是能够提供的最佳结果了。所以,当我们需要一些浏览器配置信息时,从navigator获取是一个错误的选择。