Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override downloading a file type with Chrome Extensions

I'm trying to build a chrome extension that overrides a download of a file and displays it in the browser. For example if you click on a link to a '.csv' file I'd like it to render in the browser instead of downloading it.

Chrome already does it for PDF's types and the Xml Tree extension also does exactly that for xml files.

So it should be possible, just not sure how to go about catching that event?

like image 547
sren Avatar asked Oct 08 '11 01:10

sren


2 Answers

An implementation along the lines indicated by in the previous answers and specifically designed for CSV files can be found in this extension of mine on github:

https://github.com/rgrp/chrome-csv-viewer

Furthermore, with the new(ish) chrome webrequest API a direct approach is also now possible along the following lines:

  1. Listen to onBeforeRequest (this has to be in a background script - see background.js)
  2. Check if this is a CSV file (mimetype or file extension)
  3. If so cancel the request and then display the data using xhr

A working version of this can be found in a branch of that extension: https://github.com/rgrp/chrome-csv-viewer/tree/4-webrequest-intercept

like image 113
Rufus Pollock Avatar answered Oct 04 '22 22:10

Rufus Pollock


You could always look at the XML Tree code :).

If you only need to work with links, and not opening files from the address bar or File > Open, you could build a content script that adds a click event listener to every link.

In the event listener function:

  1. Add e.preventDefault() in the first line to prevent the browser 'following' the link.

  2. Using the link href value, get the data with XMLHttpRequest.

  3. In the XMLHttpRequest callback, open a new tab and render content accordingly.

Obviously, in many ways, this is not a great solution:

  • you want 'normal' links to be handled as usual by the browser

  • how can you tell if a text file contains comma-separated values (for example) except by looking at the file extension which, of course, may not be reliable?

Are you specifically thinking of .csv files -- and/or other specific types of content?

like image 22
Sam Dutton Avatar answered Oct 04 '22 22:10

Sam Dutton