Create clone of text selection without use of clipboard

Viewed 59

For my application I need a kind of internal clipboard with history. I can't use the clipboard api (as far as I can see) as this would need permission from the user which is not an option.

I wan't to preserve formatting like bold, italics and strikethrough.

I was thinking about getting the content from window.getSelection(), but there is no way of easily cloning all the html that is in the selection.

The contents would need to go into another container element to be shown somewhere in the app.

Any ideas of how to achieve this are highly appreciated.

Best Matthias

EDIT: I'm already interrupting the copy event and replace it with custom function. What I need to do is start at the anchorNode, cut some possible offset and go forward to the focusNode (also with offset). Also all unknown/unwanted tags (span, h1, div etc need to be removed but the text content shall stay). I hoped that someone has already done this or a similar task so I can save some time :/

1 Answers

The copy event could help you, as it doesn't require any permission to work.

var clipHistory = [];
document.addEventListener('copy', (event) => {
    const selection = document.getSelection();
    clipHistory.push(selection.toString());
    event.preventDefault();      // optional, it prevents to modify the user's clipboard
});
// other functions can access clipHistory

A nice thing is that the copy event is very well supported.

Unlcukly this solution remove the formatting, but on way to keep it is to use a <div contenteditable id="parse-div"></div> and fire the parse event manually.

I found an intersting class: the Range one, but it doesn't allow to set a start and an end offset of non #text elements, as far I can undertand it.

Related