JayB
JayB

Reputation: 543

IPFS & JavaScript: check for 404 status from localhost:8080 to determine in browser userscript if local IPFS node is enabled

I'm new to IPFS, and definitely new to JavaScript, but I've managed to concoct a basic IPFS redirect userscript running in my browser: whenever an address is of the type *://*/ipfs/* or *://*/ipns/*, the script kicks in and reroutes to http://localhost:8080/<IPFS_HASH>.

However, sometimes the local IPFS node isn't running, so the reroute is sent into nothingness, because nothing is happening on localhost:8080. So my question is, if there's a way to have the JS userscript within the browser (in my case: Safari w/ Tampermonkey) determine, if localhost:8080 is reachable. If it's not reachable, the script will do nothing, if it's reachable, it will start the redirect.

When a local IPFS node is active, localhost:8080 returns "404 page not found"

https://i.sstatic.net/mX5hA.png

…and when the node is inactive, Safari can't reach anything there:

https://i.sstatic.net/r48Gs.png

So the easiest thing would (probably) be to do the JavaScript equivalent to curl -o /dev/null --silent --head --write-out "%{http_code}\n" localhost:8080: if it returns "404", IPFS is active, and the script will reroute; and if it returns "000", IPFS is inactive, and the script will do nothing.

So how do I go about this with JavaScript? Thank you for your help.

Upvotes: 1

Views: 487

Answers (1)

tgebauer
tgebauer

Reputation: 164

You can use an XMLHttpRequest to query the server. Example from here.

var xhr = new XMLHttpRequest();

xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
                // Request finished; either succesful or via timeout
                alert(xhr.status);
        }
};

xhr.open("POST", "http://localhost:8080", true);
xhr.timeout = 4000; // Set timeout to 4 seconds (4000 milliseconds)
xhr.ontimeout = function () { alert("Timed out!!!"); }
xhr.send("");

Upvotes: 2

Related Questions