Having trouble reaching PouchDB in my html WebApp - javascript

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.

Related

Using JS IPFS in the Browser?

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.

IO not found when using socket.io while building a chat application

I was using socket.io and node.js for my application where I'm trying to use socket.io package and to import io package in my client.js I added the following script with my backend running at 3008 port as per documentation :
index.html:
<script defer src="http://localhost:3008/socket.io/socket.io.js"></script>
<script defer src="js/client.js"></script>
client.js:
const io2 = io.connect("http://localhost:3008");
but it kept showing the error that
ReferenceError: io is not defined
after reading some documentation I added the following script to my html file.
<script defer src=""https://cdn.socket.io/4.4.1/socket.io.esm.min.js""></script>
But the error persisted.
What should I do?
While importing the script, you added defer and
The defer attribute tells the browser not to wait for the script. Instead, the browser will continue to process the HTML, build DOM.
Just remove that attribute for socket.io script tag and keep it as it is for another js tag.
Like this :
Make sure you get js code loaded when you get http://localhost:3008/socket.io/socket.io.js in the browser.
Hope this helps!! Please comment if you get any issues or doubts later.

pdfjs cannot use function 'getPageIterator'

I am trying to follow the documentation for pdfjs found here https://www.pdftron.com/documentation/core/guides/features/manipulation/remove/ in an attempt to remove a page from a PDF I have uploaded to my html page. Here is my html code:
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.2.228/pdf.js"></script>
<input type="file" id="input"/>
<script>
document.getElementById('input').addEventListener('change', function(e){
var reader = new FileReader()
reader.onload = function(x){
window['pdfjs-dist/build/pdf'].getDocument({data:x.target.result}).promise.then(function(doc){
doc.pageRemove(doc.getPageIterator(5));
console.log(doc.numPages)
})}
reader.readAsBinaryString(e.target.files[0])
}, false)
</script>
which gives this console error when I upload a PDF file to the page:
removeDemo.html:10 Uncaught (in promise) TypeError: doc.getPageIterator is not a function
The PDF I am uploading has more than 5 pages, so asking to remove the 5th page in particular shouldn't be the problem. Other functionality does seem to work however, for example, I have a line in the above code that prints the number of pages of the document. This works fine when I comment out the 'getPageIterator' line. So it seems to be a problem with this specific function, rather than a more general problem. I would like to know what is causing this problem. In case this is relevant, I am running this in chromium on a macbook pro.
Please let me know if there is something in the above question that I can further clarify.
Mozilla led pdf.js is primarily a browser plugin pdf viewer, without editor functions.
The function your calling doc.pageRemove(doc is for use with PDFTron webview / edit SDK and thus specific to that commercial JavaScript library.
The documentation you linked to, from PDFTron, has nothing to do with PDF.js, it is a completely separate SDK. This is why you get an error making a SDK API call on a different SDK.
Since PDF.js does not support removing pages from a PDF (nor editing in general), then I assume your intention is to use PDFTron SDK to remove (or edit in other ways) a PDF file in the browser client side.
In which case you want to do the following.
See this sample:
https://www.pdftron.com/documentation/web/samples/pdf-manipulation/#page-operations
See here to get started with the SDK:
https://www.pdftron.com/documentation/web/get-started/

How to execute node function using html button

I'm new at nodejs and I want to write to a serial port using node but now I want it to be triggered by a button. And the data is coming from a textbox.
My node script is doing fine when I run it in the console/terminal. But can't do it with a button in a webpage.
Here's my nodejs embedded in html
<!DOCTYPE html>
<html>
<head>
<title>Node x HTML</title>
</head>
<body>
<script>
function write_serial()
{
var serialport = require("serialport");
var SerialPort = serialport.SerialPort;
var sp = new SerialPort("/dev/ttyACM0", {
baudrate: 9600,
parser: serialport.parsers.readline("\n")
});
var text = document.getElementById("textbox1").value;
sp.on('open', function()
{
sp.on('data', function (data)
{
sp.write(name);
});
});
}
</script>
<Input Type = "text" id = "textbox1" >
<BR>
<br><button onclick="write_serial();" href="javascript:;">Go!</button>
</body>
</html>
Here's the error I got when I open the console of the page (F12)
ReferenceError: require is not defined
Thanks in advance for your help. :)
Node.js is a hosting environment, that can execute JS and provides Node.js specific API. Browser, is a different hosting environment, with different API's. You can't use Node's specific API in a browser, and JS that uses Node API will result in an error in a browser.
For example, your script is using global require function, which is not available in a browser API's. And that's why:
ReferenceError: require is not defined
Conversely, your script can't be executed on Node as well, since it uses browser API:
document.getElementById("textbox1")
You've mixed API's from different environments in one script.
However, if your JS script doesn't use Node or browser specific API, it can be executed in both Node and a browser without an error. But it's not the case with your script.
The solution to your problem can be to split your script into two separate scripts, run one in a browser, and the other in Node.js, and to exchange data between them using XMLHttpRequest.
NodeJS is a non-browser JavaScript environment. You can't use most NodeJS features in a browser environment, because they aren't designed for it.
Instead, you'd have a local NodeJS process providing a web endpoint (e.g., a web server; perhaps using Express, but you don't have to) and run that NodeJS process so it's listening for web requests. Then you'd have a button on your web page that makes an ajax call to the NodeJS server, which performs the work.
Naturally, this would only allow you to perform the work on the machine where the server process is running.
Maybe import the serialport module from https://wzrd.in/standalone/serialport#latest
In other hand, try to seperate the logic from the view, i don't know if your app will grow or if it's just a POC, but use a messageBroker or sockets to bind your actions'view with the engine ?
Hope it helps

