Writing Your First ZAP Script

Writing Your First ZAP Script

Beginning with stand-alone scripts provides the gentlest introduction to ZAP scripting. These scripts access ZAP's API to perform specific tasks like generating reports, managing sessions, or analyzing scan results. A simple example demonstrates core concepts:

// Stand-alone script to list all alerts
function listHighRiskAlerts() {
    var Alert = Java.type("org.parosproxy.paros.core.scanner.Alert");
    var ExtensionAlert = Java.type("org.zaproxy.zap.extension.alert.ExtensionAlert");
    
    var extAlert = control.getExtensionLoader().getExtension(ExtensionAlert.class);
    var alerts = extAlert.getAllAlerts();
    
    print("High Risk Alerts Found:");
    print("========================");
    
    for (var i = 0; i < alerts.length; i++) {
        var alert = alerts[i];
        if (alert.getRisk() == Alert.RISK_HIGH) {
            print("\nURL: " + alert.getUri());
            print("Alert: " + alert.getName());
            print("Evidence: " + alert.getEvidence());
        }
    }
}

listHighRiskAlerts();

This script demonstrates several important concepts: importing Java types for access to ZAP's internal classes, obtaining extension references through the control API, iterating through collections, and filtering based on specific criteria. The print function outputs to ZAP's script console, providing feedback during execution.

Error handling in scripts prevents crashes and provides meaningful debugging information. Wrap potentially failing operations in try-catch blocks, log errors appropriately, and provide fallback behavior. Good error handling transforms brittle scripts into reliable automation tools that operate consistently across different environments and edge cases.