修改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}`); } }
关键注意点
- 保持返回类型:函数仍需返回
Promise<SearchIndex>,原代码后续逻辑依赖该类型结构,不能返回其他类型数据。 - 异常处理:必须处理
sessionStorage.getItem返回null的情况,以及JSON解析失败的场景,避免静默失败。 - 结构验证:可选的结构检查能提前发现存储数据不符合要求的问题,避免后续业务逻辑出现更隐蔽的错误。
内容的提问来源于stack exchange,提问作者Programer Beginner
相关产品推荐
相关产品推荐

