Reputation: 3578
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();
}
}
Upvotes: 0
Views: 138
Reputation: 22485
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..
Upvotes: 2