包括所有窗口
请问如何通过 api 获得当前所有打开的页签 id
相关帖子
-
没有 api 可以直接获取的,不过可以通过下面的代码获取
(支持已加载的,未加载的,钉住的标签,分屏的标签,总之,所有标签都可以获取,但仅支持当前空间和当前窗口,即新窗口打开的不支持,但,每个新窗口打开都会获取当前窗口的,要想汇总所有窗口,可以使用 localstorage 进行窗口间的汇总即可,要想实时还得监听 localstorage 数据变化)function getTabIds() { return [...window.siyuan.layout.centerLayout.element.querySelectorAll('[data-type="tab-header"]')].map(tab=>{ const protyle = getInstanceById(tab.dataset.id); let rootId = ''; if(protyle.model) { rootId = protyle.model.editor.protyle.block.rootID; } else { const initData = protyle.headElement.getAttribute("data-initdata"); if (initData) { const initDataObj = JSON.parse(initData); if (initDataObj && initDataObj.instance === "Editor") { rootId = initDataObj.rootId || initDataObj.blockId; } } } return rootId; }); function getInstanceById(id, layout = window.siyuan.layout.centerLayout) { const _getInstanceById = (item, id) => { if (item.id === id) return item; if (!item.children) return; let ret; for (let i = 0; i < item.children.length; i++) { ret = _getInstanceById(item.children[i], id); if (ret) return ret; } }; return _getInstanceById(layout, id); } }
1 回复 -
-
-
这涉及到多窗口通信问题,最简单的方式是使用 localStorage 监听通信,比如把下面的代码添加到之前代码的任意地方即可
然后调用 await getAllWindowTabIds()即可
当然更好的方式是用 postMessage
这里还可以优化,比如监听可分为 request 和 response 两个,这样就不用 setTimeout 了,时效性更强。
// 获取所有窗口标签id async function getAllWindowTabIds(delay = 100) { const keyPrefix = '__all_window_tab_ids_'; const noticeKey = keyPrefix + 'notice'; const dataKeyPrefix = keyPrefix + 'data_'; const dataKey = dataKeyPrefix + window.siyuan.ws.app.appId; // 更新数据 const tabIds = getTabIds(); localStorage.setItem(noticeKey, performance.now()); localStorage.setItem(dataKey, JSON.stringify(tabIds)); await new Promise(resolve => setTimeout(resolve, delay)); // 获取所有数据 const keys = Object.keys(localStorage).filter(key => key.startsWith(dataKeyPrefix)); let allTabIds = []; if(keys.length > 0) { for(const key of keys) { let value = localStorage[key]; if(!value) continue; value = JSON.parse(value); if(value.length === 0) continue; localStorage.removeItem(key); allTabIds = [...allTabIds, ...value]; } } // allTabIds = [...new Set(allTabIds)]; // 去重 return allTabIds; } // 监听tab数据变化 if(!window.__hasListenedStorage) { window.__hasListenedStorage = true; const keyPrefix = '__all_window_tab_ids_'; const noticeKey = keyPrefix + 'notice'; const dataKeyPrefix = keyPrefix + 'data_'; const dataKey = dataKeyPrefix + window.siyuan.ws.app.appId; if(!localStorage.getItem(noticeKey)) localStorage.setItem(noticeKey, performance.now()); window.addEventListener('storage', function (event) { if (event.key === noticeKey) { const tabIds = getTabIds(); localStorage.setItem(dataKey, JSON.stringify(tabIds)); } }); }
1 操作wilsons 在 2025-05-28 10:41:40 更新了该回帖
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于