Lightning Aura Components – Chart.js Not Working with Locker Service Enabled Org: How to Fix

I am trying to use Chart.js library to build a demo component .Everything worked before locker came into existence and after locker service I get the below error

"Something has gone wrong. Action failed: c$OpportunitySplit$controller$setup [TypeError: Cannot read property 'getComputedStyle' of undefined]
Failing descriptor: {c$OpportunitySplit$controller$setup}.
Please try again."

The component code is below

<aura:component implements="flexipage:availableForRecordHome,force:hasRecordId,force:hasSObjectName" access="global" >
 <ltng:require styles="/resource/SLDS104/assets/styles/salesforce-lightning-design-system-ltng.css" scripts="/resource/Chartjs"
afterScriptsLoaded="{!c.setup}"/>
  <canvas aura:id="chart" id="chart" width="400" height="400">
  </canvas>
</aura:component>

The controller js code below

({
setup : function(component, event, helper) {
    var data = {
    labels: ["January", "February", "March"],
    datasets: [{
        data: [65, 59, 80, 81, 56, 55, 40]
    }]
};
var el = component.find("chart").getElement();
    console.log(el);
var ctx = el.getContext("2d");
        var myNewChart = new Chart(ctx , {
      type: "line",
      data: data,
   });
  }
})

Anybody else seeing this issue with chart.js library in the Locker Service Enabled org ?

Best Answer

Please open a case on this to get things tracked and post the case ID here so I can follow up on it. We have not tested Chart.js yet and this is most likely an issue in Locker's secure virtual DOM implementation. Can you also provide here the specific version of Chart.js (2.1.4 is the latest I believe) you are using in /resource/Chartjs so I can get look into this now? Are you using Chart.js or Chart.bundle.js?

FYI these incomplete secure virtual DOM issues tend to be quick to debug if you enable Break on All Exceptions in your browser of choice's js debugger settings. Chrome dropped me on the exact line right away. Of course since the bug was mine you can also let me deal with it - but every bit of info we can get upfront helps reduce the cycle time from reported issue to fix.

UPDATE: easily repro'ed the issue with ChartJS 2.1.4 and the problem is simply that SecureDcoument.defaultView is not implemented.

enter image description here

With that trivial fix in place (not on production yet!) things are working nicely:

enter image description here