Cannot make connection to metamask - javascript

I want to make connection to metamask and get the account balance :
<!DOCTYPE html>
<html>
<head>
<title>Test ethereum metamask</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="module">
import { ethers } from "https://cdn.ethers.io/lib/ethers-5.2.esm.min.js";
const provider = new ethers.providers.Web3Provider(window.ethereum);
const balance = await provider.getBalance("0xE0552897c6495D7efb98F3823cd48bf19e703D0b");
</script>
</head>
<body>
test
</body>
<script type="text/javascript">
console.log("========== balance =", balance);
</script>
</html>
At runtime I get console errors : Uncaught ReferenceError: balance is not defined and Access to script at 'https://cdn.ethers.io/lib/ethers-5.2.esm.min.js' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
So what is the problem ?

use cloudflare cdn and put the console.log("========== balance =", balance); into the first script. module scripts are defer by default
<script type="module">
import { ethers } from "https://cdnjs.cloudflare.com/ajax/libs/ethers/5.7.2/ethers.esm.js";
const provider = new ethers.providers.Web3Provider(window.ethereum);
const balance = await provider.getBalance(
"0xE0552897c6495D7efb98F3823cd48bf19e703D0b"
);
console.log("========== balance =", balance);
</script>
From this github post
A lot of projects are using production levels of bandwidth from the
ethers CDN to load their JavaScript, which I can no longer afford to
operate at that scale.
If you are linking to cdn.ethers.io or cdn-cors.ethers.io, you should
switch to using the relevant link provided on cdnjs.
Feedback is welcome, and I apologize for the inconvenience.
Thanks!

Related

CORS error with JS async/await but not when I paste the URL directly into browser [duplicate]

This question already has answers here:
No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API
(26 answers)
Closed 1 year ago.
When I put the URL http://192.168.1.136:8080/epost_backend/api.php?method=getCategories into chrome it returns the output from the API that I have built.
But when I put the exact same URL into a javascript async/await function, it always gets trapped in the catch error...
Here is network tab showing CORS error:
Here is the HTML/JS file:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<script>
async function getCategories(){
try{
const res = await fetch("http://192.168.1.136:8080/epost_backend/api.php?method=getCategories")
const output = await res.json()
document.getElementById('result').innerHTML = output
}
catch{
document.getElementById('result').innerHTML = "THERE WAS AN ERROR"
}
}
</script>
<body onLoad='getCategories()'>
<h1>RESULT</h1>
<div id='result'></div>
</body>
</html>
Any thoughts on what I am doing wrong or why I cant get this info this way??
I will be monitoring and answering any questions....
Thanks so much!
You simply need to enable CORS on your PHP server. You do this by setting a number of headers. At a minimum set Access-Control-Allow-Origin "*" to allow all origins to make requests to your PHP server.
A good reference can be found at this site: https://enable-cors.org/server_php.html

Resource interpreted as Stylesheet but transferred with MIME type text/html in cloudflare workers

