Copy Git branch name from task in Jira

Jira has a cool feature when you enable official integration with GitHub. It allows you to copy the branch name from a task. This is useful when you want to create a new branch for a task, and you don't want to manually type the branch name. It also shows whether the PR has been merged and other related information.

However, not every team has this integration enabled! So, here's a quick guide on how to replicate this functionality using TamperMonkey or Run JavaScript Chrome extensions.

function addBranchButton() {
  const queryString = window.location.search;
  const urlParams = new URLSearchParams(queryString);
  const product = urlParams.get('selectedIssue');
 
  let branchId = document.querySelector('#branchId');
  let title = document.querySelectorAll(`h1`)[1].textContent;
 
  if (!branchId) {
    branchId = document.createElement('div');
    branchId.id = 'branchId';
    branchId.style.position = 'absolute';
    branchId.style.left = '350px';
    branchId.style.top = '23px';
    branchId.style.display = 'block';
 
    const branchName = `${product}_${slugify(title)}`;
 
    const button = document.createElement('input');
    button.type = 'button';
    button.value = 'Copy branch name';
    button.style.backgroundColor = '#0052CC';
    button.style.color = '#EEE';
    button.style.borderWidth = '0';
    button.style.fontSize = '14px';
    button.style.padding = '8px';
    button.style.paddingLeft = '12px';
    button.style.paddingRight = '12px';
    button.style.borderRadius = '4px';
    button.style.fontWeight = '600';
    button.style.cursor = 'pointer';
    button.style.fontFamily =
      '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, "Fira Sans", "Droid Sans", "Helvetica Neue", sans-serif';
 
    button.addEventListener('click', function () {
      navigator.clipboard.writeText(branchName);
    });
 
    branchId.appendChild(button);
 
    const header = document.querySelector('#jira-issue-header');
    header.appendChild(branchId);
  }
}
 
function slugify(str) {
  return str
    .toLowerCase()
    .trim()
    .replace(/[^\w\s-]/g, '')
    .replace(/[\s-]+/g, '_');
}
 
setInterval(addBranchButton, 2000);

The implementation assumes that the markup won't change in the future, so it's not very robust and will probably stop working after a few releases. However, it works now, so enjoy it while you can!


Published on August 3, 2024 2 min read