Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NSExceptional/8f9489adbd135c415dad7968986c546e to your computer and use it in GitHub Desktop.
Save NSExceptional/8f9489adbd135c415dad7968986c546e to your computer and use it in GitHub Desktop.
A Tampermonkey script to change the behavior of the copy branch button on GitHub PRs to copy some markdown instead
(function() {
'use strict';
function copyMarkdown() {
...
navigator.clipboard.writeText(markdown);
}
function addEventsToCopyElements() {
// Get all elements with tag name clipboard-copy and class js-copy-branch
const copyElements = document.querySelectorAll("clipboard-copy.js-copy-branch");
// Add a replacement click event listener to each clipboard-copy element
copyElements.forEach(element => {
element.addEventListener("click", event => {
event.preventDefault();
// If the shift key is pressed, we want to allow the default behavior
// and run the original click events
if (event.shiftKey) {
// Run the original click event
oldClickEvents[element](event);
}
else {
// Otherwise, we want to copy the markdown to the clipboard
copyMarkdown();
}
})
});
}
// A map of clipboard-copy elements to their click event listeners
const oldClickEvents = new Map();
// Hook addEventListener to intercept click events on clipboard-copy elements
const originalAddEventListener = EventTarget.prototype.addEventListener;
EventTarget.prototype.addEventListener = function(type, listener, options) {
if (type === "click" && this.tagName === "CLIPBOARD-COPY") {
// If the element is a clipboard-copy element, we want to store the click event listener
oldClickEvents.set(this, listener);
}
else {
// Add the event listener as normal
return originalAddEventListener.apply(this, arguments);
}
};
// Wait for the DOM to be loaded before adding events
const observer = new MutationObserver((mutationList, observer) => {
for (const mutation of mutationList) {
if (mutation.type === 'childList') {
addEventsToCopyElements();
return;
}
}
});
observer.observe(document.body, { childList: true, subtree: true });
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment