3

I am working on a project using socket.io. I want to give user some links to download a file as

<a href="<path>" >Link Name</a>

When I click on link to download file, my socket gets disconnected.

When I use this

<a href="<path>" target="_blank">Link Name</a>

it works fine. Any reason why this happens?

Muath
  • 4,351
  • 12
  • 42
  • 69
Harpreet Singh
  • 2,651
  • 21
  • 31

2 Answers2

2

When you follow a link within the same window, the current page's environment gets completely torn down, including the entire JavaScript environment in which your code (and socket.io's code) is running. That's why it does this when you click a link to a new page within the current window, but not when you open a new window (target="_blank").

You'll want to look at the various single-page-application techniques, which mostly involve swapping content into the current page using ajax (and updating the hash so the URL is different) without loading an entirely new page into the window.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Ok, then why my other JS code is working fine but only my socket gets disconnected and is not emitting re-connect event automatically(as it usually do) whenever it gets disconnected. – Harpreet Singh Jun 03 '14 at 07:31
  • @HarpreetSingh: Presumably the new page you're loading contains your JavaScript, hooks up events, etc., etc. Just like just about every other page on the web. But because of the tear-down-and-rebuild, the original socket endpoint is gone, hence the disconnect. If you have a "thick" app that connects to a database on startup, exiting the app and running it again doesn't magically keep the original connection to the database, it closes the old connection and opens a new one. – T.J. Crowder Jun 03 '14 at 12:20
1

You can try to target downloads to a hidden iframe. This would prevent page reloading:

<iframe id="downloadIframe" name="downloadIframe" style="display:none;"></iframe>
<a href="<path>" target="downloadIframe">Link Name</a>

We specify id as well as name for iframe for cross-browser behavior.

Oleg
  • 22,300
  • 9
  • 68
  • 84