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)
Related
i want to integrate PLAID system on my project based Laravel framework. Currently i'm developing on step to display Consent Pane PLAID from this doc PLAID LINK DOC. I'm using the javascript code. but i still failed to integrate it. here is my code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Plaid</title>
<script src="https://cdn.plaid.com/link/v2/stable/link-initialize.js"></script>
</head>
<body >
plaid
</body>
<script>
const handler = Plaid.create({
token: 'link-sandbox-xxx',
onSuccess: (public_token, metadata) => {
console.debug("onSuccess");
console.log('public_token: ' + public_token);
console.log('account ID: ' + metadata.account_id);
},
onLoad: () => {
console.debug("onLoad");
},
onExit: (err, metadata) => {
console.debug("onExit");
console.log('metadata ' + metadata);
},
onEvent: (eventName, metadata) => {
console.debug("onEvent");
},
receivedRedirectUri: "https://domainname.com/plaid",
});
handler.open();
</script>
</html>
Display error
POST https://sandbox.plaid.com/link/workflow/start 400 (Bad Request)
Error: oauth uri does not contain a valid oauth_state_id query parameter.
i already added new URL my API menu on PLAID Dashboard but still display this error.
Please help. How do i able to integrate that on my laravel?
The receivedRedirectUri should not be set when initializing Link for the first time. It is used when initializing Link for the second time, after returning from the OAuth redirect.
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";
i have this error when i try to host pwa on github the pea works fine locally but not on github why??
Failure reason
No matching service worker detected. You may need to reload the page, or check that the scope of the service worker for the current page encloses the scope and start URL from the manifest.
and this error in the console:
A bad HTTP response code (404) was received when fetching the script.
My repo name: PWAPP
My project structure
+- index.html
+- PWA *folder
| +- sw.js
| +- manifest.json
+- icon *folder has png image
// service-worker.js
//////////////////////////////////////////////////
var APP_PREFIX = 'ApplicationName_' // Identifier for this app (this needs to be consistent across every cache update)
var VERSION = 'version_01' // Version of the off-line cache (change this value everytime you want to update cache)
var CACHE_NAME = APP_PREFIX + VERSION
var URLS = [ // Add URL you want to cache in this list.
'/PWAPP/', // If you have separate JS/CSS files,
'/PWAPP/index.html' // add path to those files here
]
// Respond with cached resources
self.addEventListener('fetch', function(e) {
console.log('fetch request : ' + e.request.url)
e.respondWith(
caches.match(e.request).then(function(request) {
if (request) { // if cache is available, respond with cache
console.log('responding with cache : ' + e.request.url)
return request
} else { // if there are no cache, try fetching request
console.log('file is not cached, fetching : ' + e.request.url)
return fetch(e.request)
}
// You can omit if/else for console.log & put one line below like this too.
// return request || fetch(e.request)
})
)
})
// Cache resources
self.addEventListener('install', function(e) {
e.waitUntil(
caches.open(CACHE_NAME).then(function(cache) {
console.log('installing cache : ' + CACHE_NAME)
return cache.addAll(URLS)
})
)
})
// Delete outdated caches
self.addEventListener('activate', function(e) {
e.waitUntil(
caches.keys().then(function(keyList) {
// `keyList` contains all cache names under your username.github.io
// filter out ones that has this app prefix to create white list
var cacheWhitelist = keyList.filter(function(key) {
return key.indexOf(APP_PREFIX)
})
// add current cache name to white list
cacheWhitelist.push(CACHE_NAME)
return Promise.all(keyList.map(function(key, i) {
if (cacheWhitelist.indexOf(key) === -1) {
console.log('deleting cache : ' + keyList[i])
return caches.delete(keyList[i])
}
}))
})
)
})
/* manifest.json */
/* ---------------------------------------------- */
{
"name": "App Name",
"short_name": "App",
"start_url": "../",
"icons": [
{
"src": "../icons/manifest-icon-192.png",
"sizes": "192x192",
"type": "image/png",
"purpose": "maskable any"
},
{
"src": "../icons/manifest-icon-512.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "maskable any"
}
],
"theme_color": "#3367D6",
"background_color": "#3367D6",
"display": "fullscreen",
"orientation": "portrait"
}
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
<!-- META -->
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Prograssive Web App -->
<link rel="manifest" href="PWA/manifest.json">
<link rel="canonical" href="https://hasanqari.github.io/PWAPP/">
<!-- BS Style -->
<link rel="stylesheet" href="asset/css/BScss/bootstrap.min.css">
<link rel="stylesheet" href="asset/css/BScss/bootstrap.css">
<!-- Main Style -->
<link rel="stylesheet" href="asset/css/app.css">
<!-- App Icon -->
<link rel="shortcut icon" href="res/img/icon.svg" type="image/x-icon">
<!-- Title -->
<title>Document</title>
</head>
<body>
<main>
<div id="content-area-start-page" class="container mb-5">
<div id="frame-start-page" class="text-center align-content-center flex-column mt-5 py-3 px-4" style="border: 3px solid #ccc; border-radius: 50%;">
<img id="logo-start-page" src="res/img/icon.svg" alt="logo" class="img-fluid" width="70%">
<h5 id="app-name-start-page" class="mb-3">App Name</h6>
<p id="app-description-start-page">مرحبا بكم في [اسم التطبيق] سهل وسريع</p>
<a id="btn-next-start-page" class="btn btn-primary" href="">التالي</a>
</div>
</div>
</main>
<!-- BS Js -->
<script src="asset/js/BSjs/bootstrap.min.js"></script>
<script src="asset/js/BSjs/bootstrap.js"></script>
<!-- Main Js -->
<script src="asset/js/app.js"></script>
<!-- Extra Js -->
<script>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('PWAPP/service-worker.js', {
scope: '/PWAPP/'
})
// ('/service-worker.js')
.then(function(registration) {
console.log("success load");
console.log(registration);
})
.catch(function(err) {
console.log(err);
});
}
</script>
</body>
</html>
anybody can help me?
thank you so mush
function makeApiCall(){
gapi.client.load('calendar', 'v3', function () {
var request = gapi.client.calendar.events.insert
console.log(request);
({
'calendarId': '',
"resource": resource
});
});
}
Unless you have forgotten to post a section of your code you have probably forgotten to register the library, as well as authorizing the user.
<script src="https://apis.google.com/js/client:platform.js"></script>
full example using Google sign-in
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hello cal v3 </title>
<!-- Create a client id on Google developer console. Web credentials https://youtu.be/pBVAyU4pZOU -->
<meta name="google-signin-client_id"
content="YourClientId">
<meta name="google-signin-scope" content="https://www.googleapis.com/auth/calendar">
</head>
<body>
<h1>Hello cal v3 </h1>
<!-- The Sign-in button. This will run `getFileAsync()` on success. -->
<p class="g-signin2" data-onsuccess="makeacall"></p>
<!-- The API response will be printed here. -->
<textarea cols="80" rows="20" id="query-output"></textarea>
<script>
// Query the API and print the results to the page.
async function makeacall() {
try {
await gapi.client.load('calendar', 'v3');
const response = gapi.client.calendar.events.insert({
calendarId: 'XXX',
resource: resource
});
displayResults(response)
} catch (e) {
console.error('Error getting files', e)
}
}
function displayResults(response) {
var formattedJson = JSON.stringify(response.result, null, 2);
document.getElementById('query-output').value = formattedJson;
}
</script>
<!-- Load the JavaScript API client and Sign-in library. -->
<script src="https://apis.google.com/js/client:platform.js"></script>
Redirect uri mismatch JavaScript origin error
Make sure that you have configured your web client properly on Google developer console and added the proper javascript origin. Simple solution for redirect_uri_mismatch error with JavaScript
you need to init gapi on page load
gapi.auth2.init({
client_id: 'xxxxxxxxxxx'
});
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