导入导出聊天记录.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. // ==UserScript==
  2. // @name 导入导出聊天记录
  3. // @namespace http://tampermonkey.net/
  4. // @version 0.1
  5. // @description 使用Ctrl+S、Ctrl+L导入导出聊天记录
  6. // @author lyyyyy
  7. // @match http://127.0.0.1:17860/
  8. // @icon https://www.google.com/s2/favicons?sz=64&domain=0.1
  9. // @run-at document-idle
  10. // @grant none
  11. // ==/UserScript==
  12. document.addEventListener('keydown', async function (e) {
  13. if (e.key.toLowerCase() == 's' && (navigator.platform.match("Mac") ? e.metaKey : e.ctrlKey)) {
  14. e.preventDefault();
  15. f另存为聊天记录(JSON.stringify(app.chat))
  16. alert('saved');
  17. }
  18. if (e.key.toLowerCase() == 'l' && (navigator.platform.match("Mac") ? e.metaKey : e.ctrlKey)) {
  19. e.preventDefault();
  20. app.chat = JSON.parse(await f打开聊天记录())
  21. alert('loaded');
  22. }
  23. });
  24. f另存为聊天记录 = (stringData) => {
  25. const blob = new Blob([stringData], {
  26. type: "text/plain;charset=utf-8"
  27. })
  28. const objectURL = URL.createObjectURL(blob)
  29. const aTag = document.createElement('a')
  30. aTag.href = objectURL
  31. aTag.download = Date.now() + "-聊天记录.json"
  32. aTag.click()
  33. URL.revokeObjectURL(objectURL)
  34. }
  35. f打开聊天记录 = async () => {
  36. let contents = ''
  37. await new Promise(resolve => {
  38. let input = document.createElement('input')
  39. input.type = 'file'
  40. input.accept = '.json'
  41. input.onchange = function () {
  42. var file = input.files[0];
  43. var reader = new FileReader();
  44. reader.onload = function (e) {
  45. contents = e.target.result;
  46. resolve()
  47. };
  48. reader.readAsText(file);
  49. }
  50. input.click()
  51. })
  52. return contents
  53. }
粤ICP备19079148号