GitHub NBViewer Transfer

Add buttons to open the current GitHub notebook in NBViewer and return from NBViewer to GitHub.

  1. // ==UserScript==
  2. // @name GitHub NBViewer Transfer
  3. // @namespace yuhuangmeng
  4. // @version 1.0.0
  5. // @description Add buttons to open the current GitHub notebook in NBViewer and return from NBViewer to GitHub.
  6. // @author yuhuangmeng
  7. // @homepageURL https://greatest.deepsurf.us/zh-CN/users/1065289-yuhuangmeng
  8. // @match https://github.com/*
  9. // @match https://nbviewer.org/github/*
  10. // @grant none
  11. // @license MIT
  12. // ==/UserScript==
  13.  
  14. /**
  15. * TODO:
  16. * 1. 将两个按钮合并为一个按钮“Github/NBViewer Switcher”, 但在 github.com的点击按钮的功能是打开 nbviewer,在 nbviewer 网站按钮的功能是打开 github 仓库
  17. * 2. debug
  18. */
  19.  
  20.  
  21. (function() {
  22. 'use strict';
  23.  
  24. // Function to get the current GitHub notebook URL
  25. function getGitHubURL() {
  26. const currentURL = window.location.href;
  27. if (currentURL.includes("github.com")) {
  28. return currentURL;
  29. }
  30. const parts = currentURL.split("/");
  31. const username = parts[parts.indexOf("github") + 1];
  32. const repo = parts[parts.indexOf("github") + 2];
  33. return `https://github.com/${username}/${repo}`;
  34. }
  35.  
  36. // Function to add a button
  37. function addButton(text, onClick) {
  38. const button = document.createElement("a");
  39. button.innerHTML = text;
  40. button.className = "btn btn-sm";
  41. button.href = "#";
  42. button.style.marginRight = "10px";
  43. button.onclick = onClick;
  44. return button;
  45. }
  46.  
  47. // Create a button to open in NBViewer
  48. const nbviewerButton = addButton("Open in NBViewer", function() {
  49. const notebookURL = getNotebookURL();
  50. window.open(notebookURL, "_blank");
  51. });
  52.  
  53. // Create a button to return to GitHub
  54. const githubButton = addButton("Return to GitHub", function() {
  55. const githubURL = getGitHubURL();
  56. window.open(githubURL, "_blank");
  57. });
  58.  
  59. // Create a container div for the buttons
  60. const buttonContainer = document.createElement("div");
  61. buttonContainer.appendChild(nbviewerButton);
  62. buttonContainer.appendChild(githubButton);
  63.  
  64. // Add styles for positioning the button container
  65. buttonContainer.style.position = "fixed";
  66. buttonContainer.style.bottom = "10px";
  67. buttonContainer.style.right = "10px";
  68. buttonContainer.style.zIndex = "9999";
  69.  
  70. // Add the button container to the document body
  71. document.body.appendChild(buttonContainer);
  72.  
  73. // Function to get the current GitHub notebook URL
  74. function getNotebookURL() {
  75. const currentURL = window.location.href;
  76. const notebookURL = currentURL.replace("github.com", "nbviewer.org/github");
  77. return notebookURL;
  78. }
  79. })();