Home > Article > Web Front-end > Can JavaScript access url?
JavaScript can access URLs. By passing URL parameters and getting parameters on the current URL through JavaScript, many functions can be achieved.
Using JavaScript, you can access and operate the URL through the "window.location" object. The following are commonly used methods related to URL operations in JavaScript:
1. Change URL
You can change the URL address of the current page by modifying the URL attribute to a new URL.
window.location.href = "https://www.example.com";
2. Get URL information
You can get the URL information of the current page, where Contains many useful properties.
window.location.href //Return the complete URL
window.location.hostname //Return the host name
window.location.pathname //Return the path name
window.location. search //Returns the query part of the URL
window.location.hash //Returns the anchor point of the URL
3. Get URL parameters
You can parse the parameters on the URL into JavaScript objects , and then obtain each parameter in the URL in the form of key-value pairs.
function getUrlParams(url){
var params = {};
url.replace(/[?&] (1 )=( 2*)/gi, function(str, key, value) {
params[key] = value;
});
return params;
}
var params = getUrlParams(window.location.href);
console.log(params.userId); //Get the userId value in the URL parameter
4. Set URL parameters
You can set URL parameters by constructing a new URL, and then change the URL address by modifying the "href" attribute of the "window.location" object.
var url = "https://www.example.com";
url = "?userId=123&userName=john";
window.location.href = url;
5. Monitor URL changes
You can add a listening function. When the URL changes, the function will be automatically triggered.
window.addEventListener("hashchange", function() {
console.log("hash changed!");
});
In short, JavaScript can pass " window.location" object implements access to and operations on URLs, thereby achieving many useful functions. However, it should be noted that in JavaScript, the operation of the URL may affect the user experience and SEO effect, and needs to be carefully considered.
The above is the detailed content of Can JavaScript access url?. For more information, please follow other related articles on the PHP Chinese website!