Clipboard.js: Allow to alter the copied text before putting it into the clipboard

Created on 20 Jan 2017  路  6Comments  路  Source: zenorocha/clipboard.js

I'd like to modify the copied text before it's put into the clipboard in order to perform some sanitization (trimming etc.).

Is this possible somehow? If not, could the API be extended so I could pass in a function for doing so? Thanks for your consideration.

Most helpful comment

What I'd like to have is the option pass in a function that modifies the selected text:

new Clipboard('.btn', {
    textModifier: function(text) {
        return text + '123';
    }
});

This function will be invoked with the selected text, and the returned text will by pasted into the clipboard. The default implementation would simply return the selected text as is.

It'd also suffice to pass the selected text to the existing text function alongside the trigger:

new Clipboard('.btn', {
    text: function(trigger, text) {
        return ...;
    }
});

Then one can either return a new text from scratch as of today, or amend the text already selected by the library.

All 6 comments

I saw the text function, but how can I get hold of the selected text in there? I don't want to return a static text but rather modify the selection. Is there an example for doing so somewhere?

Ok, so I have to look for the source element itself. I had hoped to avoid this, given the fact that clipboard.js already has done this and could simply pass the text to me in a callback. I still think that'd be a valuable addition, but I'll go for the approach you suggest. Thanks.

Can you explain in a JSFiddle how you wanted things to work?

What I'd like to have is the option pass in a function that modifies the selected text:

new Clipboard('.btn', {
    textModifier: function(text) {
        return text + '123';
    }
});

This function will be invoked with the selected text, and the returned text will by pasted into the clipboard. The default implementation would simply return the selected text as is.

It'd also suffice to pass the selected text to the existing text function alongside the trigger:

new Clipboard('.btn', {
    text: function(trigger, text) {
        return ...;
    }
});

Then one can either return a new text from scratch as of today, or amend the text already selected by the library.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

XZZsr picture XZZsr  路  5Comments

dweepcan picture dweepcan  路  3Comments

aussiechief picture aussiechief  路  3Comments

maxjvh picture maxjvh  路  5Comments

maheshnarke picture maheshnarke  路  4Comments