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-11-07 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Copy HTML to Anki
  3. // @namespace http://tampermonkey.net/
  4. // @version 4.79
  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(generateRandomID = false) {
  17. // Function to convert relative URLs to absolute URLs
  18. function makeAbsolute(url) {
  19. return new URL(url, document.baseURI).href;
  20. }
  21.  
  22.  
  23. // Function to generate a random string of numbers
  24. function generateRandomString(length) {
  25. let result = '';
  26. const characters = '0123456789';
  27. for (let i = 0; i < length; i++) {
  28. result += characters.charAt(Math.floor(Math.random() * characters.length));
  29. }
  30. return result;
  31. }
  32. // Clone the document to manipulate it
  33. let docClone = document.documentElement.cloneNode(true);
  34. // Convert all relative URLs to absolute URLs
  35. let elements = docClone.querySelectorAll('[src], [href]');
  36. elements.forEach(function(element) {
  37. if (element.hasAttribute('src')) {
  38. element.setAttribute('src', makeAbsolute(element.getAttribute('src')));
  39. }
  40. if (element.hasAttribute('href')) {
  41. element.setAttribute('href', makeAbsolute(element.getAttribute('href')));
  42. }
  43. });
  44. // Extract the text content of specific parts needed
  45. let frontElement = docClone.querySelector('.container.card');
  46. let frontField = frontElement ? frontElement.innerHTML : '';
  47. let frontFieldText = frontElement ? frontElement.textContent.trim() : '';
  48. console.log("Front Field:", frontField);
  49. // Capture image URLs, ignoring SVGs
  50. let imageUrls = Array.from(frontElement.querySelectorAll('img'))
  51. .map(img => img.getAttribute('src'))
  52. .filter(src => src && !src.includes('.svg') && src !== 'Front Image');
  53. console.log("Image URLs:", imageUrls);
  54.  
  55. //Capture content from .photo-question
  56. let photoQuestionElement = docClone.querySelector('.solution.container .photo-question');
  57. let photoQuestion = photoQuestionElement ? photoQuestionElement.outerHTML : '';
  58. console.log("Photo Question HTML:", photoQuestion);
  59.  
  60. let questionField = docClone.querySelector('form.question h3')?.innerText.trim() || '';
  61. console.log("Question Field:", questionField);
  62. let optionField = Array.from(docClone.querySelectorAll('.options .option'))
  63. .map(option => option.innerText.trim())
  64. .filter(text => text)
  65. .map(text => `<li>${text}</lis>`)
  66. .join('') || '';
  67. console.log("Option Field:", optionField);
  68. let backField = Array.from(docClone.querySelectorAll('.options .option.correct'))
  69. .map(option => option.innerText.trim())
  70. .filter(text => text)
  71. .map(text => `<li>${text}</li>`)
  72. .join('') || '';
  73. console.log("Answer Field:", backField);
  74. //let extraField = docClone.querySelector('.results.container.collected .feedback-container .text')?.innerText.trim() || '';
  75. //console.log("Additional Info Field:", extraField);
  76. let extraElement = docClone.querySelector('.results.container.collected .feedback-container .text');
  77. let extraField = extraElement ? extraElement.innerHTML : '';
  78. let extraFieldText = docClone.querySelector('.results.container.collected .feedback-container .text')?.innerText.trim() || '';
  79. console.log("Additional Info Field:", extraField);
  80.  
  81. let webpageURL = window.location.href;
  82. console.log("Tag:", webpageURL);
  83. // Generate uniqueID
  84. let uniqueID = generateRandomID ? generateRandomString(10) : questionField.concat(backField).concat(extraField).concat(photoQuestion);
  85. // Create the note fields
  86. let noteFields = {
  87. "Front": frontField.concat("<br>").concat(photoQuestion),
  88. "Question": questionField,
  89. "Options": '<div class="psol">'.concat(optionField).concat("</div>"),
  90. "Back": '<div class="psol">'.concat(backField).concat("</div>"),
  91. "Feedback": extraFieldText,
  92. "Extra": extraField,
  93. "Link": "<a href=".concat(webpageURL).concat(">Link To Card</a>"),
  94. "UniqueID": uniqueID,
  95. "Front Image": imageUrls.join('<br>')
  96. };
  97. console.log("Note fields to be sent to Anki:", noteFields);
  98. GM_xmlhttpRequest({
  99. method: "POST",
  100. url: "http://localhost:8765",
  101. data: JSON.stringify({
  102. "action": "addNote",
  103. "version": 6,
  104. "params": {
  105. "note": {
  106. "deckName": "Default",
  107. "modelName": "uofcCard",
  108. "fields": noteFields,
  109. "tags": [webpageURL]
  110. }
  111. }
  112. }),
  113. headers: {
  114. "Content-Type": "application/json"
  115. },
  116. onload: function(response) {
  117. console.log("Response from AnkiConnect:", response);
  118. if (response.status === 200) {
  119. console.log("Note fields sent to Anki successfully!");
  120. } else {
  121. console.error("Failed to send note fields to Anki.");
  122. }
  123. }
  124. });
  125. }
  126. // Add event listener for the keyboard shortcut (Ctrl+Shift+Y)
  127. document.addEventListener('keydown', function(event) {
  128. if (event.ctrlKey && event.shiftKey && event.code === 'KeyY') {
  129. copyHtmlToAnki();
  130. }
  131. });
  132. // Register the menu command to Tampermonkey menu
  133. GM_registerMenuCommand("Copy HTML to Anki", function() { copyHtmlToAnki(false); });
  134. GM_registerMenuCommand("Copy HTML to Anki with Random ID", function() { copyHtmlToAnki(true); });
  135. })();