Repository navigation
Expand file tree
/
Copy pathexport-monknow.js
More file actions
473 lines (416 loc) · 15.7 KB
/
Copy pathexport-monknow.js
File metadata and controls
473 lines (416 loc) · 15.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
/**
* ========================================================================
* Monknow 新标签页 - 书签导出脚本
* MONKNOW New Tab - Bookmark Export Script
* ========================================================================
*
* 功能:
* 1. 读取 Monknow 扩展中储存的所有收藏数据
* 2. 按原有分组(树形结构)整理
* 3. 导出为标准的 Netscape 书签 HTML 格式(Edge / Chrome 均可导入)
*
* 使用方法:
* 1. 打开 Edge/Chrome 的新标签页,确保显示的是 Monknow 扩展页面
* 2. 按 F12 打开开发者工具
* 3. 切换到 "Console"(控制台)选项卡
* 4. 将本脚本的全部代码粘贴到控制台中,按 Enter 执行
* 5. 脚本会自动下载书签文件: monknow-bookmarks.html
* 6. 在 Edge 的收藏夹管理器中导入该文件即可
*
* 原理说明:
* Monknow 使用 chrome.storage.local 存储数据,数据存放在 iconsStore 键下:
* - iconsStore.data.iconDict → 所有书签项(含 URL、标题等)
* - iconsStore.data.groupDict → 分组/文件夹定义(含分组名、成员)
* - iconsStore.data.groups → 分组的有序列表
*
* ========================================================================
*/
;(async function () {
'use strict'
function getConfig() {
return {
filename: 'monknow-bookmarks.html',
rootFolderName: 'monkonw-' + nowISO(),
timestamp: nowISO(),
}
}
function isExtensionPage() {
return (
window.location.protocol === 'chrome-extension:' ||
window.location.protocol === 'edge-extension:' ||
window.location.protocol === 'moz-extension:' ||
window.location.href.startsWith('chrome-extension://') ||
window.location.href.startsWith('edge-extension://') ||
window.location.href.startsWith('moz-extension://')
)
}
/** 休眠(用于让浏览器 UI 有时间更新) */
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms))
}
function nowISO() {
return new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19)
}
function escapeHtml(str) {
if (!str) return ''
return String(str)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
}
/**
* 安全地读取 chrome.storage (local + sync)
* 使用 Promise.all + 超时兜底,避免任何一个 storage 挂死
*/
async function readAllStorage() {
const results = { local: {}, sync: {} }
const STORAGE_TIMEOUT = 15000
try {
const localPromise = new Promise((resolve) => {
chrome.storage.local.get(null, (data) => {
if (chrome.runtime.lastError) {
console.warn('[警告] chrome.storage.local.get 错误:', chrome.runtime.lastError.message)
resolve({})
return
}
resolve(data || {})
})
})
results.local = await Promise.race([
localPromise,
sleep(STORAGE_TIMEOUT).then(() => {
console.warn('[警告] chrome.storage.local.get 超时,使用空数据')
return {}
}),
])
} catch (e) {
console.warn('[警告] 读取 chrome.storage.local 失败:', e.message)
}
try {
const syncPromise = new Promise((resolve) => {
chrome.storage.sync.get(null, (data) => {
if (chrome.runtime.lastError) {
console.warn('[警告] chrome.storage.sync.get 错误:', chrome.runtime.lastError.message)
resolve({})
return
}
resolve(data || {})
})
})
results.sync = await Promise.race([
syncPromise,
sleep(STORAGE_TIMEOUT).then(() => {
console.warn('[警告] chrome.storage.sync.get 超时,使用空数据')
return {}
}),
])
} catch (e) {
console.warn('[警告] 读取 chrome.storage.sync 失败:', e.message)
}
return results
}
/**
* 从原始 storage 数据中提取书签树
* 返回: { name, children: [bookmark | folder] }
*/
function parseMonknowBookmarks(storageData) {
const possibleKeys = [
'iconsStore',
'monknowIcons',
'icons',
'speedDial',
'sites',
'bookmarks',
]
let raw = null
let matchedKey = null
for (const key of possibleKeys) {
if (storageData.local && storageData.local[key]) {
raw = storageData.local[key]
matchedKey = key
console.log(`[信息] 在 storage.local 中找到数据键: "${key}"`)
break
}
if (storageData.sync && storageData.sync[key]) {
raw = storageData.sync[key]
matchedKey = key
console.log(`[信息] 在 storage.sync 中找到数据键: "${key}"`)
break
}
}
if (!raw) {
console.log('[信息] 未在已知键名中找到数据,正在全量扫描 storage...')
for (const [key, value] of Object.entries(storageData.local)) {
if (
value &&
typeof value === 'object' &&
(value.data || value.iconDict || value.groupDict)
) {
raw = value
matchedKey = key
console.log(`[信息] 通过扫描发现数据键: "${key}"`)
break
}
}
}
if (!raw) {
console.error('[错误] 未能在 storage 中找到 Monknow 书签数据')
console.log('[诊断] storage.local 的键名列表:', Object.keys(storageData.local))
console.log('[诊断] storage.sync 的键名列表:', Object.keys(storageData.sync))
return null
}
// 获取实际的数据对象(兼容 { data: { ... } } 和直接存储的情况)
let data = raw.data || raw
const iconDict = data.iconDict || data.icons || data.items || {}
const groupDict = data.groupDict || data.groups || data.folders || {}
const groupsOrder = data.groups || data.groupOrder || data.folderOrder || []
// 如果 groupsOrder 是数组,直接使用;如果是对象,取其键
const orderedGroupKeys = Array.isArray(groupsOrder)
? groupsOrder
: Object.keys(groupDict)
const iconCount = Object.keys(iconDict).length
const groupCount = Object.keys(groupDict).length
console.log(`[信息] 解析结果: ${groupCount} 个分组, ${iconCount} 个书签项`)
const tree = {
name: getConfig().rootFolderName,
type: 'folder',
children: [],
}
if (groupCount > 0) {
for (const groupKey of orderedGroupKeys) {
const group = groupDict[groupKey]
if (!group) continue
const folder = {
name: group.label || group.name || group.title || '(未命名分组)',
type: 'folder',
children: [],
}
const iconIds = group.data || group.icons || group.items || group.children || []
for (const iconId of iconIds) {
const icon = iconDict[iconId]
if (!icon) continue
const url = icon.url || icon.link || icon.href
if (!url || url === '' || url.startsWith('chrome-extension://')) continue
folder.children.push({
type: 'bookmark',
name: icon.label || icon.title || icon.name || url,
url: url,
})
}
if (folder.children.length > 0) {
tree.children.push(folder)
}
}
const allGroupedIds = new Set()
for (const groupKey of orderedGroupKeys) {
const group = groupDict[groupKey]
if (group && group.data) {
for (const id of group.data) allGroupedIds.add(id)
}
}
const ungroupedIcons = Object.entries(iconDict).filter(
([id]) => !allGroupedIds.has(id)
)
if (ungroupedIcons.length > 0) {
const ungroupedFolder = {
name: '未分类',
type: 'folder',
children: [],
}
for (const [, icon] of ungroupedIcons) {
const url = icon.url || icon.link || icon.href
if (!url || url === '' || url.startsWith('chrome-extension://')) continue
ungroupedFolder.children.push({
type: 'bookmark',
name: icon.label || icon.title || icon.name || url,
url: url,
})
}
if (ungroupedFolder.children.length > 0) {
tree.children.push(ungroupedFolder)
console.log(`[信息] 发现 ${ungroupedFolder.children.length} 个未分类书签`)
}
}
} else {
for (const [, icon] of Object.entries(iconDict)) {
const url = icon.url || icon.link || icon.href
if (!url || url === '' || url.startsWith('chrome-extension://')) continue
tree.children.push({
type: 'bookmark',
name: icon.label || icon.title || icon.name || url,
url: url,
})
}
}
return tree
}
function renderBookmarkTree(node, indent = '') {
if (node.type === 'bookmark') {
const escapedName = escapeHtml(node.name)
const escapedUrl = escapeHtml(node.url)
return `${indent}<DT><A HREF="${escapedUrl}">${escapedName}</A>\n`
}
if (node.type === 'folder') {
const escapedName = escapeHtml(node.name)
let html = `${indent}<DT><H3>${escapedName}</H3>\n`
html += `${indent}<DL><p>\n`
for (const child of node.children) {
html += renderBookmarkTree(child, indent + ' ')
}
html += `${indent}</DL><p>\n`
return html
}
return ''
}
function generateBookmarkHTML(tree) {
let html = `<!DOCTYPE NETSCAPE-Bookmark-file-1>
<!-- This is an automatically generated file.
It will be read and overwritten.
DO NOT EDIT! -->
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
<TITLE>Monknow Bookmarks</TITLE>
<H1>${escapeHtml(CONFIG.rootFolderName)}</H1>
<DL><p>
`
for (const child of tree.children) {
html += renderBookmarkTree(child, ' ')
}
html += `</DL><p>
`
return html
}
function downloadFile(content, filename, mimeType = 'text/html') {
const blob = new Blob([content], { type: `${mimeType};charset=utf-8` })
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = filename
a.style.display = 'none'
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
// 延迟释放 URL
setTimeout(() => URL.revokeObjectURL(url), 10000)
console.log(`[完成] 文件已下载: ${filename}`)
}
const CONFIG = getConfig()
console.log('')
console.log('╔══════════════════════════════════════════════════════╗')
console.log('║ Monknow 新标签页 - 书签导出工具 v2.0 ║')
console.log('╚══════════════════════════════════════════════════════╝')
console.log('')
// 步骤 1: 检查运行环境
console.log('[步骤 1/5] 检查运行环境...')
if (typeof chrome === 'undefined' || !chrome.storage) {
console.error('[错误] 未检测到 chrome.storage API!')
console.error('原因: 脚本需要在 Monknow 扩展页面(新标签页)中运行。')
console.error('请按以下步骤操作:')
console.error(' 1. 打开 Edge/Chrome/Firefox 的新标签页(必须显示 Monknow 界面)')
console.error(' 2. 按 F12 打开开发者工具')
console.error(' 3. 切换到 Console 选项卡')
console.error(' 4. 粘贴本脚本并执行')
return
}
if (!isExtensionPage()) {
console.warn('[警告] 当前页面不是扩展页面(URL:', window.location.href, ')')
console.warn('如果后续读取失败,请确保在 Monknow 新标签页中运行本脚本。')
} else {
console.log('[信息] 当前页面:', window.location.href)
}
// 步骤 2: 读取所有 storage 数据
console.log('')
console.log('[步骤 2/5] 读取 chrome.storage 数据...')
const storageData = await readAllStorage()
const localKeys = Object.keys(storageData.local)
const syncKeys = Object.keys(storageData.sync)
console.log(`[信息] storage.local 包含 ${localKeys.length} 个键:`, localKeys)
console.log(`[信息] storage.sync 包含 ${syncKeys.length} 个键:`, syncKeys)
// 步骤 3: 解析书签数据
console.log('')
console.log('[步骤 3/5] 解析书签数据...')
const bookmarkTree = parseMonknowBookmarks(storageData)
if (!bookmarkTree) {
console.error('')
console.error('[错误] 无法解析书签数据!')
console.log('')
console.log('=== 诊断信息 ===')
console.log('[诊断] 导出原始 storage 数据以便分析...')
const rawDump = JSON.stringify(
{
timestamp: nowISO(),
url: window.location.href,
localKeys,
syncKeys,
localData: storageData.local,
syncData: storageData.sync,
},
null,
2
)
downloadFile(rawDump, `monknow-raw-dump-${nowISO()}.json`, 'application/json')
console.log('[诊断] 原始数据已导出为 monknow-raw-dump-*.json')
console.log('[诊断] 请将此文件提供给开发者进行分析。')
return
}
const summary = countBookmarks(bookmarkTree)
console.log(`[信息] 共解析出 ${summary.folders} 个分组, ${summary.bookmarks} 个书签`)
// 步骤 4: 生成 HTML
console.log('')
console.log('[步骤 4/5] 生成 Netscape 书签 HTML...')
const bookmarkHTML = generateBookmarkHTML(bookmarkTree)
// 步骤 5: 下载文件
console.log('')
console.log('[步骤 5/5] 下载书签文件...')
const filename = `monknow-bookmarks-${nowISO()}.html`
downloadFile(bookmarkHTML, filename)
console.log('')
console.log('=== 导出内容预览 ===')
printTreePreview(bookmarkTree)
console.log('')
console.log('╔══════════════════════════════════════════════════════╗')
console.log('║ 导出完成 ║')
console.log('╚══════════════════════════════════════════════════════╝')
console.log('')
console.log(` 文件名: ${filename}`)
console.log(` 书签数: ${summary.bookmarks}`)
console.log(` 分组数: ${summary.folders}`)
console.log('')
console.log('=== 导入到 Edge 收藏夹 ===')
console.log(' 1. 打开 Edge 浏览器')
console.log(' 2. 点击右上角星标 → "收藏夹"')
console.log(' 3. 点击 "..." (更多选项) → "导入收藏夹"')
console.log(' 4. 选择刚下载的 HTML 文件')
console.log(' 5. 书签将按照原有分组结构导入')
console.log('')
console.log('=== 导入到 Chrome 书签 ===')
console.log(' 1. 打开 Chrome 浏览器')
console.log(' 2. 点击右上角 ⋮ → "书签和列表" → "书签管理器"')
console.log(' 3. 点击 "整理" → "导入书签"')
console.log(' 4. 选择刚下载的 HTML 文件')
console.log('')
function countBookmarks(node) {
let folders = 0
let bookmarks = 0
function walk(n) {
if (n.type === 'folder') {
folders++
for (const child of n.children) walk(child)
} else if (n.type === 'bookmark') {
bookmarks++
}
}
for (const child of node.children) walk(child)
return { folders, bookmarks }
}
function printTreePreview(node, indent = '') {
for (const child of node.children) {
if (child.type === 'folder') {
console.log(`${indent}📁 ${child.name} (${child.children.length} 项)`)
printTreePreview(child, indent + ' ')
} else if (child.type === 'bookmark') {
console.log(`${indent}🔗 ${child.name}`)
}
}
}
})()