|
1 | 1 | // ==UserScript==
|
2 | 2 | // @name GitHub PR Diff Button
|
3 | 3 | // @namespace http://tampermonkey.net/
|
4 |
| -// @version 1.0 |
| 4 | +// @version 1.1 |
5 | 5 | // @description Adds a button to view PR diff in new tab
|
6 | 6 | // @author Siew Kam Onn
|
7 | 7 | // @match https://github.com/*/pull/*
|
|
12 | 12 | (function () {
|
13 | 13 | "use strict";
|
14 | 14 |
|
| 15 | + /** |
| 16 | + * Adds a "View Diff" button next to the Code button in GitHub PR pages |
| 17 | + * @returns {void} |
| 18 | + */ |
15 | 19 | function addDiffButton() {
|
16 | 20 | // Find the Code button
|
17 | 21 | const codeButton = document.querySelector(
|
|
31 | 35 | diffButton.className = "btn btn-sm diff-view-button ml-2";
|
32 | 36 | diffButton.innerHTML = "View Diff";
|
33 | 37 | diffButton.onclick = () => {
|
34 |
| - const currentUrl = window.location.href; |
35 |
| - GM.openInTab(`${currentUrl}.diff`, true); |
| 38 | + try { |
| 39 | + const currentUrl = window.location.href; |
| 40 | + // Extract the base PR URL (remove hash fragments and extra paths after the PR number) |
| 41 | + const match = currentUrl |
| 42 | + .split("#")[0] |
| 43 | + .match(/https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/\d+/); |
| 44 | + const basePrUrl = match ? match[0] : currentUrl; |
| 45 | + GM.openInTab(`${basePrUrl}.diff`, true); |
| 46 | + } catch (error) { |
| 47 | + console.error("GitHub PR Diff Button: Error opening diff view", error); |
| 48 | + // Fall back to current URL if parsing fails |
| 49 | + GM.openInTab(`${window.location.href}.diff`, true); |
| 50 | + } |
36 | 51 | };
|
37 | 52 |
|
38 | 53 | // Insert after the details element
|
|
52 | 67 |
|
53 | 68 | // Run on page load
|
54 | 69 | window.addEventListener("load", addDiffButton);
|
| 70 | + |
| 71 | + // Run immediately in case the page is already loaded |
| 72 | + addDiffButton(); |
55 | 73 | })();
|
0 commit comments