代码如下,支持悬浮的一键复制。
// ==UserScript==
// @name JSON Formatter with Copy Button
// @namespace http://tampermonkey.net/
// @version 0.1
// @description Format JSON on the current page with a copy button
// @author You
// @match *://*/*
// @grant GM_addStyle
// ==/UserScript==
(function() {
'use strict';
function formatAndHighlightJSON() {
const preElements = document.querySelectorAll('pre');
preElements.forEach(preElement => {
try {
const json = JSON.parse(preElement.textContent);
const jsonString = JSON.stringify(json, null, 2);
const highlightedJSON = syntaxHighlight(jsonString);
preElement.innerHTML = `${highlightedJSON}
`;
addCopyButton(preElement);
} catch (error) {
console.error('Error parsing JSON:', error);
}
});
}
function syntaxHighlight(jsonString) {
jsonString = jsonString.replace(/&/g, '&').replace(//g, '>');
return jsonString.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+-]?\d+)?)/g, function(match) {
let cls = 'number';
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'key';
} else {
cls = 'string';
}
} else if (/true|false/.test(match)) {
cls = 'boolean';
} else if (/null/.test(match)) {
cls = 'null';
}
return `${match}`;
});
}
function addCopyButton(element) {
const copyButton = document.createElement('button');
copyButton.textContent = 'Copy JSON';
copyButton.style.position = 'fixed';
copyButton.style.bottom = '20px';
copyButton.style.right = '20px';
copyButton.style.padding = '10px';
copyButton.style.cursor = 'pointer';
copyButton.addEventListener('click', function() {
copyToClipboard(element.textContent);
});
document.body.appendChild(copyButton);
}
function copyToClipboard(text) {
const textarea = document.createElement('textarea');
textarea.value = text;
document.body.appendChild(textarea);
textarea.select();
document.execCommand('copy');
document.body.removeChild(textarea);
// alert('JSON copied to clipboard!');
}
formatAndHighlightJSON();
// 添加样式
GM_addStyle(`
.json-code {
display: block;
white-space: pre-wrap;
font-family: 'Microsoft Yahei', monospace;
padding: 10px;
background-color: #fff5f5;
border: 1px solid #ddd;
border-radius: 5px;
font-size: 14px;
}
.number {
color: #007777;
}
.string {
color: #007777;
}
.boolean {
color: #0033FF;
}
.null {
color: #0000FF;
}
.key {
color: #cc0000;
font-weight: bold;
}
`);
})();