I am trying to add an external css file and i got to know a method to add using this answer Adding External Stylesheet using JavaScript
and using that i am trying to add the external file but getting the error here is the code which i am tried to run
const html = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h2 class="heading">Hello</h2>
<script>
var element = document.createElement("link");
element.setAttribute("rel", "stylesheet");
element.setAttribute("type", "text/css");
element.setAttribute("href", "main.css");
document.getElementsByTagName("head")[0].appendChild(element);
</script>
</body>
</html>`
async function handleRequest(request) {
return new Response(html, {
headers: {
'content-type': 'text/html;charset=UTF-8',
},
})
}
addEventListener('fetch', (event) => {
return event.respondWith(handleRequest(event.request))
})
and when i run this code in firefox then this error comes
The stylesheet https://staticpage.practice.workers.dev/main.css was not loaded because its MIME type, “text/html”, is not “text/css”.
The problem is that you're serving the same HTML from every path.
When you visit your site in your browser, first the browser requests the page, and it gets back HTML as it expected. But your HTML contains some JavaSript which constructs a tag like: <link rel="stylesheet" type="text/css" href="main.css"> When your browser sees this, it tries to load main.css as a stylesheet. Since this is a relative path, it tries to load it from the same server that served the HTML. But that server is your worker, and your worker always returns your HTML in response to every request. So when the browser requests main.css, it gets the HTML again. This isn't a valid stylesheet, so it complains with the error you saw.
You could try changing your worker's handleRequest() method to be something like:
async function handleRequest(request) {
let url = new URL(request.url);
if (url.pathname === "/") {
return new Response(html, {
headers: {
'content-type': 'text/html;charset=UTF-8',
},
})
} else if (url.pathname === "/main.css") {
// TODO: return your stylesheet here.
} else {
return new Response("Not found", {status: 404});
}
}
Alternatively, if you meant to load the stylesheet from a different hostname, not from your worker, then you should change this line:
element.setAttribute("href", "main.css");
to contain a fully-qualified URL, like:
element.setAttribute("href", "https://example.com/main.css");

Firebase popup signin popup-closed-by-user error

I am trying to use the Javascript client library for Firebase auth to sign in with a Google account and popup window. However, when I try to sign in, the signin window pops up, I select my Google account, and then it spends about 10 seconds loading (with the blue progress bar moving), then the popup window closes, and shortly after I get the following error message:
code: "auth/popup-closed-by-user"
message: "The popup has been closed by the user before finalizing the operation."
I have enabled Google signin in the authentication section of the Firebase web UI. Below is the code I am using which is pretty much directly copied from the Firebase docs. I have made no other changes to the project config. I started a new project just to test this and have simply run firebase init, enabling only hosting, and enabling Google signin in the authentication web UI.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Welcome to Firebase Hosting</title>
<script src="/__/firebase/7.14.6/firebase-app.js"></script>
<script src="/__/firebase/7.14.6/firebase-auth.js"></script>
<script src="/__/firebase/init.js"></script>
</head>
<body>
<button id="signin">sign in</button>
<button id="signout">sign out</button>
<script>
const provider = new firebase.auth.GoogleAuthProvider();
const signinButton = document.querySelector("#signin");
signinButton.addEventListener("click", () =>
firebase
.auth()
.signInWithPopup(provider)
.then(function (result) {
console.log("result", result);
})
.catch(function (error) {
console.error(error);
})
);
const signoutButton = document.querySelector("#signout");
signoutButton.addEventListener("click", () =>
firebase
.auth()
.signOut()
.then(function () {
console.log("signed out");
})
.catch(function (error) {
console.error(error);
})
);
</script>
</body>
</html>
See this issue: https://github.com/firebase/firebase-js-sdk/issues/3188.
For some users, this is resolved by adding the app domain to the list of authorized domains:
Firebase Console -> Auth -> Sign-In Method -> Authorized Domains -> Add (domain)
For some users this may be caused by the Firefox Containers feature, or by the Firefox Enhanced Tracking Protection feature, specifically its isolate other cross-site cookies feature.

CORS request made despite error in console

I'm fiddling around with Google Cloud Storage. I've created a simple Python Flask handler:
#!/usr/bin/env python3
import secrets
import flask
from flask_cors import CORS
from google.cloud import storage
app = flask.Flask(__name__)
CORS(app)
client = storage.Client()
bucket = client.get_bucket('<my-bucket>')
#app.route('/')
def get_upload_urls():
blob = bucket.blob('00000' + secrets.token_hex())
return flask.jsonify({
'url': blob.create_resumable_upload_session(),
})
if __name__ == '__main__':
app.run('0.0.0.0', 9999)
This is accompanied by a really simple web frontend:
index.html:
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="user-scalable=no,initial-scale=1,maximum-scale=1,minimum-scale=1,width=device-width">
<title>Test</title>
</head>
<body>
<input id="input" type="file" />
<button id="button">Upload</button>
<script src="index.js"></script>
</body>
</html>
index.js:
const input = document.getElementById('input')
const button = document.getElementById('button')
button.addEventListener('click', async () => {
const [ body ] = input.files
const response = await fetch('http://localhost:9999')
const { url } = await response.json()
await fetch(url, {
method: 'PUT',
body,
})
})
This frontend allows me to pick a file, and upload it to Google Cloud Storage using a resumable upload session created by the Python backend.
The problem with this is that it actually works. I'd expect the PUT request to fail, but it doesn't.
When a file has been selected and the upload button is pressed, the following errors are logged to the console:
index.html:1 Failed to load
https://www.googleapis.com/upload/storage/v1/b//o?uploadType=resumable&upload_id=:
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:3333' is therefore not allowed
access. If an opaque response serves your needs, set the request's
mode to 'no-cors' to fetch the resource with CORS disabled.
index.js:13 Uncaught (in promise) TypeError: Failed to fetch
async function (async)
button.addEventListener # index.js:5
However, the PUT request was made succesfully and the file shows up in the Google Cloud Storage. I can download it and it appears to be totally fine.
Why doesn't the PUT request fail despite the CORS error in the console?
Edit:
I'm just looking for an explanation, not for a workaround — I'm going to configure CORS properly anyway. I would just like to know why the request doesn't fail, and why fetch does reject.
#sideshowbarker was right, I had the same issue. CORS needs to be set also in PUT response in addition to OPTIONS preflight request. Then fetch will succeed (even though upload worked before).

podio API JS browser authentication and API calls

I'm quite newbee on API thing, been reading the documentation here for JAVASCRIPT client but I can't make things work, even on authentication part. I already have the client ID and ClientSecret from PODIO itself.
Basically, I want to get all podio data in a workspace in a JSON format using client side (browser only).
I've downloaded the library here and created an HTML file on my localhost and link the podio-js with following code. Getting this error "podio-js.js:1 Uncaught ReferenceError: require is not defined at podio-js.js:1". Do I need to install something such that loader thing to make this work?
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script type="text/javascript" src="lib/podio-js.js"></script>
<script type="text/javascript">
var podio = new PodioJS({
authType: 'server',
clientId: 'foo',
clientSecret: 'foo'
});
var redirectURL = 'http://localhost/PODIO-JS/podio-js-master/PODIO_CLIENT.html';
// Your request handler (for example in ExpressJS)
var action = function(request, response) {
var authCode = request.query.code;
var errorCode = request.query.error;
podio.isAuthenticated().then(function() {
// Ready to make API calls...
}).catch(function(err) {
if (typeof authCode !== 'undefined') {
podio.getAccessToken(authCode, redirectURL, function(err, response) {
// make API calls here
console.log (responsedata);
});
} else if (typeof errorCode !== 'undefined') {
// a problem occured
console.log(request.query.error_description);
} else {
// start authentication via link or redirect
console.log(podio.getAuthorizationURL(redirectURL));
}
});
</script>
</head>
<body>
</body>
</html>
You can only use the syntax PodioJS = require('podio-js') if you're working in an AMD environment, typically using requirejs.
You're using a good ol' HTML page instead, which means you have to follow the second part of the browser usage section found here: https://github.com/podio/podio-js#browser
From within the podio-js folder:
npm install -g browserify
npm run bundle
and then include dist/podio-js.js using a tag in your HTML page.
Note: once you've bundled the source, you can copy paste the compiled file wherever you want.

Categories

Resources