console.log(コンソールログ)をHTML 上に表示


<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>Console to HTML</title>
    <style>
        #log-container {
            background-color: #222;
            color: #00ff00;
            padding: 15px;
            font-family: monospace;
            border-radius: 5px;
            height: 200px;
            overflow-y: auto;
            margin-top: 20px;
        }
        .log-entry {
            border-bottom: 1px solid #444;
            margin-bottom: 5px;
            padding-bottom: 5px;
        }
    </style>
</head>
<body>

    <h2>画面上のコンソール</h2>
    <button onclick="testLog()">ログを出力してみる</button>

    <div id="log-container"></div>

    <script>
        // --- console.logをHTMLに表示させるための仕組み ---
        const logContainer = document.getElementById('log-container');
        
        // 元のconsole.logを保存しておく(ブラウザのコンソールにも出すため)
        const originalLog = console.log;

        console.log = function(...args) {
            // 1. 本物のコンソールにも出力
            originalLog.apply(console, args);

            // 2. HTML要素を作成して追加
            const element = document.createElement('div');
            element.className = 'log-entry';
            
            // 配列やオブジェクトも見やすいように文字列変換
            element.textContent = args.map(arg => 
                typeof arg === 'object' ? JSON.stringify(arg) : arg
            ).join(' ');

            logContainer.appendChild(element);

            // 常に最新のログが見えるように自動スクロール
            logContainer.scrollTop = logContainer.scrollHeight;
        };

        // --- テスト用関数 ---
        function testLog() {
            console.log("現在時刻:", new Date().toLocaleTimeString());
            console.log({ status: "OK", message: "データを受信しました" });
        }
    </script>
</body>
</html>

コメント