Skip to content

Commit 312bb95

Browse files
committed
fix: File download fails when the clicked on the file name but works when clicking on the download (cloud) icon.
closes: RocketChat#2763
1 parent 4d5eb17 commit 312bb95

File tree

1 file changed

+38
-2
lines changed

1 file changed

+38
-2
lines changed

src/ui/components/ServersView/ServerPane.tsx

Lines changed: 38 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import type { FC } from 'react';
2-
import React, { useRef, useEffect } from 'react';
2+
import React, { useEffect, useRef } from 'react';
33
import { useDispatch } from 'react-redux';
44
import type { Dispatch } from 'redux';
55

@@ -99,7 +99,10 @@ export const ServerPane: FC<ServerPaneProps> = ({
9999
if (!webview) {
100100
return;
101101
}
102-
const addEventListenerOnce = (e: 'did-attach', cb: () => void): void => {
102+
const addEventListenerOnce = (
103+
e: 'did-attach' | 'new-window',
104+
cb: () => void
105+
): void => {
103106
const handler = () => {
104107
cb();
105108
webview.removeEventListener(e, handler);
@@ -119,10 +122,43 @@ export const ServerPane: FC<ServerPaneProps> = ({
119122
}, 300);
120123
};
121124

125+
const handleDidStartLoading = (): void => {
126+
webview.executeJavaScript(`
127+
document.addEventListener('click', function(event) {
128+
const fileDownloadURL = 'https://open.rocket.chat/file-upload';
129+
const isFileDownloadURL = event.target.href.startsWith(fileDownloadURL);
130+
const isTargetBlank = event.target.target === '_blank';
131+
132+
const fileName = event.target.href.split('/').pop().split('?')[0];
133+
134+
if (isFileDownloadURL && isTargetBlank) {
135+
event.preventDefault()
136+
137+
let downloadURL = event.target.href
138+
if (!downloadURL.endsWith('?download')) downloadURL += '?download'
139+
140+
const dynamicAnchor = document.createElement('a');
141+
dynamicAnchor.target = '_blank';
142+
dynamicAnchor.download = fileName;
143+
dynamicAnchor.href = downloadURL;
144+
145+
dynamicAnchor.addEventListener('click', function(e) {
146+
e.stopPropagation();
147+
});
148+
149+
document.body.appendChild(dynamicAnchor);
150+
dynamicAnchor.click();
151+
}
152+
})
153+
`);
154+
};
155+
122156
addEventListenerOnce('did-attach', handleAttachReady);
157+
webview.addEventListener('did-start-loading', handleDidStartLoading);
123158

124159
return () => {
125160
webview.removeEventListener('did-attach', handleAttachReady);
161+
webview.removeEventListener('did-start-loading', handleDidStartLoading);
126162
};
127163
}, [dispatch, serverUrl]);
128164

0 commit comments

Comments
 (0)