utils.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. export function sleep(ms) {
  2. return new Promise(resolve => setTimeout(resolve, ms));
  3. }
  4. export function stringToHex(str) {
  5. let result = '';
  6. for (let i = 0; i < str.length; i++) {
  7. result += str.charCodeAt(i).toString(16);
  8. }
  9. return result;
  10. }
  11. export function hexToString(str) {
  12. let result = '';
  13. for (let i = 0; i < str.length; i += 2) {
  14. result += String.fromCharCode(parseInt(str.substr(i, 2), 16));
  15. }
  16. return result;
  17. }
  18. export function formatDate(d, format) {
  19. if (!format)
  20. format = 'normal';
  21. switch (format) {
  22. case 'normal':
  23. return `${d.getDate().toString().padStart(2, '0')}.${(d.getMonth() + 1).toString().padStart(2, '0')}.${d.getFullYear()} ` +
  24. `${d.getHours().toString().padStart(2, '0')}:${d.getMinutes().toString().padStart(2, '0')}`;
  25. }
  26. }
  27. export function fallbackCopyTextToClipboard(text) {
  28. let textArea = document.createElement('textarea');
  29. textArea.value = text;
  30. document.body.appendChild(textArea);
  31. textArea.focus();
  32. textArea.select();
  33. let result = false;
  34. try {
  35. result = document.execCommand('copy');
  36. } catch (e) {
  37. //
  38. }
  39. document.body.removeChild(textArea);
  40. return result;
  41. }
  42. export async function copyTextToClipboard(text) {
  43. if (!navigator.clipboard) {
  44. return fallbackCopyTextToClipboard(text);
  45. }
  46. let result = false;
  47. try {
  48. await navigator.clipboard.writeText(text);
  49. result = true;
  50. } catch (e) {
  51. //
  52. }
  53. return result;
  54. }