包括所有窗口
请问如何通过 api 获得当前所有打开的页签 id
相关帖子
- 其他回帖
-
这涉及到多窗口通信问题,最简单的方式是使用 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 更新了该回帖 - 查看全部回帖
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于