Home > Mobile >  Saving HTML Element to Clipboard Giving Error
Saving HTML Element to Clipboard Giving Error

Time:02-24

I have written some code to copy a hyperlink to the clipboard in HTLM format, however it's giving me an error.

  copyLink() {
    let theInput = "<a href='www.google.com'>This is a test</a>";
    let item: ClipboardItem = new ClipboardItem({'text/html': theInput});
    let clipboard: any = navigator.clipboard;
    clipboard.write([item]);
  }

When the code is ran I get this: enter image description here

Can anyone explain why?

I'm using an older version of angular with an older version of typescript so I had to add these interface definitions to the top of my file to get it to compile.

interface ClipboardItem {
  readonly types: string[];
  readonly presentationStyle: "unspecified" | "inline" | "attachment";
  getType(): Promise<Blob>;
}

interface ClipboardItemData {
  [mimeType: string]: Blob | string | Promise<Blob | string>;
}

declare var ClipboardItem: {
  prototype: ClipboardItem;
  new (itemData: ClipboardItemData): ClipboardItem;
};

CodePudding user response:

ClipboardItem expects a Blob as value for the MIME-Type

Source (See Constructor): https://developer.mozilla.org/en-US/docs/Web/API/ClipboardItem

const myHTMLString = "<a href='www.google.com'>This is a test</a>";
const myBlob = new Blob([ myHTMLString ], {type: 'text/html'});
let item = new ClipboardItem({'text/html': myBlob });
  • Related