Use of front-end basic location

concept

Get the address information of the current page, modify some attributes, and implement page jumps and refreshes, etc.

 Sample display

window.location Meaning .originURL base address, including protocol name, domain name and port number .protocolProtocol ( http: or  https:) .hostdomain name + port number .hostnameDomain name .portPort number .pathnamepath (starting /with) .searchQuery string, starting with ?Page .hashanchor, starting with #complete .hrefURL

What is easier to confuse is hostthat hostnamethe difference between these two properties is that the former also contains the port number.

Modify attribute value

Except originfor 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 .hrefboth 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 .hrefit is slightly faster and window.locationconcatenating strings is the slowest.

.assign()hrefIt 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'
      })
    }

Guess you like

Origin blog.csdn.net/2201_75705263/article/details/135152374