Files
lingniu-platform/sdk/frontend/oauth2-login-sdk/dist/utils/url.js
2026-02-09 11:24:51 +08:00

100 lines
2.9 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* URL处理工具
* 用于生成授权URL、解析URL参数等功能
*/
/**
* 生成随机字符串
* @param length 字符串长度默认32位
* @returns 随机字符串
*/
export function generateRandomString(length = 32) {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let result = '';
for (let i = 0; i < length; i++) {
result += chars.charAt(Math.floor(Math.random() * chars.length));
}
return result;
}
/**
* 解析URL查询参数
* @param url URL字符串默认为当前URL
* @returns 查询参数对象
*/
export function parseQueryParams(url = window.location.href) {
const params = {};
const queryString = url.split('?')[1];
if (!queryString) {
return params;
}
const pairs = queryString.split('&');
for (const pair of pairs) {
const [key, value] = pair.split('=');
if (key) {
params[decodeURIComponent(key)] = decodeURIComponent(value || '');
}
}
return params;
}
/**
* 构建URL查询参数
* @param params 查询参数对象
* @returns 查询参数字符串
*/
export function buildQueryParams(params) {
const pairs = [];
for (const [key, value] of Object.entries(params)) {
if (value !== undefined && value !== null) {
pairs.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`);
}
}
return pairs.length ? `?${pairs.join('&')}` : '';
}
/**
* 生成OAuth2授权URL
* @param authorizationEndpoint 授权端点URL
* @param clientId 客户端ID
* @param redirectUri 重定向URL
* @param options 可选参数
* @returns 授权URL
*/
export function generateAuthorizationUrl(authorizationEndpoint, clientId, redirectUri, options) {
const { responseType = 'code', scope, state = generateRandomString(32), ...extraParams } = options || {};
const params = {
client_id: clientId,
redirect_uri: redirectUri,
response_type: responseType,
state,
...(scope ? { scope } : {}),
...extraParams
};
const queryString = buildQueryParams(params);
return `${authorizationEndpoint}${queryString}`;
}
/**
* 检查当前URL是否为授权回调
* @param url URL字符串默认为当前URL
* @returns 是否为授权回调
*/
export function isCallbackUrl(url = window.location.href) {
const params = parseQueryParams(url);
return !!params.code || !!params.error;
}
/**
* 获取当前URL的路径名
* @param url URL字符串默认为当前URL
* @returns 路径名
*/
export function getPathname(url = window.location.href) {
const urlObj = new URL(url);
return urlObj.pathname;
}
/**
* 获取当前URL的主机名
* @param url URL字符串默认为当前URL
* @returns 主机名
*/
export function getHostname(url = window.location.href) {
const urlObj = new URL(url);
return urlObj.hostname;
}
//# sourceMappingURL=url.js.map