Reputation: 164
I tried putting location.reload() in my node.js code because I want to reload the browser and it gave me an error which said that location was not defined. Is there a way to reload a browser from a node.js file in code?
Upvotes: 1
Views: 1578
Reputation: 108641
Can nodejs force a browser to reload? No, it cannot. Why not? In most cases, the browser hits your nodejs server when it wants something (a new page, or data from a REST api, or whatever). There's no way for node to reach out and touch the browser. It's the other way around. That lies at the heart of what tbl (Tim Berners-Lee) came up with on inventing the web and the http protocol. Browser-initiated connections.
You can write browser-side Javascript code to poll (hit every so often) an API on your nodejs server saying "should I reload now?".
Or you can go the cheap-and-nasty route of using a meta-refresh tag. If you include this one, for example, in the <head>
of your HTML page, the page will refresh every five seconds.
<meta http-equiv="refresh" content="5">
But, this is monstrously ugly. Page flickers. If the user's interacting with it, it disappears out from under her and reappears.
If you want to get fancy, you can set up a persistent browser-to-nodejs connection with Websockets or socket.io. Those are built on top of http / https so they'll work. Then nodejs can send a message to the browser telling it to refresh, or to hit some other page (location.href="some URL"
).
Upvotes: 4