Cannot read property 'digest' of undefined
Peter Hoffmann
Posted on August 21, 2019
I just had the strangest error while trying to generate a simple unique identifier from SHA265(Date())
.
The problem
My code looks like this and worked trouble-free developing on my Spontaneous HTTP Server:
async function genSessionId () {
const msgBuffer = new TextEncoder('utf-8').encode(Date.now())
const hashBuffer = await window.crypto.subtle.digest('SHA-256', msgBuffer)
const hashArray = Array.from(new Uint8Array(hashBuffer))
return hashArray.map(b => ('00' + b.toString(16)).slice(-2)).join('')
}
(source: MDN)
The search
Thanks to the completely meaningless error message I was stunned and had to look really hard to find the reason (I didn't find anything on the dev docs, or MDN web docs). Thanks to some guy on the internet I was directed in the right direction and could finally search in the right corner. Hidden the first paragraph, second indent you find the solution.
The reason
Access to the WebCrypto API is restricted to secure origins (which is to say https:// pages).
(Source: Chromium)
The call
Websecurity is constantly improving, especially Chrome is not only implementing important web technologies with a breathtaking speed but also tightening security vastly. Making HTTPS the default is e.g. for sure the right thing to do.
But.
But we still need to be able to develop in our own setup without being patronized. This is the second experience that already cost me some time and will cost even more as I now have to find a way around this. The whole CORS rules are also very hindering and I wish I could have a switch to turn them of temporarily. Just for development. To be clear, not for the whole browser, I still need it for browsing, just for my dev servers.
The update
Google Web Advocate DasSurma replied to my call: You can add your own "secure origin" via a chrome flag. ❤️
Posted on August 21, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.