2

I have to copy API response to the clipboard(ctrl+c). i was trying to do through document.executeCommand in post man test section. But i was getting document is not defined error.

Is there any other way to complete my requirement.

  • The error `document is not defined` should not happen if you are in a browser context. What is the context you are running your code ? Also, have you tried using the [Clipboard API](https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API) ? Also have you read https://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript ? – Seblor Aug 04 '20 at 15:04
  • `execCommand` is now obsolete. – Alien Aug 04 '20 at 15:05
  • 1
    we can not have document inside postman, since its not a browser. This question is all about to find alternative solution – TirupathiRao Aug 04 '20 at 15:07
  • 1
    I don't think clipboard api is supported in the postman – Alien Aug 04 '20 at 15:08
  • Not really sure I understand your usecase - Are you not able to use the feature in the top right of the response section? – Danny Dainton Aug 04 '20 at 15:17
  • i can use the response section but i dont want to copy my response every time by pressing ctrl+c, i want it to be done when api is given response – TirupathiRao Aug 06 '20 at 09:55

1 Answers1

0

EDIT: I've done it.

Try this:

let template =
`
    <textarea id='copy' style='width:35%'></textarea>
    <script>
        pm.getData(function (error, data)
        {
            var node = document.getElementById('copy');
            node.textContent = data.response;
            var selection = document.getSelection();
            selection.removeAllRanges();
            node.select();
            document.execCommand('copy');
            selection.removeAllRanges();
            document.getElementById('copy').textContent = 'Response copied to clipboard!';
        });
    </script>
`;

pm.visualizer.set(template, {
    response: responseBody
});

Previous answer:

You could print it to the console in a triple-clickable (to highlight) format, making it a bit faster to copy. I use this technique in one of my Collections.

My example responses are in JSON, but the piece I want is nested, so I use this log statement:

console.info(ζ.name + " Results:\n\r", ζ.results.data[0]);

Where the ζ.results.data[0] portion is a convenient, triple-clickable JSON string.

Stroh
  • 31
  • 5
  • You could obviously combine the new answer and my previous answer if you want to copy the response to the clipboard as formatted JSON. – Stroh Apr 23 '21 at 15:41