Using JS IPFS in the Browser? - javascript

I am developing a digital wallet and I am using ipfs inside a web extension, but I have the following errors:
this is my code:
const node = await Ipfs.create()
const results = await node.add('hello manlio')
document.getElementById('demo').innerHTML = JSON.stringify(results)
How to solve these errors ? thanks
I tried the following examples on ipfs: https://github.com/ipfs-examples/js-ipfs-examples

There are a few potential issues that could cause errors in this code:
Make sure that the IPFS library is correctly imported and available in your code. You can do this by adding the following line at the top of your code:
import Ipfs from 'ipfs';
Make sure, also, that the element with the ID 'demo' exists in the HTML document. If it does not exist, the following line of code will throw an error:
document.getElementById('demo').innerHTML = JSON.stringify(results) .
If you are running this code in a web browser, you may need to handle any potential CORS (Cross-Origin Resource Sharing) errors. You can do this by serving your HTML file from a local web server, or by using a CORS proxy.

Related

FileSystemWritableFileStream.write causes quota error

I'm using File System Access API (https://developer.mozilla.org/en-US/docs/Web/API/File_System_Access_API) to read and write a file into disk. This is my code;
const writable = await cacheFileHandle.createWritable({ keepExistingData: false });
await writable.write(JSON.stringify(cache));
await writable.close();
This code fails with Uncaught (in promise) DOMException: The operation failed because it would cause the application to exceed its storage quota. error. This began when the file reached 10MB. Is there any way to solve this?
Note:
I already tried the HTML File API solutions.
I tried window.webkitStorageInfo.requestQuota(window.PERSISTENT, 10240*10240,()=>{...},()=>{...}). That didn't work.
Another solution was to put unlimitedStorage to the manifest.json, but this is a react app, so that didn't help either.

Having trouble reaching PouchDB in my html WebApp

I want to use pouchDB in my WebApp so that when I click on a button, the data from a JSON file would be saved to pouchDB. In my index.html I imported these at first:
<script type="module" src="pouchdb/packages/node_modules/pouchdb/src/pouchdb.js"></script>
<script type="module" src="pouchdb-load/dist/pouchdb.load.js"></script>
<script src="js/pdb.js"></script>
I cloned pouchDB to my working html folder so the path should be fine. But in my js file it started to throw error from this line var PouchDB = require('pouchdb'); stating 'Uncaught ReferenceError: require is not defined', which I think it means that my WebApp failed to reach pouchDB from the src.
What I've tried:
Use <script src="//cdn.jsdelivr.net/npm/pouchdb#7.2.1/dist/pouchdb.min.js"></script> in the html file instead of using pouchdb.js in the js folder as the source.
This is also the only source this PouchDB official guide uses in its todo demo. This demo worked perfectly on my laptop, but when it comes to my own WebApp it no longer works and still throws the same error.
Another problem for this method is that even if the cdn link worked and I could reach pouchdb.min.js, I still need the pouchdb.load.js to be able to work since I want data in the JSON file to be saved to pouch.
In the PouchDB official guide, it doesn't even included this line var PouchDB = require('pouchdb'); in its app.js, but directly says var db = new PouchDB('todos');. But when I attempted to do it this way, a new error occurred: 'ReferenceError: PouchDB is not defined'.
I also tried npm install pouchdb-browser and then in the js file I wrote:
var PouchDB = require('pouchdb-browser');
var pouchdb = PouchDB.default.defaults();
but it throws the same error associated with require.
I think the problem is still that the sources in the html failed to created this connection between pouchdb.js with my WebApp. Meanwhile everything seems fine when I followed the official guide to make the todo Demo. Any idea what might have caused this problem and how to solve it?
I think you're mixing up client side and server side programming. You can't do "require" natively in client-side JavaScript code. Here's a very simple example of taking data from a form and writing it to local PouchDB:
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/pouchdb#7.2.1/dist/pouchdb.min.js"></script>
</head>
<body>
<textarea id="doc" rows="10">
{
"a": 1
}
</textarea>
<br>
<button onclick="save()">Save</button>
<div id="response"></div>
<script>
const db = new PouchDB('todos')
const save = async function() {
const el = document.getElementById('doc')
const doc = JSON.parse(el.value)
const response = await db.post(doc)
document.getElementById('response').innerHTML = JSON.stringify(response)
}
</script>
</body>
</html>
It gets PouchDB from the CDN - notice that I'm using https:// instead of // as the protocol because we always want to fetch PouchDB using https even if the hosted page is served out on http.
Once PouchDB is loaded, we write the document to PouchDB database using the post function and write the response back to the page.

