开发者

Auto-download behavior and back button issue

Instead of linking directly to files for download on a web site we link to a page that says "thank you for downloading". The page has tracking codes on it so we know how many people have downloaded the file. The page launches the download file using the jQuery code shown which adds a short delay after the page loads 开发者_运维百科before the download begins. The download location has a content disposition header so it always downloads properly in the browser leaving the "thank you for downloading" page visible. This all works well.

The problem comes if the user carries on browsing past this page and then hits back. The download fires again.

Using window.location.replace(href); didn't seem to fix it.

The issue is further complicated by the fact that the CMS delivering the page has set it to expire immediately so it's not being cached.

Suggestions for (i) ways to avoid this problem; (ii) any better ways to handle file download / thank you pages?

jQuery Code

$(document).ready(function () {
    $('a.autoDownload').each(function () {
        setTimeout('navigateToDownload("' + $(this).attr('href') + '")', 4000);
    });
});

function navigateToDownload(href) {
    document.location.href = href;
}


One possible approach would be to set a cookie via Javascript when the page first loads. Then, if that page is ever loaded again, you can check for the presence of the cookie, and if present, do not execute the auto download?

Using the Cookie plugin for jQuery as an example:

$(document).ready(function () {
    $('a.autoDownload').each(function () {
        var hasDownloadedThisLink = $.cookie("site." + $(this).attr('id'));
        if (!hasDownloadedThisLink) {
            $.cookie("site." + $(this).attr('id'), "true");
            setTimeout('navigateToDownload("' + $(this).attr('href') + '")', 4000);
        }   
    });
});

This is just an example. If you went this way, you'd have to consider how many possible download links there might be, as there is a limit on how many cookies you can set. Also notice that I used an id attribute of the links to identify them in the cookie - I figured this would be more suitable that using some form the href attribute. I also prefixed the cookie name with site..


Well there are a couple of solutions to this. Here's an example:

function navigateToDownload(href){
    var e = document.createElement("iframe");
    e.src=href;
    e.style.display='none';
    document.body.appendChild(e);
}

Other implemenatations might exist, but I doubt they're less "hacky".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