开发者

Override downloading a file type with Chrome Extensions

开发者 https://www.devze.com 2023-04-12 02:44 出处:网络
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

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?


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


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?

0

精彩评论

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

关注公众号