Register service worker without access to local files

I'm attempting to build a PWA using Webflow, a web development tool. It is a web design platform, and it also manages hosting. It allows me to embed code into <head> or after the document, but it doesn't allow me to add any files to the server. I'm using a data: url to add a manifest file, which is working well. However, I'm finding it difficult to add a service worker.
I tried hosting the service-worker.js file on another server, and used navigator.serviceWorker.register('url_of_sw.js') but it gives me an origin error: ServiceWorker registration failed: DOMException: Failed to register a ServiceWorker: The origin of the provided scriptURL ('script_url') does not match the current origin ('site_url').
I tried a data: url by using navigator.serviceWorker.register('data:encoded_data') and it says that the protocol is not supported.
Is there any way to register a service worker without access to the local filestore? I know I can do it if I have control of a subdomain by setting document.domain. I want to assume I cannot do this.
This seems a browser security restriction. Just imagine, someone XSS this site, then all of the request will be control. It is dangerous.
Only service worker has this limit. For WebWorker, you can try:
const makeWorker = (workerFn) => {
const fnStr = `(${workerFn.toString()})()`;
const fnBolb = new Blob([fnStr]);
const fnUrl = URL.createObjectURL(fnBolb);
const worker = new Worker(fnUrl);
return worker;
};

CORS 400 header missing (among other issues)

This is my first project using javascript (basically forked code from here: https://www.kkhaydarov.com/audio-visualizer/)
I'm trying to build a visualizer that responds to the audio I am hosting.
Problems:
- Getting thrown a CORS 400 error (i'm using https://cors-anywhere.herokuapp.com/http:// in my source url)
- Audio is not getting recognized
Here is a link to my project on codepen: https://codepen.io/beewash92/project/editor/ZGWOQr
Code is also stored on my github: https://github.com/beewash/js-audio-visualizer
enter code here
I've scoured other posts on stackoverflow and across the web, but still running into issues. You're help is appreciated !
If you try to browse the link in chrome you will get the message as below
Missing required request header. Must specify one of: origin,x-requested-with
You will need to define the custom request header as stated above in order for it to work. Refer the api here as it clearly stated what you should do beforehand.
You should create a request with the header as follows
fetch('https://cors-anywhere.herokuapp.com/http://soundcloud.com/gentttry/10999-1', {
'headers': {
'Origin': 'soundcloud.com'
}
})
.then(res=>res.blob())
.then(blob=>URL.createObjectURL(blob))
.then(audio_src=>{
// Then init your audio here and assign the url
})

WebSocket connection to <url> failed: Error during WebSocket handshake: Unexpected response code: 404

I' m new to WebSocket and Node.js. I'm trying to create a real-time chat as a basic program. I basically based my code here. I run my code in Amazon Linux for it to run as a real web server. I always got an error after I input the user's name.
I use node-static as a static server API for my index.html file.
Here's my code for my javascript: app.js
And here's my code for index.html located inside the "public" folder: index.html
I always get the error at line15 in index.html.
Can anyone tell me what is the problem there? I tried moving that part anywhere inside the connectToChat() function but the error is still there.
You have an error in url you call.
It have to be ws://<mywebserver>:8000
instead of ws://<mywebserver>:8000/index.html
To fix it, in index.html , change this line
var url = document.URL.replace("http://", "ws://");
to
var url = document.origin.replace("http://", "ws://");
I had the same issue. I was able to fix it by pointing the client script to the real IP. It is not the best solution, but it will do for the moment.
let socket = io('http://000.000.000.000:0000');
Hope it helps!

Categories