Shopify App - Using Script Tags with Ruby on Rails Application

I'm trying to familiarize myself with the concept of using script tags. I'm making a ruby on rails app that does something as simple as alert "Hi" when a customer visits a page. I am testing this public app on a local server and I have the shopify_app gem installed. The app has been authenticated and I have access to the store's data. I've viewed the Shopify API documentation on using script tags and I've looked at the Shopify Embedded App example that Shopify has on GitHub. The documentation details the properties of a script tag and gives examples of script tags with their properties defined, but doesn't say anything about where to place the script tag in an application, or how to configure an environment so that the js file in the script tag will go through.
I've discovered that a js file being added with a script tag will only work if the js file is hosted online, so I've uploaded the js file to google drive. I have the code for the script tag in the index action of my HomeController (the default page for the app). This is the code I'm using:
def index
if response = request.env['omniauth.auth']
sess = ShopifyAPI::Session.new(params[:shop], response[:credentials][:token])
session[:shopify] = sess
ShopifyAPI::Base.activate_session(sess)
ShopifyAPI::ScriptTag.create(
:event => "onload",
:src => "https://drive.google.com/..."
)
end
I think the problem may be tied to the request.env. The response is not being read as request.env[omniauth.auth] and I believe that the response coming back as valid may be required for the script tag to go through.
The method that I tried above is from the 2nd answer given in this topic: How to develop rails app for shopify with ScriptTags.
The first answer suggested using this code:
ShopifyAPI::Base.site = token
s = ShopifyAPI::ScriptTag.create(:events => "onload",:src => "your javascript url")
However, it doesn't say where to place both lines of code in a rails application. I tried putting the second line in a js file in my rails application, but it did not work.
I don't know if I'm encountering problems because I'm running the app on a local server or if there is something missing from the configuration of my application.
I'd appreciate it if anyone could point me in the right direction.
Try putting something like this in config/initializers/shopify_app.rb
ShopifyApp.configure do |config|
config.api_key = "xxx-xxxx-xxx-xxx"
config.secret = "xxx-xxxx-xxx-xxx"
config.scope = "read_orders, read_products"
config.embedded_app = true
config.scripttags = [
{event:'onload', src: 'https://yourdomain.herokuapp.com/javascripts/yourjs.js'}
]
end
Yes, you are correct that you'll need the js file you want to include for your script tag publicly available - if you are using localhost for development look into ngrok.
Do yourself the favor of ensuring your callbacks use SSL when interacting with the Shopify API (i.e. configure your app with https://localhost/ as a callback setting in the Shopify app settings). I went through the trouble of configuring thin as the web server locally with a self-signed SSL certificate.
With a proper set up you should be able to debug why the response is failing the omniauth check.
I'm new to the Shopify API(s), but not Rails. Their documentation leaves a lot to be desired.
Good luck to you sir,

Categories