Home > Blockchain >  Send a link to a webpage and automatically download a file
Send a link to a webpage and automatically download a file

Time:11-02

so I have a webpage with a element similar to the following

<a href="docs/some_file.xlsx" download="some_file.xlsx" class="btn btn-primary">Download!</a>

Now I'd like to send a hyperlink to some clients via email so that they would access the webpage and at the same time have the file downloaded without them having to click on it. That way they get the file and I make sure that they see the webpage where there is a lot more information.

So far I thought about a right click and copy link to the button directly from the browser but that hyperlink simply downloads the file if I click on it from ab email and I want the browser to pop up and show the landing page where the button and info is. Any idea?

BTW, the webpage is fully static so no php running. Only HTML and javascript could be used to configure the webpage

CodePudding user response:

You can trigger a file download with JavaScript by firing click() on an <a> tag with the download attribute. Something like this:

const $link = document.createElement('a');
$link.href = 'docs/some_file.xlsx';
$link.download = 'some_file.xlsx';
$link.click();

Keep in mind, however, that browsers may try to limit automatic file downloads in order to prevent sites doing dodgy things. I've seen this in particular when a site tries to download multiple files, so I think you'll be fine just downloading a single file.

Generally, the best way around this is to ensure that you only perform this action in response to user input, such as a click, but that doesn't sound like it would work for the solution you're looking for here.

CodePudding user response:

What you could do - setup a certain parameter for example: https://example.com/?autodownload=1

then add a piece of javascript that either imediately, or after some timeout automatically downloads the file. Something like:

document.addEventListener("DOMContentLoaded", function(event) { 
    if (window.location.href.indexOf("autodownload") > -1)
      setTimeout(function(){ 
            window.open("https://example.com/docs/some_file.xlsx");
        }, 3000); //your timeout in miliseconds
    }
});

of course this solution will not work, if browser will block opening new windows. Second possibility with this approach is to replace the window.open function with click on the anchor itself.

  • Related