33

如何让 Javascript 告诉我网站网址。

例如,如果我有一个页面www.example.com/page.html

我希望 Javascript 告诉我网站 url 是www.example.com不是www.example.com/page.html(哪个 document.location 告诉我)

有没有办法做到这一点?如果是这样,怎么做?

在此先感谢您的帮助 :)

4

8 回答 8

101

有几种方法可以做到这一点,但一种方法可能最适合某些情况(例如在 iFrame 中)。

协议+域+页面

document.URL
> "http://example.com/page1.html"

document.location.href
> "http://example.com/page1.html"

协议+域

document.location.origin
> "http://example.com"

领域

document.location.host
> "example.com"

document.location.pathname
> "/page1.html"
于 2013-10-23T19:17:18.383 回答
0

试试这个

document.location.host
于 2013-10-23T19:00:16.967 回答
0

使用 alert(window.location.origin) 获取 url。

于 2013-10-23T19:02:33.447 回答
0

尝试

document.location.origin

这将为您提供协议和主机。

于 2013-10-23T19:03:04.730 回答
0

采用

window.location.hostname

您只需在 chrome 开发工具控制台中输入即可对其进行测试

参考

MDN:https ://developer.mozilla.org/en-US/docs/Web/API/Location

于 2013-10-23T19:03:40.343 回答
0

有很多方法可以得到这个。
打开 Chrome 浏览器并按 F12,您将获得控制台。

在那里为相同的问题 URL 键入以下命令。你会得到你的答案

window.location.hostname // Output : stackoverflow.com

window.location.origin // Output : http://stackoverflow.com

document.location.host // Output : stackoverflow.com
于 2013-10-23T19:19:13.127 回答
0

采用

document.location.origin+document.location.pathname;

将您重定向到哪里document.location.origin并将您重定向到“/stackoverflow/”(您的项目名称)。通过这种方式,您可以在 js 文件中引用您想要的页面或帖子。假设如果我想引用我的主页,我会使用"http://www"document.location.pathname

var address=document.location.origin+document.location.pathname;
 window.location.replace(address+"/home");

所以使用上面的例子我可以很容易地重定向到我的主页

于 2015-12-07T12:28:08.927 回答
0

你也可以使用location.href= '/'+'path_name/sub_path_name'

'/'= 然后带您到主页

'path_name/sub_path_name'= 将新路径传递到域页面

于 2021-09-13T10:04:37.123 回答