鉴于我在下面这一页
http://www.webmail.com/pages/home.aspx
如何用JavaScript检索主机名(“http://www.webmail.com”)?
鉴于我在下面这一页
http://www.webmail.com/pages/home.aspx
如何用JavaScript检索主机名(“http://www.webmail.com”)?
当前回答
要获取主机名:location.hostname
但你的例子也在寻找方案,也就是位置。在Chrome中,origin似乎可以做你想做的事情,但在Mozdev文档中却没有提及。你可以用
location.protocol + '//' + location.hostname
如果你也想要端口号(当它不是80时),那么:
location.protocol + '//' + location.host
其他回答
根据您的需要,您可以使用其中一个窗口。位置属性。 在您的问题中,您询问的是主机,可以使用window.location.hostname(例如www.example.com)检索。在你的例子中,你展示了一个叫做原点的东西,它可以使用window.location.origin(例如http://www.example.com)来检索。
var path = window.location.origin + "/";
//result = "http://localhost:60470/"
要获取主机名:location.hostname
但你的例子也在寻找方案,也就是位置。在Chrome中,origin似乎可以做你想做的事情,但在Mozdev文档中却没有提及。你可以用
location.protocol + '//' + location.hostname
如果你也想要端口号(当它不是80时),那么:
location.protocol + '//' + location.host
你可以尝试这样做:
1. Get the full URL:
window.location
2. Get the only protocol:
window.location.protocol
3. Get the host:
window.location.host
4. Get the host and protocol:
window.location.origin
5. Get pathname or directory without protocol and host:
var url = 'http://www.example.com/somepath/path2/path3/path4';
var pathname = new URL(url).pathname;
alert(pathname);
您可以使用以下命令获取协议、主机和端口:
window.location.origin
浏览器兼容性
桌面
Chrome | Edge | Firefox (Gecko) | Internet Explorer | Opera | Safari (WebKit) |
---|---|---|---|---|---|
(Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |
30.0.1599.101 (possibly earlier) | ? | 21.0 (21.0) | 11 | ? | 7 (possibly earlier, see webkit bug 46558) |
移动
Android | Edge | Firefox Mobile (Gecko) | IE Phone | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|
(Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |
30.0.1599.101 (possibly earlier) | ? | 21.0 (21.0) | ? | ? | 7 (possibly earlier, see webkit bug 46558) |
所有浏览器兼容性都来自Mozilla开发者网络
使用前牢记窗口和位置
1.在客户端渲染中使用窗口和位置(注意:不在ssr中使用)
window.location.host;
or
var host = window.location.protocol + "//" + window.location.host;
2.服务器端渲染
如果你使用nuext .js(vue)或next.js(react),请参考文档
对于nuxt js框架
req.headers.host
代码:
async asyncData ({ req, res }) {
if (process.server) {
return { host: req.headers.host }
}
路由器代码:
export function createRouter (ssrContext) {
console.log(ssrContext.req.headers.host)
return new Router({
middleware: 'route',
routes:checkRoute(ssrContext),
mode: 'history'
})
}
对于next.js框架
Home.getInitalProps = async(context) => {
const { req, query, res, asPath, pathname } = context;
if (req) {
let host = req.headers.host // will give you localhost:3000
}
}
对于node.js用户
var os = require("os");
var hostname = os.hostname();
or
request.headers.host
对于laravel用户
public function yourControllerFun(Request $request) {
$host = $request->getHttpHost();
dd($host);
}
or
直接在web.php中使用
Request::getHost();
注意:
您手动检查CSR和SSR应用程序 例子 ssr渲染
if(req.server){
host=req.host;
}
if(req.client){
host=window.location.host;
}