1

I want to refresh a page in a browser tab using keyboard shortcut or CLI command when the browser window is not active (i.e. I'm working on different display). The webpage that have to be refreshed is well under my control, so I can inject any javascript there. Scrolling location should be kept after the refresh. My idea is to include simple javascript on that page that will wait for some outside event, i.e. through socket, and when this event happens, run location.reload(true). Then I can communicate with this javascript from the command line (shell) script and assign keyboard shortcut to this command line script if needed. I'm pretty sure it's possible because there are lots of tools that allow this (e.g. LiveReloadX). I cannot use such tools because I don't want to automatically refresh the window when something changes, I want to do it by explicit command. It seems that it should be really simple, but I cannot find the solution so far. So, my question is: how to make javascript running in the browser to be controlled from the command line?

1 Answer 1

1
+50

There's two parts to getting your solution done - the server running on your command line and the client running on your webpage.

Client

In your browser, you want to initialize a WebSocket client. MDN has a great example to get started with this, and I added your intended functionality of refreshing the page:

// Create WebSocket connection.
const socket = new WebSocket('ws://localhost:8080');

// Connection opened
socket.addEventListener('open', function (event) {
    socket.send('Hello Server!');
});

// Listen for messages
socket.addEventListener('message', function (event) {
    console.log('Message from server ', event.data);
    location.reload(true)
});

Server

There are many different ways to set up a WebSocket server and choosing the one that works best for you is probably too broad for an answer on this site. I did some quick research, and it looks like websocketd is a great way to wrap an existing command line program that uses standard in/out into a WebSocket server. You would need to implement a command line program that listens for your refresh shortcut and then writes a message to standard out. Then, you would wrap it with websocketd and run it from the command line:

websocketd --port=8080 ./your-shortcut-listener.sh
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.