Exporting object in Webpack 5 - javascript

I'm building a JS library with Webpack and trying to export an object.
import jwt_decode from "jwt-decode";
console.log(location.hash.replace('#', ''));
export var upstream = {
user: {
getUserDetails: () => {
if (location.hash) {
return jwt_decode(location.hash.replace('#', ''));
} else {
return null;
}
}
}
}
In my client-side code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>UpStream</title>
</head>
<body>
<script src="http://localhost:8080/app.js"> <!--server is up, connects fine-->
</script>
<script>
console.log(upstream);
</script>
</body>
</html>
The console.log(); statement works as intended, but I cannot access the upstream object. Any pointers?

To be able to access upstream via window or just upstream you would need to ensure you specify the export as a Library with libraryTarget of 'window'.
Hopefully that helps!

Related

Uncaught (in promise) Error: 'args.method' must be a non-empty string

When trying to connect the metamask wallet with my local site i am getting this error
I am Using the eth_requestAccounts methord but getting the down err
inpage.js:8 Uncaught (in promise) Error: 'args.method' must be a non-empty string.
at o (inpage.js:8:31826)
at Object.invalidRequest (inpage.js:8:32276)
at l.request (inpage.js:1:37391)
at HTMLButtonElement.Connect (index.js:13:27)
this was the error being Printed on MY console
// HOW TO CONNECT YOUR METAMASK TO YOUR FRONTEND
const button = document.getElementById("ConnectButton");
//button.addEventListener('click',connect);
if (button) {
console.log("button successfully imported");
} else {
console.log("BUtton is not imported");
}
const Connect = async () => {
if (typeof window.ethereum !== "undefined") {
await window.ethereum.request({ methord: "eth_requestAccounts" });
button.innerHTML = "Connected";
} else {
button.innerHTML = "Pls install metamask";
}
};
button.addEventListener("click", Connect);
MY index.js
<!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>FUND ME</title>
</head>
<body>
<h1>HELLO WORLD
</h1>
<button id="ConnectButton">Connect</button>
<script src="index.js"></script>
</body>
</html>
MY index.html
It might likely be a typo error. You have methord instead of method

Exported functions are not defined. Parcel/Browserify

When I use a bundler to make my JS browser compatible my exported functions are not exported.
Error: (index):11 Uncaught TypeError: connect is not a function
at HTMLButtonElement.onclick ((index):11:46)
index.js (Same root file as index.html)
const {ethers} = require("ethers");
async function connect() {
if (typeof window.ethereum !== 'undefined') {
await ethereum.request({method: "eth_requestAccounts"});
}
}
module.exports = {
connect
}
index.html (Same root file as index.js)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>HTML 5 Boilerplate</title>
<script src="./index.js" type="module"></script>
</head>
<body>
<button id="connect" onclick="connect()"> Connect </button>
</body>
</html>
Using parcel, which auto creates a dist file and starts a local server.
Also tried browserify and had same issue.
Parcel supports script tag/elements of type module.
This code works for me but window.ethereum is undefined, it's related to MetaMask no?
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>HTML 5 Boilerplate</title>
</head>
<body>
<button id="connect">Connect</button>
<script type="module">
//Import your module
import something from "./index.js";
//Assign event listener to button
document
.getElementById("connect")
.addEventListener("click", function (event) {
something.connect();
});
console.log("something", something);
/* JavaScript module code here */
</script>
</body>
</html>
index.js
const { ethers } = require("ethers");
async function connect() {
console.log("Inside connect function");
console.log("window.etherum", window.ethereum);
console.log("ethers", ethers);
if (typeof window.ethereum !== "undefined") {
await ethereum.request({ method: "eth_requestAccounts" });
}
}
module.exports = {
connect,
};

Is there a specific way to route to different pages on a GitHub Pages site?

I have a GitHub Pages site hosted here. The splash page to open displays just fine, but once you click in the circle to transition to the next page, landing.html, you are met with a 404 error. I have tried every possible way I can think of to fix this; Absolute references, local references, completely rearranging my whole file organization system, and nothing is working.
Here is my index.html 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>Portfolio</title>
<link rel="stylesheet" type="text/css" href="./css/title.css"></link>
</head>
<body>
<div class="container">
<div class="x-shape" id="x-left"></div>
<div class="x-shape" id="x-right"></div>
<div class="ripple" hidden="true"></div>
<div class="white-line" id="line-ver"></div>
<div class="white-line" id="line-hor"></div>
</div>
<div class="title">AVRIE LATTA</div>
<script src="jquery-3.6.0.js"></script>
<script type="text/javascript" src="js/title.js"></script>
</body>
</html>
Here is my title.js file:
const openLanding = () => {
window.location.href = "/html/landing.html";
};
const closeTitle = () => {
$(".container").animate({
width: `${$(".container").width() * 0.1}`,
height: `${$(".container").height() * 0.1}`
}, 750, () => {
$(".container").animate({
width: `${$(".container").width() * 1000}`,
height: `${$(".container").height() * 1000}`
}, 1000, () => {
$(".container").animate({
opacity: "-=1"
}, 1000, () => {
$(".title").animate({
opacity: "-=1"
}, 1000, () => {
$(".title").animate({
width: '5%'
}, 1000, openLanding());
});
});
});
});
};
$('.container').click(() => {
closeTitle();
});
My files are organized as follows:
site
index.html
html
landing.html
js
title.js
See: https://docs.github.com/en/pages/getting-started-with-github-pages/about-github-pages#types-of-github-pages-sites
In your case, you are hosting a page from the repository webdevportfolio. This would be a 'project' site. This means that the files in that repository start from the root page https://avrielatta.github.io/webdevportfolio/
In your js/title.js file, you have the following line:
window.location.href = "/html/landing.html";
This navigates to https://avrielatta.github.io/html/landing.html
Thus, GitHub Pages is tries to find a landing.html in a html repository, or html/landing.html in your 'user' site repository avrielatta.github.io.
To access the proper files/pages from your webdevportfolio repository, you can do something like:
// relative location
window.location.href = "html/landing.html";
// direct location
window.location.href = "/webdevportfolio/html/landing.html";

