web.js 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import { WebPlugin } from '@capacitor/core';
  2. export class ClipboardWeb extends WebPlugin {
  3. async write(options) {
  4. if (typeof navigator === 'undefined' || !navigator.clipboard) {
  5. throw this.unavailable('Clipboard API not available in this browser');
  6. }
  7. if (options.string !== undefined) {
  8. await this.writeText(options.string);
  9. }
  10. else if (options.url) {
  11. await this.writeText(options.url);
  12. }
  13. else if (options.image) {
  14. if (typeof ClipboardItem !== 'undefined') {
  15. try {
  16. const blob = await (await fetch(options.image)).blob();
  17. const clipboardItemInput = new ClipboardItem({ [blob.type]: blob });
  18. await navigator.clipboard.write([clipboardItemInput]);
  19. }
  20. catch (err) {
  21. throw new Error('Failed to write image');
  22. }
  23. }
  24. else {
  25. throw this.unavailable('Writing images to the clipboard is not supported in this browser');
  26. }
  27. }
  28. else {
  29. throw new Error('Nothing to write');
  30. }
  31. }
  32. async read() {
  33. if (typeof navigator === 'undefined' || !navigator.clipboard) {
  34. throw this.unavailable('Clipboard API not available in this browser');
  35. }
  36. if (typeof ClipboardItem !== 'undefined') {
  37. try {
  38. const clipboardItems = await navigator.clipboard.read();
  39. const type = clipboardItems[0].types[0];
  40. const clipboardBlob = await clipboardItems[0].getType(type);
  41. const data = await this._getBlobData(clipboardBlob, type);
  42. return { value: data, type };
  43. }
  44. catch (err) {
  45. return this.readText();
  46. }
  47. }
  48. else {
  49. return this.readText();
  50. }
  51. }
  52. async readText() {
  53. if (typeof navigator === 'undefined' ||
  54. !navigator.clipboard ||
  55. !navigator.clipboard.readText) {
  56. throw this.unavailable('Reading from clipboard not supported in this browser');
  57. }
  58. const text = await navigator.clipboard.readText();
  59. return { value: text, type: 'text/plain' };
  60. }
  61. async writeText(text) {
  62. if (typeof navigator === 'undefined' ||
  63. !navigator.clipboard ||
  64. !navigator.clipboard.writeText) {
  65. throw this.unavailable('Writting to clipboard not supported in this browser');
  66. }
  67. await navigator.clipboard.writeText(text);
  68. }
  69. _getBlobData(clipboardBlob, type) {
  70. return new Promise((resolve, reject) => {
  71. const reader = new FileReader();
  72. if (type.includes('image')) {
  73. reader.readAsDataURL(clipboardBlob);
  74. }
  75. else {
  76. reader.readAsText(clipboardBlob);
  77. }
  78. reader.onloadend = () => {
  79. const r = reader.result;
  80. resolve(r);
  81. };
  82. reader.onerror = e => {
  83. reject(e);
  84. };
  85. });
  86. }
  87. }
  88. //# sourceMappingURL=web.js.map