react 如何获取url协议
获取 URL 协议的方法
在 React 中可以通过 window.location.protocol 获取当前页面的 URL 协议(如 http: 或 https:)。以下是具体实现方式:
直接通过 window.location 获取

const protocol = window.location.protocol;
console.log(protocol); // 输出 "http:" 或 "https:"
在 React 组件中使用

import React, { useEffect } from 'react';
function App() {
useEffect(() => {
const protocol = window.location.protocol;
console.log('当前协议:', protocol);
}, []);
return <div>检查控制台输出协议信息</div>;
}
处理动态路由或服务端渲染(SSR)
在 Next.js 等 SSR 框架中,需通过 useEffect 或条件判断确保代码在客户端执行:
import { useEffect } from 'react';
function ProtocolChecker() {
useEffect(() => {
if (typeof window !== 'undefined') {
console.log('协议:', window.location.protocol);
}
}, []);
return null;
}
注意事项
window.location.protocol返回的字符串包含冒号(如https:)。- 服务端渲染时直接访问
window对象会报错,需通过typeof window检查。






