Home / Disable / Disable Console Logs
Duplicate Snippet

Embed Snippet on Your Site

Disable Console Logs

// Disable Console Logs for Production
// Frontend only per WPCode Plugin Location Settings
// Header Priority 0 must run before any scripts are enqueued

Code Preview
php
<?php
$isProduction = true;
        $triggerWords = ['.loc', 'localhost', '.local', 'staging.', '.staging', '.testing', '.dev'];
        // edit triggerWords for your setup, these as fairly standard identifiers of non production env
        // the goal is to check the root url for a string that would never be in a production URL
        // multiple triggers make this more robust but also more janky
        // be mindful of unintended matching with subdomains ex: https://subdomain.deviantart.com/ will match for .dev
        foreach ($triggerWords as $triggerWord) {
            if (strpos($_SERVER['HTTP_HOST'], $triggerWord)) {
                $isProduction = false;
                break;
            }
        }
        
        echo "<script>";
        echo "const isProduction = ";
        echo $isProduction ? 'true;' : 'false;';
        // Disable console log on production
        echo "if (isProduction === true) {console.log = console.warn = console.error = function() {};};";
        echo "</script>";

Comments

Add a Comment