12

Hello everyone,

I've tried to retrieve an image from a websocket server (in .NET) I send the image as bytes then I retrieve it on the client side, the code for retrieving on the client side (using canvas and JavaScript):

var c=document.GetElementById("myCanvas");
var ctx=c.getContext("2d");
ws.onmessage=function(evt)
{
    var image=new Image();
    image.src=URL.createObjectURL(evt.data);
    ctx.drawImage(image,0,0);
}

it perfectly displays the picture on firefox, but at Chrome, it just returning undefined and won't load the image through createObjectURL I'm using Chrome 18.0.1025.162

any idea?

jazzytomato
  • 6,994
  • 2
  • 31
  • 44
Eldon Lesley
  • 915
  • 6
  • 19
  • 38

1 Answers1

23

From MDN:

This method is prefixed in Chrome and Webkit as window.webkitURL.createObjectURL().

You should test if URL exists and then use the appropriate object:

(window.URL ? URL : webkitURL).createObjectURL(evt.data);
apsillers
  • 112,806
  • 17
  • 235
  • 239
  • 4
    I wish I had seen this one earlier, made me lost around 10 hours working on my phone. Thanks ! – Sephy Nov 12 '13 at 21:31
  • 2
    When I try this, I still get a 404 not found for my blob, and get an additional `'webkitURL' is deprecated. Please use 'URL' instead.` - I believe the responses here explain the reason - http://stackoverflow.com/questions/6755401/createobjecturl-is-returning-undefined-in-chrome – Jonathan Basile Jun 08 '15 at 17:44
  • 3
    @JonathanBasile My answer tested from `webkitURL` and used it (with `URL` as a fallback). I have just changed it to use `URL` by default and use `webkitURL` as a fallback. Does that work? If not, you may be using `createObjectURL` incorrectly (or in a way to violates some security assumption), and you should create a new question. – apsillers Jun 08 '15 at 17:46
  • 1
    I think my problem is actually that I am testing on localhost - which apparently chrome forbids - I haven't tested it yet over the internet – Jonathan Basile Jun 08 '15 at 17:47
  • 1
    A local server run on `localhost` *should* work (but maybe there's some kind of rule against it?). On the other hand, a `file:` URL may be likely to fail, as it does for many other new APIs, for security reasons. – apsillers Jun 08 '15 at 17:49