JavaScript 窗口.URL 在函数中未定义

JavaScript window.URL is undefined in function

本文关键字:未定义 函数 窗口 URL JavaScript      更新时间:2023-09-26

我正在学习一些JavaScript,选择一个文件并使用它来创建一个对象URL,该URL可以设置为HTML5 videosrc。我正在 Ubuntu Lucid 上的 Chrome 版本 18.0.1025.162 中尝试这样做,并使用本地 HTML 文件以及同一文件夹中的 JavaScript 文件和媒体文件。

我可以使用输入元素选择一个视频文件,当我单击播放链接时,将执行 JavaScript 函数playVideo()

<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 文件是

$(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);
     }     
}

当我不选择任何文件并单击播放链接时,默认视频播放和控制台日志显示未选择文件 - 正如预期的那样。

当我选择一个视频文件,然后单击播放链接时,会发生错误。然后,playVideo()方法调用控制台日志显示window.URL' is 未定义setVideoSrc()

为什么会这样?有人可以帮我纠正这个问题吗?这是控制台日志输出

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 

在 Chrome 中使用 window.webkitURL。

这在Chrome和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;
}

另请参阅:

  • http://caniuse.com/#feat=bloburls
  • https://developer.mozilla.org/en/DOM/window.URL.createObjectURL
  • http://www.w3.org/TR/FileAPI/#url

试试这个方式:-

var file = document.getElementById('fselect').files[0];
if(file){
  setVideoSrc(player,file); 
}

以下行适用于Chrome和Firefox:-

window.URL.createObjectURL(file);

确保您正在上述浏览器上进行测试。

请参阅此信息

  • 窗。URL.createObjectURL
  • 窗。网址

你试过吗

 window.location.href = "URL";

而不是 window.url?似乎不支持网址功能。