javascript - How do you copy response values to the clipboard in Postman javascript tests?
问题描述
I've recently found out about the ability in postman to write pre-request and test scripts using javascript.
I'm trying to figure out if it's possible to copy a value to the clipboard during a test in conjunction with setting the postman environment variable.
For example:
var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable ("Action ID", jsonData.ActionId);
// set jsonData.ActionId to clipboard
解决方案
There is a way that it could be achieved, by using the visualizer and bringing in the clipboard.js
CDN.
This is very basic but by adding this script to the Tests
tab, you can see the variable value in the Visualize
tab, in the response section.
pm.environment.set("Action_ID", pm.response.json().ActionId);
let template = `
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.0/clipboard.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.4.1/dist/jquery.min.js"></script>
</head>
<body>
<div>
<div>
<pre><code style="width:max-content!important;" id="copyText">${pm.environment.get('Action_ID')}</code></pre>
</div>
<button class="copyButton" type="button" data-clipboard-action="copy" data-clipboard-target="#copyText" style="background:green;color:white;">Copy to Clipboard</button>
</div>
</body>
</html>
<script>
var clipboard = new ClipboardJS('.copyButton');
clipboard.on('success', function(e) {
e.clearSelection();
e.trigger.textContent = '✔ Copied!';
window.setTimeout(function() {
e.trigger.textContent = 'Copy to Clipboard';
}, 2000);
});
clipboard.on('error', function(e) {
e.clearSelection();
e.trigger.textContent = '✗ Not Copied';
window.setTimeout(function() {
e.trigger.textContent = 'Copy to Clipboard';
}, 2000);
});
</script>`
pm.visualizer.set(template, pm.response.json())
推荐阅读
- bash - OSX 终端继续自行接线
- asp.net-mvc - 如何在新数据库中执行 SQL 查询?
- java - 从相机捕获图像时位图为空
- database - 如何在 DolphinDB 的内存表中添加一列?
- excel - Powerquery 将分隔的列拆分为唯一的行
- html - 使最小列的多列大小
- c++ - 功能无法匹配 GLDEBUGPROC,仅在 MSVC 上(使用相同的 glew 版本 2.1.0,在带有 gcc/clang 的 linux 上很好)
- java - 自定义输入强制 Pattern.compile 抛出 PatternSyntaxException
- python - Python - 从数据框构建摘要数据框
- nginx - Nginx 挂在音频文件请求上