-
Notifications
You must be signed in to change notification settings - Fork 3
/
rtfRedirectHandler.js
96 lines (82 loc) · 2.48 KB
/
rtfRedirectHandler.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
'use strict';
function getViewerURL(fileUrl) {
return chrome.extension.getURL('viewer/viewer.html') + '?file=' + encodeURIComponent(fileUrl);
}
function getHeader(details, headerName) {
return details.responseHeaders.find(function(element){
if(element.name.toLowerCase() === headerName){
return element;
}
return false;
});
}
function contentTypeContains(contentType, string){
if(contentType.value.indexOf(string) > -1){
return true;
}
return false;
}
function urlIndicatesRtf(url){
if(url.indexOf('?') > -1){
url = url.substring(0, url.indexOf('?'));
}
return url.toLowerCase().endsWith('.rtf');
}
function contentDispositionIndicatesRtf(contentDisposition){
if (contentDisposition.value.toLowerCase().startsWith('attachment')) {
var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
var filename = filenameRegex.exec(contentDisposition.value)[1];
if (filename) {
return filename.toLowerCase().endsWith('.rtf');
}
}
return false;
}
function isRtfFile(details) {
var contentType = getHeader(details, 'content-type');
var contentDisposition = getHeader(details, 'content-disposition');
var isRtf = false;
if (contentType) {
isRtf = contentTypeContains(contentType, 'application/rtf') ||
contentTypeContains(contentType, 'text/rtf') ||
contentTypeContains(contentType, 'text/richtext') ||
urlIndicatesRtf(details.url);
}
if (contentDisposition) {
isRtf = isRtf || contentDispositionIndicatesRtf(contentDisposition);
}
return isRtf;
}
chrome.webRequest.onHeadersReceived.addListener(
function(details) {
if (!isRtfFile(details)) {
return;
}
return { redirectUrl: getViewerURL(details.url) };
},
{
urls: ['<all_urls>'],
types: ['main_frame', 'sub_frame']
},
['blocking','responseHeaders']
);
chrome.webRequest.onBeforeRequest.addListener(
function (details) {
return { redirectUrl: getViewerURL(details.url) };
},
{
urls: ['ftp://*/*.rtf', 'file://*/*.RTF'],
types: ['main_frame', 'sub_frame']
},
['blocking']
);
chrome.webRequest.onBeforeRequest.addListener(
function (details) {
return { redirectUrl: getViewerURL(details.url) };
},
{
urls: ['file://*/*.rtf', 'file://*/*.RTF'],
types: ['main_frame', 'sub_frame']
},
['blocking']
);