Script error from Chrome with Karma and Webdriver

Perry Mitchell / 2016-08-04 19:49:20
Script error from Chrome with Karma and Webdriver

Chrome is a funny beast, but it makes for a great test­ing or ex­e­cu­tion tar­get when us­ing tools like Karma or Webdriver. Karma al­lows for catch­ing global un­caught ex­cep­tions, but writ­ing some­thing your­self is quite straight­for­ward:

function handleError(err) {
    console.log("Caught the error:", err);
}

// Maybe:
window.addEventListener("error", handleError, false);
// Or possibly:
window.onerror = (msg, url, line, col, error) => handleError(error || new Error(msg));
// Or even:
window.addEventListener("unhandledrejection", function(event) {
    // event is a PromiseRejectionEvent
    handleError(event);
}, false);

Global er­ror han­dling is ba­si­cally a night­mare.

All this trou­ble to end up with some­thing like this:

Error: Script error

Jackie Chan WTF

Thanks Chrome. So it turns out that this is ac­tu­ally to do with se­cu­rity, and can oc­cur when run­ning lo­cal (localhost) scripts and re­sources. I en­coun­tered it first in JasDriver, which uses Webdriver. The fix was to add the --allow-file-access-from-files Chrome flag:

let webdriverCapabilities = Webdriver.Capabilities.chrome();
webdriverCapabilities.set('chromeOptions', {
    'args': ["--allow-file-access-from-files"]
});

webdriver = (new Webdriver.Builder())
    .withCapabilities(webdriverCapabilities)
    .build();

The sec­ond en­counter was with Karma run­ner in a pro­ject at work, and in­volved an up­date to our Karma con­fig:

{
    // snip

    browsers: ["ChromeWithoutWebSecurity"],

    customLaunchers: {
        ChromeWithoutWebSecurity: {
            base: 'Chrome',
            flags: ['--disable-web-security']
        }
    }

    // snip
}

These flags are ob­vi­ously fine for test­ing pur­poses, and make our er­rors a lit­tle eas­ier to read. Chrome will stop feed­ing us cryp­tic "Script error" mes­sages and we can get on with our work.