Jump to content

User:Zackmann08/scripts/copyPageName.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 waitForElement(selector) {
  return new Promise(resolve => {
    // Check if it already exists
    const element = document.querySelector(selector);
    if (element) {
      return resolve(element);
    }

    // Observe changes if it doesn't exist yet
    const observer = new MutationObserver(mutations => {
      const element = document.querySelector(selector);
      if (element) {
        resolve(element);
        observer.disconnect(); // Stop observing once found
      }
    });

    observer.observe(document.body, {
      childList: true,
      subtree: true
    });
  });
}

function copyPageName()
{
	var dummy = $('<input>').val(mw.config.get('wgPageName').replace(/_/g, ' ')).appendTo('body').select();
	document.execCommand('copy');
	mw.notify('Page name copied to clipboard');
}

function copyPageTitle()
{
	var dummy = $('<input>').val(mw.config.get('wgTitle').replace(/_/g, ' ')).appendTo('body').select();
	document.execCommand('copy');
	mw.notify('Page title copied to clipboard');
}

mw.loader.using( [ 'oojs-ui-core' ] ).then( function () {
// jQuery(document).ready(function($) {
	
	(async () => {
		await waitForElement("#firstHeading");
		var first_heading = document.getElementById('firstHeading');
	
		var copyButton = new OO.ui.ButtonWidget({framed: false});
		copyButton.setElementId( 'copyPageName' ).setIcon( 'copy' );
			
		copyButton.on( 'click', function () {
			copyPageName(0);
		});
		copyButton.$element.css( 'font-size', '50%' );
		copyButton.$element.css( 'vertical-align', 'text-bottom' );
		copyButton.$element.css( 'margin-right', '0' );
		
		copyButton.$element.insertBefore( $(first_heading.firstChild) );
		
		if (mw.config.get('wgNamespaceNumber') != 0) {
			var copyTitleButton = new OO.ui.ButtonWidget({framed: false});
			copyTitleButton.setElementId( 'copyPageTitle' ).setIcon( 'copy' );
			copyTitleButton.on( 'click', function () {
				copyPageTitle(0);
			});
			copyTitleButton.$element.css( 'font-size', '50%' );
			copyTitleButton.$element.css( 'vertical-align', 'text-bottom' );
			copyTitleButton.$element.css( 'margin-right', '0' );
			
			copyTitleButton.$element.insertAfter( $(document.getElementsByClassName('mw-page-title-main')[0]) );
		}
	})();
});


//</nowiki>