User:Polygnotus/Scripts/SectionLinks.js
Appearance
Code that you insert on this page could contain malicious content capable of compromising your account. If you import a script from another page with "importScript", "mw.loader.load", "iusc", or "lusc", take note that this causes you to dynamically load a remote script, which could be changed by others. Editors are responsible for all edits and actions they perform, including by scripts. User scripts are not centrally supported and may malfunction or become inoperable due to software changes. A guide to help you find broken scripts is available. If you are unsure whether code you are adding to this page is safe, you can ask at the appropriate village pump. This code will be executed when previewing this page. |
Documentation for this user script can be added at User:Polygnotus/Scripts/SectionLinks. |
// Add link icons with tooltips to h2 headers for current versions, old revisions, and diffs
(function() {
function addLinkIcons() {
const headers = document.querySelectorAll('h2[id]');
headers.forEach(header => {
// Skip the table of contents heading
if (header.id === 'mw-toc-heading') {
return;
}
const isCurrentVersion = !window.location.search.match(/[?&]oldid=(\d+)/) && !document.querySelector('.diff-currentversion-title');
if (isCurrentVersion) {
// Add two icons for current version
addIcon(header, '🔗', false, 'Copy link to this section'); // Chain link emoji for section link
addIcon(header, '📌', true, 'Copy permalink to this section'); // Pushpin emoji for permalink
} else {
// Add single icon for old revision or diff
addIcon(header, '🔗', true, 'Copy link to this section of this specific revision');
}
});
}
function addIcon(header, iconText, isPermalink, tooltipText) {
const icon = document.createElement('span');
icon.innerHTML = iconText;
icon.style.cursor = 'pointer';
icon.style.marginRight = '5px';
icon.style.fontSize = '0.8em';
icon.title = tooltipText; // Add tooltip
icon.addEventListener('click', function(e) {
e.preventDefault();
let url;
if (isPermalink) {
const currentId = mw.config.get('wgRevisionId');
url = `${window.location.origin}${window.location.pathname}?oldid=${currentId}#${header.id}`;
} else {
url = `${window.location.origin}${window.location.pathname}#${header.id}`;
}
navigator.clipboard.writeText(url).then(() => {
mw.notify(`${isPermalink ? 'Permalink' : 'Section link'} copied to clipboard!`, {
type: 'success',
tag: 'urlCopy'
});
}).catch(() => {
mw.notify('Failed to copy URL', {
type: 'error',
tag: 'urlCopy'
});
});
});
header.insertBefore(icon, header.firstChild);
}
// Run the function when the DOM is fully loaded
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', addLinkIcons);
} else {
addLinkIcons();
}
})();