On-Click A-tag with Href, socket gets disconnected

China☆狼群 提交于 2019-12-12 09:49:35

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/24009218/on-click-a-tag-with-href-socket-gets-disconnected

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!