concept
Get the address information of the current page, modify some attributes, and implement page jumps and refreshes, etc.
Sample display
window.location
Meaning .origin
URL base address, including protocol name, domain name and port number .protocol
Protocol ( http:
or https:
) .host
domain name + port number .hostname
Domain name .port
Port number .pathname
path (starting /
with) .search
Query string, starting with ?
Page .hash
anchor, starting with #
complete .href
URL
What is easier to confuse is host
that hostname
the difference between these two properties is that the former also contains the port number.
Modify attribute value
Except origin
for the read-only properties, all the above properties can be modified. The effect of the modification is to jump to the corresponding new address.
Property list
List of methods
.assign()
Navigate to the specified URL .replace()
Navigate to the specified URL and delete the access record of the current page .reload()
Reload the current page .toString()
Return URL string
.toString()
and .href
both return URLs, is there a difference between them? The result is the same, there is a slight difference in performance. It can be seen from the performance test results on JSPerf that .href
it is slightly faster and window.location
concatenating strings is the slowest.
.assign()
href
It is equivalent to direct modification , so .replace()
what is the difference between them?
.assign()
When jumping to the new address, the access record of the current page will be left. Clicking the browser's return button will return to the original page and .replace()
will not be retained.
Scene 1: Page jump collection
location.href='https://www.baidu.com'
window.open('http://www.baidu.com','_self')
location.assign('http://www.baidu.com')
location.replace('http://www.baidu.com')
<a href="https://www.baidu.com">跳转</a>
- Jump to a fixed address in the page
function imitateClick(url){
let aEle = document.createElement("a");
aEle.setAttribute("href", url);
aEle.setAttribute("target", "_blank");
aEle.setAttribute("id", "previewJumpEle");
// 防止重复添加
if (!document.getElementById("previewJumpEle")) {
document.body.appendChild(aEle);
}
// 模拟点击
aEle.click();
(aEle.remove && aEle.remove()) || (aEle.removeNode && aEle.removeNode(true));
};
imitateClick('https://www.baidu.com');
- Directly make a senseless jump in js, but this method has a drawback: after verification, some browsers may intercept it, so use it with caution.
<meta http-equiv="refresh" content="5;url=http://www.w3school.com.cn">
Scenario 2: Detect the protocol and prompt the user
if (location.protocol == 'http:') {
this.$confirm('确定吗?').then(() => {
location.href = 'https://www.baidu.com'
})
}