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