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.78
  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. //Capture content from .photo-question
  48. let photoQuestionElement = docClone.querySelector('.solution.container .photo-question');
  49. let photoQuestion = photoQuestionElement ? photoQuestionElement.outerHTML : '';
  50. console.log("Photo Question HTML:", photoQuestion);
  51. let questionField = docClone.querySelector('form.question h3')?.innerText.trim() || '';
  52. console.log("Question Field:", questionField);
  53. let optionField = Array.from(docClone.querySelectorAll('.options .option'))
  54. .map(option => option.innerText.trim())
  55. .filter(text => text)
  56. .map(text => `<li>${text}</lis>`)
  57. .join('') || '';
  58. console.log("Option Field:", optionField);
  59. let backField = Array.from(docClone.querySelectorAll('.options .option.correct'))
  60. .map(option => option.innerText.trim())
  61. .filter(text => text)
  62. .map(text => `<li>${text}</li>`)
  63. .join('') || '';
  64. console.log("Answer Field:", backField);
  65. //let extraField = docClone.querySelector('.results.container.collected .feedback-container .text')?.innerText.trim() || '';
  66. //console.log("Additional Info Field:", extraField);
  67. let extraElement = docClone.querySelector('.results.container.collected .feedback-container .text');
  68. let extraField = extraElement ? extraElement.innerHTML : '';
  69. let extraFieldText = docClone.querySelector('.results.container.collected .feedback-container .text')?.innerText.trim() || '';
  70. console.log("Additional Info Field:", extraField);
  71. let webpageURL = window.location.href;
  72. console.log("Tag:", webpageURL);
  73. // Generate uniqueID
  74. let uniqueID = generateRandomID ? generateRandomString(10) : questionField.concat(backField).concat(extraField).concat(photoQuestion);
  75. // Create the note fields
  76. let noteFields = {
  77. "Front": frontField.concat("<br>").concat(photoQuestion),
  78. "Question": questionField,
  79. "Options": '<div class="psol">'.concat(optionField).concat("</div>"),
  80. "Back": '<div class="psol">'.concat(backField).concat("</div>"),
  81. "Feedback": extraFieldText,
  82. "Extra": extraField,
  83. "Link": "<a href=".concat(webpageURL).concat(">Link To Card</a>"),
  84. "UniqueID": uniqueID
  85. };
  86. console.log("Note fields to be sent to Anki:", noteFields);
  87. GM_xmlhttpRequest({
  88. method: "POST",
  89. url: "http://localhost:8765",
  90. data: JSON.stringify({
  91. "action": "addNote",
  92. "version": 6,
  93. "params": {
  94. "note": {
  95. "deckName": "Default",
  96. "modelName": "uofcCard",
  97. "fields": noteFields,
  98. "tags": [webpageURL]
  99. }
  100. }
  101. }),
  102. headers: {
  103. "Content-Type": "application/json"
  104. },
  105. onload: function(response) {
  106. console.log("Response from AnkiConnect:", response);
  107. if (response.status === 200) {
  108. console.log("Note fields sent to Anki successfully!");
  109. } else {
  110. console.error("Failed to send note fields to Anki.");
  111. }
  112. }
  113. });
  114. }
  115. // Add event listener for the keyboard shortcut (Ctrl+Shift+Y)
  116. document.addEventListener('keydown', function(event) {
  117. if (event.ctrlKey && event.shiftKey && event.code === 'KeyY') {
  118. copyHtmlToAnki();
  119. }
  120. });
  121. // Register the menu command to Tampermonkey menu
  122. GM_registerMenuCommand("Copy HTML to Anki", function() { copyHtmlToAnki(false); });
  123. GM_registerMenuCommand("Copy HTML to Anki with Random ID", function() { copyHtmlToAnki(true); });
  124. })();