User:Polygnotus/Scripts/Fragment.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.
This code will be executed when previewing this page.
Documentation for this user script can be added at User:Polygnotus/Scripts/Fragment.
// <nowiki>
// Add "Link to selected text" to Tools menu
$(function() {
mw.util.addPortletLink(
'p-tb',
'#',
'Link to selected text',
't-linktotext',
'Create a URL fragment linking to the selected text'
);
$('#t-linktotext').on('click', function(e) {
e.preventDefault();
var selection = window.getSelection();
if (!selection || selection.rangeCount === 0 || selection.toString().trim() === '') {
mw.notify('No text selected', { type: 'error' });
return;
}
var range = selection.getRangeAt(0);
// Get the selected text
var selectedText = selection.toString().replace(/\s+/g, ' ').trim();
// Get text before selection for prefix
var beforeRange = range.cloneRange();
beforeRange.collapse(true);
beforeRange.setStart(beforeRange.startContainer.parentElement || beforeRange.startContainer, 0);
var beforeText = beforeRange.toString().replace(/\s+/g, ' ').trim();
// Get text after selection for suffix
var afterRange = range.cloneRange();
afterRange.collapse(false);
var endContainer = range.endContainer;
var endParent = endContainer.parentElement || endContainer;
afterRange.setEndAfter(endParent);
var afterText = afterRange.toString().replace(/\s+/g, ' ').trim();
// Extract prefix (last few words before selection)
var beforeWords = beforeText.split(' ').filter(w => w.length > 0);
var prefix = beforeWords.slice(-3).join(' ');
// Extract suffix (first few words after selection)
var afterWords = afterText.split(' ').filter(w => w.length > 0);
var suffix = afterWords.slice(0, 3).join(' ');
// Build text fragment
var words = selectedText.split(' ').filter(w => w.length > 0);
var textFragment = '';
if (prefix) {
textFragment += encodeURIComponent(prefix) + '-,';
}
if (words.length > 5) {
var textStart = words.slice(0, 3).join(' ');
var textEnd = words.slice(-3).join(' ');
textFragment += encodeURIComponent(textStart) + ',' + encodeURIComponent(textEnd);
} else {
textFragment += encodeURIComponent(selectedText);
}
if (suffix) {
textFragment += ',-' + encodeURIComponent(suffix);
}
// Store fragment and reload with a flag
sessionStorage.setItem('pendingTextFragment', textFragment);
var reloadUrl = window.location.origin + window.location.pathname +
window.location.search + (window.location.search ? '&' : '?') + '_clearhighlight=1';
window.location.href = reloadUrl;
});
// On page load, check if we're coming back from a reload
var urlParams = new URLSearchParams(window.location.search);
if (urlParams.has('_clearhighlight')) {
var textFragment = sessionStorage.getItem('pendingTextFragment');
if (textFragment) {
sessionStorage.removeItem('pendingTextFragment');
// Remove the flag from URL and add text fragment
urlParams.delete('_clearhighlight');
var cleanSearch = urlParams.toString();
var newUrl = window.location.origin + window.location.pathname +
(cleanSearch ? '?' + cleanSearch : '') + '#:~:text=' + textFragment;
window.location.replace(newUrl);
}
}
});
// </nowiki>