Skip to content
On this page

location

浏览器相关方法

isBrowser

判断当前环境是否为浏览器

函数参数和返回值

js
/**
 * @return {boolean}
 */
展示源码
ts
export function isBrowser(): boolean {
  return typeof Window !== 'undefined' && typeof document !== 'undefined';
}

代码用例

js
const isInBrowser = isBrowser();

parseQuery

获取 location.search 中的 query 值。

内部先将 query 参数转化成键值对形式,再根据接收的 key 找到其对应的 value

函数参数和返回值

js
/**
 * @param {string} key 要获取的值的键
 * @return {string}
 */
展示源码
ts
export function parseQuery<T extends any>(key: string): T | null {
  if (!isBrowser()) {
    return null;
  }

  const queryStr = window.location.search.replace('?', '');
  const queryMap: Record<string, any> = {};

  for (const param of queryStr.split('&')) {
    const [key, value] = param.split('=');
    try {
      queryMap[key] = JSON.parse(value);
    } catch (err) {
      queryMap[key] = value;
    }
  }

  return queryMap[key];
}

代码用例

js
const myId = parseQuery('id');

Released under the MIT License.