2022-09-19 20:05:33
在Chrome调试器中将JS变量保存为本地JSON文件,可通过以下步骤实现:
打开Chrome开发者工具
快捷键:F12 或 Ctrl+Shift+I(Windows/Linux),Cmd+Opt+I(Mac)
右键页面选择“检查”
切换到Console标签页
确保当前处于Console面板,可直接执行JavaScript代码
注入保存功能代码
(function(console){ console.save = function(data, filename){ if(!data) { console.error('Console.save: No data'); return; } if(!filename) filename = 'console.json'; if(typeof data === "object"){ data = JSON.stringify(data, undefined, 4); } var blob = new Blob([data], {type: 'text/json'}), e = document.createEvent('MouseEvents'), a = document.createElement('a'); a.download = filename; a.href = window.URL.createObjectURL(blob); a.dataset.downloadurl = ['text/json', a.download, a.href].join(':'); e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); a.dispatchEvent(e); };})(console);复制上述代码到Console中执行
这会为console对象添加save()方法
保存变量到JSON文件
// 示例:保存页面所有button元素var buttons = $('button'); // 或使用其他选择器console.save(buttons, 'buttons.json');// 保存任意JS对象var myData = {name: "Test", items: [1,2,3]};console.save(myData, 'mydata.json');自动下载文件
执行后浏览器会自动弹出文件保存对话框
选择保存位置即可生成JSON文件
关键点说明:
注意事项:
替代方案:若遇到兼容性问题,可使用以下简化版:
function saveToFile(data, filename) { const json = JSON.stringify(data, null, 2); const blob = new Blob([json], {type: 'application/json'}); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = filename || 'data.json'; a.click(); setTimeout(() => URL.revokeObjectURL(url), 100);}// 使用方式:saveToFile(myVariable, 'filename.json');此方法同样能实现变量保存功能,且代码更简洁易读。