<my-log> ❤️

用來代替系統 console.log,可用於 CodePen。

customElements.define('my-log', class extends HTMLElement {

    connectedCallback() {

        const root = this.attachShadow({ mode: 'open' });

        root.innerHTML = `
            <style>
                #container {
                    border: 1px solid black;
                    padding: 8px;
                    background: black;
                    color: white;
                }

                #container p {
                    margin: -8px;
                    margin-bottom: 8px;
                    padding: 8px;
                    background: var(--my-log-title-bg, tomato);
                }
            </style>
            <div id="container">
                <p>
                    console logs: 
                    <button>clear</button>
                </p>
                <div id="logs"></div>
            </div>
        `;

        // <div> for logs
        this.logs = root.querySelector('#logs');
        // clear button
        this.button = root.querySelector('button');

        // clear on click
        this.button.addEventListener('click', e => {
            this.clear();
        })

    }// end: constructor()

    // ⭐️ escape HTML special characters
    escapeHTML(str) {
        return str 
            .replace(/&/g, '&amp;' )    // ampersand (must be first❗️)
            .replace(/>/g, '&gt;'  )    // greater than
            .replace(/</g, '&lt;'  )    // less than
            .replace(/"/g, '&quot;')    // double-quote
            .replace(/'/g, '&#39;' )    // single-quote
            .replace(/`/g, '&#96;' );   // backtick
    }

    // log
    log(msg) {
        this.logs.innerHTML += this.escapeHTML(msg) + '<br>';
    }

    // clear logs
    clear() {
        this.logs.innerHTML = '';
    }
});

Usage

function log(msg){
    const div = document.querySelector('my-log');
    div.log(msg);
}

Last updated