Issue interfacing smart contract with the front end

I'm actually trying to write a simple smart contract with front end that takes a value from the user and saves that in the variable in the smart contract.
The index.html part of my project is
<!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">
<title>Example</title>
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div id="message"></div>
<form method="POST">
<div><input id= "message" name = "message" type= "text">
</div>
<div>
<button type="button" id="register">Register</button>
</div>
</div>
</form>
<script src="js/bootstrap.min.js"></script>
<script src="js/web3.min.js"></script>
<script src="js/truffle-contract.js"></script>
<script src="js/app.js"></script>
</body>
</html>
And app.js is
App = {
web3Provider: null,
contracts: {},
account: '0x0',
init: function() {
return App.initWeb3();
},
initWeb3: function() {
if (typeof web3 !== 'undefined') {
// If a web3 instance is already provided by Meta Mask.
App.web3Provider = web3.currentProvider;
web3 = new Web3(web3.currentProvider);
} else {
// Specify default instance if no web3 instance provided
App.web3Provider = new Web3.providers.HttpProvider('http://localhost:7545');
web3 = new Web3(App.web3Provider);
}
return App.initContract();
},
initContract: function() {
$.getJSON("HelloWorld.json", function(hello) {
// Instantiate a new truffle contract from the artifact
App.contracts.HelloWorld = TruffleContract(hello);
// Connect provider to interact with contract
App.contracts.HelloWorld.setProvider(App.web3Provider);
return App.bindEvents();
});
},
bindEvents: function() {
$(document).on('click', '#register', function(){ var msg = $('#message').val(); App.handleMessage(msg); });
},
handleMessage: function(msg){
var hwinstance;
App.contracts.HelloWorld.deployed().then(function(instance) {
hwinstance = instance;
return hwinstance.setMessage(msg);
}).then( function(result){
if(result.receipt.status == '0x01')
alert("successfully")
else
alert("failed due to revert")
}).catch( function(err){
alert("failed")
})
}
};
$(function() {
$(window).load(function() {
App.init();
console.log('starting app.js');
});
});
The smart contract code that I've written is
pragma solidity 0.5.16;
contract HelloWorld {
string private message = "hello world";
function getMessage() public view returns(string memory) {
return message;
}
function setMessage(string memory newMessage) public {
message = newMessage;
}
}
When I ran the commands truffle complie and truffle migrate, it showed no errors but when I ran 'npm run dev' the page says "Cannot GET /".
I'm not able to understand where the mistake is. Please help!
Is there any other way of interfacing the frontend to the smart contract?
Your local server cannot find your page either because it is in the wrong directory or the local server has not been installed. Run npm install --save-dev lite-server. In the package.json you should have something like
"script": {
"dev": "lite-server",
...
}
Move your index.html and App.js into src/ directory you create at the root of the project. Run npm run dev to check again. It should work. If you are interested in an easy to use truffle box with react, I have developed a truffle box with React + Material-UI. Take a look here https://github.com/rouftom/truffle-react-material

Workbox, staleWhileRevalidate called only once on image

I'm developing a PWA and I'm trying to use workbox to manage the service-worker and the caching of assets.
In my PWA I have to show all the newer images if the device is online and, if not, the images in the cache.
When I try to implement it I see that the staleWhileRevalidate method on image is called only once in the page for each image, also if I try to refresh multiple times. I need to close the webpage and when I reopen it the image is updated correctly. It's normal that it work in this way?
When I try it with localhost, the staleWhileRevalidate is called every time I reload the page, but when I load the website on a remote server, the app does not work anymore in this way.
service-worker.js:
importScripts('workbox-sw.prod.v2.0.0.js');
const workboxSW = new WorkboxSW();
var CACHE_NAME = 'my-cache';
var filesToCache = [
'imgs/images.png',
'index.html'
];
self.addEventListener('install', function(e) {
console.log('[ServiceWorker] Install');
e.waitUntil(
caches.open(CACHE_NAME).then(function(cache) {
console.log('[ServiceWorker] Caching App Shell');
return cache.addAll(filesToCache);
})
);
});
workboxSW.router.registerRoute(
/.*\/imgs\/(.*\/)?.*\.(png|jpg|jpeg|gif)/,
({event}) => {
console.log("staleWhileRevalidate called);
return workboxSW.strategies.staleWhileRevalidate({cacheName: CACHE_NAME}).handle({event}).catch((error) => {
console.log("Error staleWhileRevalidate");
return error;
});
}
);
index.html:
<!DOCTYPE html>
<html>
<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 class="title">PWA</title>
</head>
<body>
<div class="container">
<img src="imgs/image.png">
</div>
<script>
if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
navigator.serviceWorker.register('service-worker.js').then(function(registration) {
console.log('ServiceWorker registration successful);
}, function(err) {
console.log('ServiceWorker registration failed: ', err);
});
});
}
</script>
</body>
</html>
Installing (not in localhost)
First Reload (not in localhost)
Second Reload (and more times)

Categories

Resources