Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript window.URL is undefined in function

I was learning some JavaScript, to select a file and use it to create an objectUrl which can be set as the src of an HTML5 video. I am trying this out in Chrome version 18.0.1025.162 on Ubuntu Lucid, and using a local HTML file with a JavaScript file and media files in the same folder.

I can select a video file using the input element and when I click on a play link, the JavaScript function playVideo() is executed.

<video id="vid" name='myvid' width="640" height="360" controls="controls">
       <source src="test.webm" type="video/webm" />
</video>
<br><a href="#" id="playlnk">Play </a> </li>
<br><input type="file" name="fileselect" id="fselect"> </input>

JavaScript file is

$(document).ready(function(){
        player=$('#vid').get(0);        
        $('#playlink').click(function(){playVideo(player);});        
    });
function setVideoSrc(player,file){
    console.log('winurl='+window.URL);
    var fileURL = window.URL.createObjectURL(file);
    player.src=fileURL;
    player.load();
    return;
}
function playVideo(player) {
     var file=document.getElementById('fselect').files[0];
     console.log('you chose:'+file);
     if (file==undefined){
        console.log('no file chosen');
     }else{
        console.log('file='+file);
        setVideoSrc(player,file);
     }     
}

When I don't select any file and click on the playlink, the default video plays and console log says no file chosen - as expected.

The error occurs when I select a video file and then click on the playlink. Then the playVideo() method calls setVideoSrc() in which the console log says window.URL' is undefined`

Why does this happen? Can someone help me correct this? Here is the console log output

you chose:[object File] //from playVideo() function
file=[object File]   //from playVideo() function
winurl=undefined   //setVideoSrc() function
Uncaught TypeError: Cannot call method 'createObjectURL' of undefined 
like image 524
damon Avatar asked May 10 '12 07:05

damon


1 Answers

Use window.webkitURL in Chrome.

This whould work in both Chrome and FireFox

function setVideoSrc(player,file){
    var myURL = window.URL || window.webkitURL
    console.log('winurl='+myURL);
    var fileURL = myURL.createObjectURL(file);
    player.src=fileURL;
    player.load();
    return;
}

See also:

  • http://caniuse.com/#feat=bloburls
  • https://developer.mozilla.org/en/DOM/window.URL.createObjectURL
  • http://www.w3.org/TR/FileAPI/#url
like image 100
Maurice Avatar answered Oct 20 '22 19:10

Maurice