Suggestion for 'copy to clipboard' feature?
I don't suppose there would be any out of the box, minimal way to add a 'copy json to clipboard' feature?
Just looking at the element that is created (#json-renderer), I can see all the data is dispersed throughout subsequent child elements.
So, if I wanted to add this feature, when loading the data, I suppose I would need to add the JSON to a data attribute of an element or perhaps even a cookie, and then implement a standard 'copy to clipboard' method?
Perhaps:
https://developer.mozilla.org/en-US/docs/Web/API/Navigator/clipboard
Below is a little proof of concept - seems to work, has pretty printing and all!
(I'm not sure if there is a size 'limit' on HTML data attributes).
Part 01 - loading the JSON:
// instantiate json-renderer
$('#json-renderer').jsonViewer(my_json_data, {collapsed: false, rootCollapsable: true, withQuotes: false, withLinks: false});
// prepend an icon to the json-renderer div
$('#json-renderer').prepend("<span id='copy_to_clipboard' style='position: absolute; right: 50px; margin-top: 10px; cursor: pointer'></span>");
// add the json to the icons data attribute
$('#copy_to_clipboard').data('my_json_data',my_json_data);
Part 02 - copying to the clipboard:
// copy to clipboard
const copy_to_clipboard = async (my_json_data) => {
try {
await navigator.clipboard.writeText(JSON.stringify(my_json_data, null, 2));
console.log('content copied to clipboard!');
} catch (err) {
console.error('failed to copy: ', err);
}
}
// add click handling
$(document).on("click", "#copy_to_clipboard", function() {
let $this = $(this);
let my_json_data = $this.data("my_json_data")
copy_to_clipboard(my_json_data);
});