Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Suggestion for 'copy to clipboard' feature? #30

Open
oshihirii opened this issue Feb 4, 2023 · 0 comments
Open

Suggestion for 'copy to clipboard' feature? #30

oshihirii opened this issue Feb 4, 2023 · 0 comments

Comments

@oshihirii
Copy link

oshihirii commented Feb 4, 2023

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); 

}); 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant