[英]Javascript Get Website URL
How do I get Javascript to tell me the website url. 如何让Javascript告诉我网站的网址。
For example if I have a page www.example.com/page.html
例如,如果我有一个页面
www.example.com/page.html
I want Javascript to tell me the site url is www.example.com
and not www.example.com/page.html
(which document.location tells me) 我希望Javascript告诉我网站网址是
www.example.com
而不是www.example.com/page.html
(哪个document.location告诉我)
Is there a way to do this? 有没有办法做到这一点? If so, how?
如果是这样,怎么样?
Thanks in advance for your help :) 在此先感谢您的帮助 :)
There are several ways you can do this, but one way might be best for certain situations (eg within an iFrame).
有几种方法可以做到这一点,但有一种方法可能最适合某些情况(例如在iFrame中)。
Protocol + Domain + Page 协议+域+页面
document.URL
> "http://example.com/page1.html"
document.location.href
> "http://example.com/page1.html"
Protocol + Domain 协议+域
document.location.origin
> "http://example.com"
Domain 域
document.location.host
> "example.com"
Page 页
document.location.pathname
> "/page1.html"
试试这个
document.location.host
使用alert(window.location.origin)获取url。
Try 尝试
document.location.origin
That will give you the protocol and host. 这将为您提供协议和主机。
Use 使用
window.location.hostname
You can test it by just typing it in the chrome dev tools console 您只需在chrome dev工具控制台中键入它即可对其进行测试
Reference 参考
MDN: https://developer.mozilla.org/en-US/docs/Web/API/Location MDN: https : //developer.mozilla.org/en-US/docs/Web/API/Location
There are many ways to get this. 有很多方法可以做到这一点。
Open Chrome browser and press F12, you'll get console. 打开Chrome浏览器并按F12,您将获得控制台。
Type following commands there for the same question URL. 在同一问题URL中键入以下命令。 You will get your answer
你会得到你的答案
window.location.hostname // Output : stackoverflow.com
window.location.origin // Output : http://stackoverflow.com
document.location.host // Output : stackoverflow.com
use 使用
document.location.origin+document.location.pathname;
where document.location.origin
will redirect you to "http://www"
and document.location.pathname
will redirect you to "/stackoverflow/"(Name of your project). 其中
document.location.origin
会将您重定向到"http://www"
, document.location.pathname
会将您重定向到“/ stackoverflow /”(项目名称)。 In this way you can give reference to page or post you want in your js file.Suppose if i want reference to my home page i would have use 通过这种方式,您可以在js文件中引用您想要的页面或帖子。如果我想参考我的主页,我会使用
var address=document.location.origin+document.location.pathname;
window.location.replace(address+"/home");
So using above example i can easily redirect to my homepage 因此,使用上面的示例我可以轻松地重定向到我的主页
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.