chrome插件提取标签数据
本意想把chrome保存的标签拉一个目录保存,可以使用插件直接导出文件,现在实现了数据拼接,导出文件未实现(因为没有new Blob);
目录结构如下;
background.js
// 递归函数,用于构建书签树
function buildBookmarkTree(node) {if (node.children) {const folder = {name: node.title,type: 'folder',children: []};node.children.forEach(child => {folder.children.push(buildBookmarkTree(child));});return folder;} else {return {name: node.title,url: node.url,type: 'bookmark',needLogin: false,loginInfo: {username: '',password: ''}};}
}
// 处理书签导出 是一个异步
async function exportBookmarks(sendResponse) {let bookList = []await chrome.bookmarks.getTree(tree => {const root = tree[0];const bookmarkTree = buildBookmarkTree(root);sendResponse({ status: 'success' ,bookList:[bookmarkTree]});console.log('bookmarkTree',[bookmarkTree]);bookList.concat([bookmarkTree])// const jsonData = JSON.stringify(bookmarkTree, null, 2);// const blob = new Blob([jsonData], { type: 'application/json' });// try{// const url = URL.createObjectURL(blob);// const a = document.createElement('a');// a.href = url;// a.download = 'bookmarks.json';// a.click();// URL.revokeObjectURL(url);// }catch(e){// console.log('bookmarkTree-error',e)// }});console.log('bookList2',bookList);return bookList
}
// 监听来自 popup.js 的消息
chrome.runtime.onMessage.addListener(async (request, sender, sendResponse) => {if (request.action === 'exportBookmarks') {let bookList = await exportBookmarks(sendResponse);console.log('bookList1',bookList)sendResponse({ status: 'success' ,bookList:bookList});}return true;
});
manifest.json
{"manifest_version": 3,"name": "Bookmark Exporter","version": "1.0","description": "Export bookmarks to a JSON file with tree structure and login info","action": {"default_popup": "popup.html","default_icon": {"16": "icon16.png","32": "icon16.png"}},"permissions": ["bookmarks"],"background": {"service_worker": "background.js"}
}
popup.html
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Bookmark Exporter</title>
</head><body><button id="exportButton">保存书签</button><script src="popup.js"></script>
</body></html>
popup.js
document.addEventListener('DOMContentLoaded', () => {const exportButton = document.getElementById('exportButton');exportButton.addEventListener('click', () => {chrome.runtime.sendMessage({ action: 'exportBookmarks' }, response => {console.log('response',response)if (response.status === 'success') {const jsonData = JSON.stringify(response.bookList, null, 2);const blob = new Blob([jsonData], { type: 'application/json' });try{const url = URL.createObjectURL(blob);const a = document.createElement('a');a.href = url;a.download = 'bookmarks.json';a.click();URL.revokeObjectURL(url);}catch(e){console.log('bookmarkTree-error',e)}console.log('Bookmarks exported successfully');}else{}});});
});