Copy HTML to Anki

Copy specific parts of HTML text and send them to Anki, converting relative URLs to absolute URLs. Trigger with Ctrl+Shift+Y or via Tampermonkey menu.

当前为 2024-08-20 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Copy HTML to Anki
  3. // @namespace http://tampermonkey.net/
  4. // @version 4.76
  5. // @description Copy specific parts of HTML text and send them to Anki, converting relative URLs to absolute URLs. Trigger with Ctrl+Shift+Y or via Tampermonkey menu.
  6. // @author nabe
  7. // @match *://*/*
  8. // @grant GM_xmlhttpRequest
  9. // @grant GM_registerMenuCommand
  10. // @connect localhost
  11. // @run-at document-end
  12. // @license MIT
  13. // ==/UserScript==
  14. (function() {
  15. 'use strict';
  16. function copyHtmlToAnki() {
  17. // Function to convert relative URLs to absolute URLs
  18. function makeAbsolute(url) {
  19. return new URL(url, document.baseURI).href;
  20. }
  21. // Clone the document to manipulate it
  22. let docClone = document.documentElement.cloneNode(true);
  23. // Convert all relative URLs to absolute URLs
  24. let elements = docClone.querySelectorAll('[src], [href]');
  25. elements.forEach(function(element) {
  26. if (element.hasAttribute('src')) {
  27. element.setAttribute('src', makeAbsolute(element.getAttribute('src')));
  28. }
  29. if (element.hasAttribute('href')) {
  30. element.setAttribute('href', makeAbsolute(element.getAttribute('href')));
  31. }
  32. });
  33. // Extract the text content of specific parts needed
  34. let frontElement = docClone.querySelector('.container.card');
  35. let frontField = frontElement ? frontElement.innerHTML : '';
  36. let frontFieldText = frontElement ? frontElement.textContent.trim() : '';
  37. console.log("Front Field:", frontField);
  38.  
  39. //Capture content from .photo-question
  40. let photoQuestionElement = docClone.querySelector('.solution.container .photo-question');
  41. let photoQuestion = photoQuestionElement ? photoQuestionElement.outerHTML : '';
  42. console.log("Photo Question HTML:", photoQuestion);
  43.  
  44. let questionField = docClone.querySelector('form.question h3')?.innerText.trim() || '';
  45. console.log("Question Field:", questionField);
  46. let optionField = Array.from(docClone.querySelectorAll('.options .option'))
  47. .map(option => option.innerText.trim())
  48. .filter(text => text)
  49. .map(text => `<li>${text}</lis>`)
  50. .join('') || '';
  51. console.log("Option Field:", optionField);
  52. let backField = Array.from(docClone.querySelectorAll('.options .option.correct'))
  53. .map(option => option.innerText.trim())
  54. .filter(text => text)
  55. .map(text => `<li>${text}</li>`)
  56. .join('') || '';
  57. console.log("Answer Field:", backField);
  58. //let extraField = docClone.querySelector('.results.container.collected .feedback-container .text')?.innerText.trim() || '';
  59. //console.log("Additional Info Field:", extraField);
  60. let extraElement = docClone.querySelector('.results.container.collected .feedback-container .text');
  61. let extraField = extraElement ? extraElement.innerHTML : '';
  62. let extraFieldText = docClone.querySelector('.results.container.collected .feedback-container .text')?.innerText.trim() || '';
  63. console.log("Additional Info Field:", extraField);
  64.  
  65. let webpageURL = window.location.href;
  66. console.log("Tag:", webpageURL);
  67. // Create the note fields
  68. let noteFields = {
  69. "Front": frontField.concat("<br>").concat(photoQuestion),
  70. "Question": questionField,
  71. "Options": '<div class="psol">'.concat(optionField).concat("</div>"),
  72. "Back": '<div class="psol">'.concat(backField).concat("</div>"),
  73. "Feedback": extraFieldText,
  74. "Extra": extraField,
  75. "Link": "<a href=".concat(webpageURL).concat(">Link To Card</a>"),
  76. "UniqueID": questionField.concat(backField).concat(extraField).concat(photoQuestion)
  77. };
  78. console.log("Note fields to be sent to Anki:", noteFields);
  79. GM_xmlhttpRequest({
  80. method: "POST",
  81. url: "http://localhost:8765",
  82. data: JSON.stringify({
  83. "action": "addNote",
  84. "version": 6,
  85. "params": {
  86. "note": {
  87. "deckName": "Default",
  88. "modelName": "uofcCard",
  89. "fields": noteFields,
  90. "tags": [webpageURL]
  91. }
  92. }
  93. }),
  94. headers: {
  95. "Content-Type": "application/json"
  96. },
  97. onload: function(response) {
  98. console.log("Response from AnkiConnect:", response);
  99. if (response.status === 200) {
  100. console.log("Note fields sent to Anki successfully!");
  101. } else {
  102. console.error("Failed to send note fields to Anki.");
  103. }
  104. }
  105. });
  106. }
  107. // Add event listener for the keyboard shortcut (Ctrl+Shift+Y)
  108. document.addEventListener('keydown', function(event) {
  109. if (event.ctrlKey && event.shiftKey && event.code === 'KeyY') {
  110. copyHtmlToAnki();
  111. }
  112. });
  113. // Register the menu command to Tampermonkey menu
  114. GM_registerMenuCommand("Copy HTML to Anki", copyHtmlToAnki);
  115. })();