如何从浏览器地址栏获取URL?

Con*_*tor 16 javascript url

我想做一些js分析,所以我需要知道如何将用户在地址栏中输入的任何内容作为js变量,这样我才能知道最常见的拼写错误.这样我就可以将最常见的拼写错误重定向到正确的地址,并减少404页面请求.

浏览器中用户输入的示例:

https://stackoverflow.com/questions

.........................................

我试过用

document.location
Run Code Online (Sandbox Code Playgroud)

但是这显示了用户所在的页面(即404页面地址),而不是他们输入的内容

jwu*_*ler 26

这为您提供了用户所在的确切网址:

document.location.href
Run Code Online (Sandbox Code Playgroud)

在提交请求之前无法确定用户键入的内容(出于安全原因).


KAR*_*N.A 5

JavaScript提供了许多方法来使当前URL显示在Web浏览器地址栏中。您可以使用Window对象的Location对象属性来获取这些详细信息。

  1. href =>这将返回显示在地址栏中的整个URL。
  2. host =>这将在地址栏中返回URL的主机名和端口。
  3. hostname =>这将仅返回地址栏中URL的主机名。
  4. port =>这将仅返回地址栏中URL的端口详细信息。
  5. protocol =>这将在地址栏中返回URL的协议。就像URL使用HTTP(不使用SSL)或HTTPS(使用SSL)一样。
  6. pathname =>这将在地址栏中返回URL的路径名(域名后的值)。
  7. hashpathname =>这将返回URL的锚点部分,包括哈希单(#)。
  8. search =>这将返回URL的查询部分,例如以问号(?)开头的部分。
    console.log(' href => ' + window.location.href);
    console.log(' host => ' + window.location.host);
    console.log(' hostname => ' + window.location.hostname);
    console.log(' port => ' + window.location.port);
    console.log(' protocol => ' + window.location.protocol);
    console.log(' pathname => ' + window.location.pathname);
    console.log(' hashpathname => ' + window.location.hash);
    console.log(' search=> ' + window.location.search);
    Run Code Online (Sandbox Code Playgroud)

参考: https : //tecadmin.net/get-current-url-web-browser-using-javascript/


san*_*ers 0

javascript: alert(window.location.hostname);
Run Code Online (Sandbox Code Playgroud)

如果要显示路径名,请替换.hostname.pathname.