Using JavaScript in conjunction with IPFS to verify the 404 status from localhost:8080 and identify if the local IPFS node is active within a browser user script

As a newcomer to IPFS and JavaScript, I have successfully created a simple IPFS userscript that redirects addresses containing *://*/ipfs/* or *://*/ipns/* to

http://localhost:8080/<IPFS_HASH>
.

However, there is an issue when the local IPFS node is not running, causing the reroute to fail because nothing is happening on localhost:8080. My question is, is there a way for the userscript, which runs in my browser (Safari with Tampermonkey), to determine if localhost:8080 is reachable? If it is reachable, the script should initiate the redirect, but if not, it should do nothing.

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

https://i.stack.imgur.com/mX5hA.png

On the other hand, when the node is inactive, Safari cannot reach anything at that address:

https://i.stack.imgur.com/r48Gs.png

The most straightforward solution may be to use JavaScript to mimic the command

curl -o /dev/null --silent --head --write-out "%{http_code}\n" localhost:8080
: if the response is "404", IPFS is active, and the script can proceed with the rerouting; but if it is "000", then IPFS is inactive, and the script should refrain from any action.

How can I implement this functionality in JavaScript? Any assistance would be greatly appreciated.

Answer №1

To interact with the server, you may utilize an XMLHttpRequest. Check out an example from this source.

var request = new XMLHttpRequest();

request.onreadystatechange = function () {
        if (request.readyState == 4) {
                // The request has been completed; can be successful or due to timeout
                alert(request.status);
        }
};

request.open("GET", "http://example.com/api/data", true);
request.timeout = 3000; // Set a timeout of 3 seconds (3000 milliseconds)
request.ontimeout = function () { alert("Request timed out!"); }
request.send("");

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

VueJS Error: Attempting to access a property that is undefined causing a TypeError (reading 'toLowerCase')

Whenever I attempt to filter and remove items from an array, everything works fine. However, when I try to add new items to the array, I encounter an error message that says "TypeError: Cannot read properties of undefined (reading 'toLowerCase'). ...

Troubleshooting: ReactJS CSS Class Issue

I'm fairly new to working with ReactJS and I've encountered an issue while trying to create a class for a specific form. Below is the code I've written: import React, { Component, PropTypes } from 'react'; import s from './s ...

Adding an extra element to the <MuiThemeProvider /> causes the page to display as blank with no error notifications

After incorporating Material UI into my Meteor application via npm install --save material ui I successfully implemented the <Header /> component in my app.js file. However, when I try to add additional components, such as localhost:3000, all I see ...

Is there a way to change TTF files into OTF format?

I am looking to utilize the @font-face feature and have my fonts stored in TrueType (TTF) format. Can anyone advise on how to convert TTF to OpenType (OTF) format? ...

Utilize JavaScript to seamlessly play a Spotify track within the Spotify client without disrupting your current

A little while back, I recall the simplicity of clicking play on a song within a website and having it instantly start playing on my computer without any additional steps. It was seamless and effortless. My goal for my website is to have music start playi ...

Unable to retrieve file path from image selection in JavaScript by clicking on a button

I am trying to create a simple browsing feature that only accepts images. However, after clicking the button, I am unable to retrieve the full path in JavaScript. All I can get is the filename. JavaScript <script type="text/javascript"> functio ...

Tips for identifying if the cursor is hovering over the :before or :after section of an element

One of the challenges I am facing involves CSS and defining drop areas for users to interact with, allowing them to either drop a section before or after existing sections. .section:before, .section:after { content: "[insert here]"; height: 64px; ...

`In NodeJS, facing a challenge with implementing a many-to-many relationship using Sequelize's

I'm in the process of setting up many-to-many relationships between roles and accesses. The `roles` table will contain a list of roles (admin, developer, etc...) and the `accesses` table will have a list of permissions (Create Project, Create Site, De ...

Displaying properties of objects in javascript

Just starting with JavaScript and struggling to solve this problem. I attempted using map and filter but couldn't quite implement the if condition correctly. How can I find the records in the given array that have a gender of 0 and color is red? let s ...

"Can you tell me the method for obtaining an array within an Angular

Within the realm of PHP, there exist certain elements within an array: $this->data['messages']['ms'][] = 'Line1'; $this->data['messages']['ms'][] = 'Line2'; along with a method that return ...

Arranging JSON data by a specific attribute using JavaScript

As someone who is new to JavaScript, I have been working on some basic exercises. In my current code, I have a JSON data stored in a String that contains information about employees. My goal is to sort this data based on the age attribute and display the o ...

The POST variable consistently remains void

The approach I am using to handle the data sent with jquery.ajax involves sending an empty string by default. Whenever there is a change, I monitor the input for changes and resend the data. Everything seems to work fine in the console, but in PHP, $this-& ...

Ways to prevent scrolling on mobile web browsers?

I am currently facing an issue with disabling scrolling on a webpage when a user opens a popup, while still allowing them to scroll within the popup itself. The popup element is defined by the following attributes: #popup { display: none; width: ...

The margin data table unexpectedly grew on its own following the action of toggling column visibility

The margin table data mysteriously increased on its own after hiding / showing columns. Here is the original result before show/hide column: https://i.sstatic.net/N96HX.png After multiple show/hide actions (more than 10 times): https://i.sstatic.net/lPIG ...

Python script for downloading audio files loaded with JavaScript

I am currently working on a Python script to automate the process of downloading English audio files from a specific website. When I click on the play button, the audio file starts to load and play, but I am unsure how to capture and download the file in ...

HTML structure consisting of a 3 by 3 grid

Creating a 3x3 grid with cells that have varying heights depending on content is proving to be challenging. Except for the cells marked with red arrows, the rest of the grid has fixed height in pixels. I attempted to build a 3x3 grid using divs to experi ...

Error encountered while testing karma: subscription function is not recognized

I encountered an issue with my karma unit test failing with the following error message. "this.gridApi.getScaleWidth().subscribe is not a function" GridApi.ts export class GridApi { private scaleWidthSubject = new BehaviorSubject<{value: number}& ...

Conceal and reveal buttons at the same location on an HTML webpage

There are 3 buttons on my custom page called page.php: <input type="submit" value="Btn 1" id="btn1"> <input type="submit" value="Btn 2" id="btn2" onClick="action();> <input type="submit" value="Btn 3" id="btn3" onClick="action();> ...

Explore various queries and paths within MongoDB Atlas Search

I am currently working on developing an API that can return search results based on multiple parameters. So far, I have been able to successfully query one parameter. For example, here is a sample URL: http://localhost:3000/api/search?term=javascript& ...

Obtain the value stored in the variable named "data"

I'm trying to calculate the sum of data values using jQuery, similar to this example: { label: "Beginner", data: 2}, { label: "Advanced", data: 12}, { label: "Expert", data: 22}, and then add them together. Like so: var sum = data1+data2+dat ...