JS event error to force and rename Download file

Asked

Viewed 336 times

0

Hello, I have a Script to force download via remote URL that I got as answer here on the site, however I think I must have done something wrong because the Download event is not starting and not even renaming the file at download time.

Updating: With the help of Dontvote the script is downloading the case just to rename the file of the Remote Url otherwise this ok, someone would be able to help me with this.

Observing changed the code in question from image file to video file.

 <!DOCTYPE html>
<html>
<body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<style>
.hide-link {
   position: absolute;
   top: 0px;
   left: 0px;
}
</style>   
 <script>
function download(url, nome) {
    var el = document.createElement("a");
        el.download = nome; //Define o nome
        el.href = url; //Define a url
        el.target = "_blank"; //Força abrir em uma nova janela
        el.className = "hide-link"; //Adiciona uma classe css pra ocultar

    document.body.appendChild(el);

    if (el.fireEvent) {
        el.fireEvent('onclick');//Simula o click pra navegadores com suporte ao fireEvent
    } else {
        //Simula o click
        var evObj;

        evObj = document.createEvent("MouseEvents");
        evObj.initEvent("click", true, false);
        el.dispatchEvent(evObj);
    }

    //Remove o link da página
    setTimeout(function() { document.body.removeChild(el); }, 100);
}
</script>
<div class="hide-link" onload="download('http://thumb.mais.uol.com.br/14317945.mp4', 'video01.mp4')">Clique aqui</div>  
</body>    
</html>
  • And you debugged the function, or checked if there are any errors in the console?

  • I tested the script on various Online Script Testing sites and on 4 servers the function was not started at all.

1 answer

1

You’re making a mistake right now:

evObj.initEvent(type, true, false);

Because the variable type is not set. I tested by placing "click" hard code and it worked:

evObj.initEvent("click", true, false);

Fiddle

As I said, the element div does not have the event onload. When you posted the code using a button with onclick, function worked.

  • Ata bug my already edited put onclick event

  • @Rodrigo see my edition.

  • @Rodrigo you do not stop changing your code, so there is no help. I put a fiddle with your code working the way I said.

  • The Download event is working only that it is not renaming the file at download time. Just missing this more grateful for the help so far.

  • @Rodrigo good, according to this documentation(see Notes): "This attribute is only honored for links to Resources with the same-origin.", then it probably won’t work because you are making the request to a third party server.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.