0

Our client want to be able to run some javascript tracking code when users click on a link to download a PDF. My solution is to pass the name of the file, as a querystring, to a page that then prompts the user to download the file. Is there anyway to get the javascript to run before the .net code?

This is what I'm using on the file download page:

public partial class FileTracking : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string pdf = Request["pdf"] ?? string.Empty;

        if (string.IsNullOrEmpty(pdf)) return;

        Response.Clear();
        Response.AppendHeader("content-disposition", "attachment; filename=" + pdf);
        Response.ContentType = "application/octet-stream";
        Response.WriteFile(pdf);
        Response.Flush();
        Response.End();
    }
}

1 Answer 1

2

Without seeing the javascript code, it's difficult to assess fully. However, IF you were using jquery, then it would of course be possible to intercept the click on the link by doing something akin to the following:

$('.myLink' data-filename='warandpeace.pdf' data-file-url="/file/history").click(function(e){
    var fileName = $(this).data('filename');
    var url = $(this).data('file-url');
    // this prevents the link actioning straight away
    e.preventDefault();
    // do your tracking stuff here 
    trackMyStuff(fileName);
    // invoke your file download now
    downloadMyFile(fileName, url);
    return false;
});

Hope this helps...

[edit] - added some in-line data attrs to show a fuller example..

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.