Copy HTML to Anki

Copy entire HTML of a webpage and send it to Anki, converting relative URLs to absolute URLs. Trigger with Ctrl+Shift+Y or via Tampermonkey menu.

当前为 2024-07-10 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Copy HTML to Anki
  3. // @namespace http://tampermonkey.net/
  4. // @version 1.6
  5. // @description Copy entire HTML of a webpage and send it 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.  
  15. (function() {
  16. 'use strict';
  17.  
  18. function copyHtmlToAnki() {
  19. // Function to convert relative URLs to absolute URLs
  20. function makeAbsolute(url) {
  21. return new URL(url, document.baseURI).href;
  22. }
  23.  
  24. // Clone the document to manipulate it
  25. let docClone = document.documentElement.cloneNode(true);
  26.  
  27. // Convert all relative URLs to absolute URLs
  28. let elements = docClone.querySelectorAll('[src], [href]');
  29. elements.forEach(function(element) {
  30. if (element.hasAttribute('src')) {
  31. element.setAttribute('src', makeAbsolute(element.getAttribute('src')));
  32. }
  33. if (element.hasAttribute('href')) {
  34. element.setAttribute('href', makeAbsolute(element.getAttribute('href')));
  35. }
  36. });
  37.  
  38. let htmlContent = docClone.outerHTML;
  39. console.log("HTML content copied with absolute URLs:", htmlContent);
  40.  
  41. GM_xmlhttpRequest({
  42. method: "POST",
  43. url: "http://localhost:8765",
  44. data: JSON.stringify({
  45. "action": "addNote",
  46. "version": 6,
  47. "params": {
  48. "note": {
  49. "deckName": "Default",
  50. "modelName": "htmlcard",
  51. "fields": {
  52. "HTML": htmlContent
  53. },
  54. "tags": ["newimport"]
  55. }
  56. }
  57. }),
  58. headers: {
  59. "Content-Type": "application/json"
  60. },
  61. onload: function(response) {
  62. console.log("Response from AnkiConnect:", response);
  63. if (response.status === 200) {
  64. console.log("HTML content sent to Anki!");
  65. } else {
  66. alert("Failed to send content to Anki.");
  67. }
  68. }
  69. });
  70. }
  71.  
  72. // Add event listener for the keyboard shortcut (Ctrl+Shift+Y)
  73. document.addEventListener('keydown', function(event) {
  74. if (event.ctrlKey && event.shiftKey && event.code === 'KeyY') {
  75. copyHtmlToAnki();
  76. }
  77. });
  78.  
  79. // Register the menu command to Tampermonkey menu
  80. GM_registerMenuCommand("Copy HTML to Anki", copyHtmlToAnki);
  81. })();