You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

修改TypeScript函数从Session Storage获取搜索索引JSON数据

修改mkdocs-material的fetchSearchIndex函数从Session Storage读取搜索索引

背景

mkdocs-material的bundle.ts中,原fetchSearchIndex()函数会根据协议从search_index.js或search_index.json文件拉取符合SearchIndex接口的搜索索引数据,该接口包含config、docs、options三个字段,JSON结构明确。

需求

修改该函数,不再从JSON文件获取数据,改为从Session Storage中键为search-index的位置读取JSON数据。

错误分析

你遇到的index.ts:99 Uncaught (in promise) TypeError: r.location.split is not a function or its return value is not iterable错误,本质是修改后的函数没有保持原函数的返回类型与数据结构。原函数返回解析后的SearchIndex对象,而你的代码可能错误返回了类似fetch响应对象的结构,或直接返回未解析的字符串,导致后续代码试图调用location.split这类响应对象专属方法,从而触发报错。

正确修改方案

需保证函数返回符合Promise<SearchIndex>类型的结果,同时处理Session Storage数据不存在、JSON解析失败的场景,具体修改如下:

修改后的代码

async function fetchSearchIndex(): Promise<SearchIndex> {
  // 从Session Storage获取存储的索引字符串
  const storedIndex = sessionStorage.getItem('search-index');
  
  // 处理数据不存在的情况
  if (!storedIndex) {
    throw new Error('Session Storage中未找到搜索索引数据');
  }

  try {
    // 解析JSON并断言为SearchIndex类型
    const searchIndex = JSON.parse(storedIndex) as SearchIndex;

    // 可选:验证数据结构是否符合要求,避免后续逻辑出错
    if (!searchIndex.config || !searchIndex.docs || !searchIndex.options) {
      throw new Error('Session Storage中的搜索索引结构不完整');
    }

    return searchIndex;
  } catch (error) {
    throw new Error(`加载搜索索引失败: ${(error as Error).message}`);
  }
}

关键注意点

  1. 保持返回类型:函数仍需返回Promise<SearchIndex>,原代码后续逻辑依赖该类型结构,不能返回其他类型数据。
  2. 异常处理:必须处理sessionStorage.getItem返回null的情况,以及JSON解析失败的场景,避免静默失败。
  3. 结构验证:可选的结构检查能提前发现存储数据不符合要求的问题,避免后续业务逻辑出现更隐蔽的错误。

内容的提问来源于stack exchange,提问作者Programer Beginner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 01:42:10