欢迎访问宙启技术站
智能推送

如何编写一个函数来获取当前网页的URL地址

发布时间:2023-12-16 08:49:43

编写一个函数来获取当前网页的URL地址,可以使用以下方法:

方法一:使用location对象的href属性

function getCurrentURL() {
  return window.location.href;
}

// 使用例子
var currentURL = getCurrentURL();
console.log(currentURL);

方法二:使用location对象的toString()方法

function getCurrentURL() {
  return window.location.toString();
}

// 使用例子
var currentURL = getCurrentURL();
console.log(currentURL);

方法三:使用document对象的URL属性

function getCurrentURL() {
  return document.URL;
}

// 使用例子
var currentURL = getCurrentURL();
console.log(currentURL);

方法四:使用document对象的documentURI属性

function getCurrentURL() {
  return document.documentURI;
}

// 使用例子
var currentURL = getCurrentURL();
console.log(currentURL);

方法五:使用window.location对象的属性组合拼接

function getCurrentURL() {
  var protocol = window.location.protocol;
  var hostname = window.location.hostname;
  var port = window.location.port;
  var pathname = window.location.pathname;
  var search = window.location.search;
  var hash = window.location.hash;
  
  return protocol + "//" + hostname + (port ? ":" + port : "") + pathname + search + hash;
}

// 使用例子
var currentURL = getCurrentURL();
console.log(currentURL);

以上是几种常用的方法来获取当前网页的URL地址,根据需要选择适合的方法使用即可。