<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<p>Test that window.onerror and "error" event listeners from main world are
invoked for uncaught exceptions in the main world, user scripts, isolated worlds.
The `error` object in the event is sanitized out across worlds.</p>
<div id="console"></div>
<script>
var recordCount = 0;
var expectedRecordCount = (2 * 2 * 3);
function checkEnd() {
    recordCount++;
    if (recordCount === expectedRecordCount)
        testRunner.notifyDone();
}

function log(msg) {
    var record = document.createElement("div");
    record.textContent = msg;
    document.getElementById("console").appendChild(record);
}

function header(msg) {
    document.getElementById("console").append(document.createElement("br"), msg);
}

function lastUrlComponent(url) {
    return url ? url.match( /[^\/]+\/?$/ )[0] : url;
}

window.onerror = function(msg, url, line, column, error) {
    log("Main world window.onerror: " + msg + " at " + lastUrlComponent(url) + ":" + line + ":" + column + " " + error);
    checkEnd();
    return true;
}

window.addEventListener("error", function(e) {
    log("Main world error event listener: " + e.message + " at " + lastUrlComponent(e.filename) + ":" + e.lineno + ":" + e.colno + " " + e.error);
    checkEnd();
    e.preventDefault();
});

function triggerExceptions(worldName)
{
    // Serializable error data is fine.
    setTimeout(function() {
        throw "SerializableError from (" + worldName + ")";
    }, 0);

    // Non-serializable data should be null.
    setTimeout(function() {
        var globalObject = (1, eval)('this');
        throw globalObject;
    }, 0);
}

if (window.testRunner) {
    testRunner.dumpAsText();
    testRunner.waitUntilDone();
}

header("User Script");
testRunner.addUserScript("(" + triggerExceptions + ")('user script')", false, true);

setTimeout(function() {
    header("Main World");
    triggerExceptions("main world");
}, 100);

setTimeout(function() {
    header("Isolated World");
    testRunner.evaluateScriptInIsolatedWorld(0, "(" + triggerExceptions + ")('isolated script')");
}, 200);
</script>
</body>
</html>
