robotstxt-2fa/assets/js/recovery-codes.js
2026-06-05 14:04:51 +00:00

111 lines
2.7 KiB
JavaScript

( function() {
'use strict';
const settings = window.robotstxt2FARecovery || {};
document.addEventListener( 'DOMContentLoaded', () => {
const root = document;
bindCopyButtons( root );
} );
function bindCopyButtons( scope ) {
const buttons = scope.querySelectorAll( '[data-robotstxt-2fa-copy-button]' );
buttons.forEach( ( button ) => {
if ( '1' === button.dataset.robotstxt2FaCopyBound ) {
return;
}
button.dataset.robotstxt2FaCopyBound = '1';
button.addEventListener( 'click', () => {
const container = button.closest( '[data-robotstxt-2fa-codes-scope]' );
if ( ! container ) {
return;
}
const codes = Array.from( container.querySelectorAll( '[data-robotstxt-2fa-code]' ) )
.map( ( element ) => element.textContent || '' )
.filter( ( value ) => value.trim().length > 0 );
if ( ! codes.length ) {
return;
}
copyCodes( codes.join( '\n' ), container );
} );
} );
}
function copyCodes( text, scope ) {
const feedback = scope.querySelector( '[data-robotstxt-2fa-copy-feedback]' );
const confirmMessage = getString( 'copyConfirm' );
const fallbackMessage = getString( 'copyFallback' );
const updateFeedback = ( message, isError ) => {
if ( ! feedback || ! message ) {
return;
}
feedback.hidden = false;
feedback.textContent = message;
if ( isError ) {
feedback.classList.add( 'error' );
} else {
feedback.classList.remove( 'error' );
}
};
if ( navigator.clipboard && navigator.clipboard.writeText ) {
navigator.clipboard.writeText( text )
.then( () => {
if ( confirmMessage ) {
updateFeedback( confirmMessage, false );
}
} )
.catch( () => {
if ( fallbackMessage ) {
updateFeedback( fallbackMessage, true );
}
} );
return;
}
const helper = document.createElement( 'textarea' );
helper.value = text;
helper.setAttribute( 'readonly', 'readonly' );
helper.style.position = 'absolute';
helper.style.left = '-9999px';
document.body.appendChild( helper );
helper.select();
try {
const success = document.execCommand( 'copy' );
if ( success && confirmMessage ) {
updateFeedback( confirmMessage, false );
return;
}
} catch ( error ) {
// Continue to fallback message below when execCommand fails.
} finally {
document.body.removeChild( helper );
}
if ( fallbackMessage ) {
updateFeedback( fallbackMessage, true );
}
}
function getString( key ) {
if ( settings.strings && settings.strings[ key ] ) {
return String( settings.strings[ key ] );
}
return '';
}
}() );