PWA app retruns No matching service worker detected - javascript

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

Related

API call returns image after I render the components

I'm using g-s-i a npm package to make calls to google images.
I'm unable to make this API call and, just after, render the application. I'm aware this has to do with async, but I have no idea how to use it here. I have tried many things with the function imageSearch, but nothing has worked.
I thank if someone can show me a solution to my problem.
My MWE:
HTML:
<!doctype html>
<html class="no-js" lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>Debug example</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="apple-touch-icon" href="/apple-touch-icon.png">
<!-- Place favicon.ico in the root directory -->
</head>
<body>
<h1>Debugger example</h1>
<div id="main">
</div>
</body>
<script type="module" src="./dist/bundle.js">
</script>
</html>
JS:
var gis = require('g-i-s'); // search images from google https://www.npmjs.com/package/g-i-s
var main = document.querySelector("#main")
// Query examples
var searchTopics = [
{
searchTerm: 'sleep',
queryStringAddition: '&tbs=ic:trans'
},
{
searchTerm: 'pony',
queryStringAddition: '&tbs=ic:trans',
filterOutDomains: ['deviantart.net', 'deviantart.com']
}
];
var imageSearch = (query) => {
let response = [];
gis(query, (error, results) => {
console.log(results[1].url)
response.push(results[1].url)
}
)
return response;
};
// =results= look like:
// [
// {
// "url": "https://i.ytimg.com/vi/mW3S0u8bj58/maxresdefault.jpg",
// "width": 1280,
// "height": 720
// },
// {
// "url": "https://i.ytimg.com/vi/tntOCGkgt98/maxresdefault.jpg",
// "width": 1600,
// "height": 1200
// },
// (...)
// ]
var imageLayout = (title) =>
((src) => {let e = document.createElement("div")
e.innerHTML = title
let img = document.createElement("img")
img.src = src
e.appendChild(img)
return e})
var render = (queries) => {
queries.forEach((query) =>{
let img = imageSearch(query)
console.log(img)
main.appendChild(imageLayout(query.searchTerm)(img[0]))
})}
render(searchTopics)
NPM:
npm init
npm install g-i-s
npm install --save-dev browserify #babel/core #babel/preset-env babelify
browserify js/main.js > ./dist/bundle.js -t babelify
watchify js/*.js -o ./dist/bundle.js -d
What happens in my browser:
Your imageSearch function calls gis() which doesn't successfully create the response object until the callback passed as the second parameter to gis() is called. However, you're immediately returning the empty response array.
Instead, pass a callback in to imageSearch that gets called when gis() returns, something like this:
const imageSearch = (query, cb) => {
gis(query, (error, results) => cb(error, results[1].url));
};
const render = (queries) => {
queries.forEach((query) => {
let img = imageSearch(query, (error, img) => {
if (error) {
console.log("An error happened: ", error);
return;
}
main.appendChild(imageLayout(query.searchTerm)(img))
});
});
};
You could also move on to using Promises but that's a different matter, and would not largely change the outcome of the code, just the format of it.

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

Cordova -> face-api-js [Error] Failed to load resource: The requested URL was not found on this server. (null, line 0)

I have spent the last 4 days trying to resolve this issue. I'm finally at the point that no suggestions online have helped. I'm trying to build a "simple" cordova app that uses face-api.js for mood/expression detection on a real-time local camera feed. The setup is simple: video using iosrtc cordova plugin and then using face-api-js on a canvas overlay to draw face landmarks..etc.
I receive the following error when using safari console (as i'm testing directly on an ios device).
[Error] Failed to load resource: The requested URL was not found on this server. (null, line 0)
file:///private/var/containers/Bundle/Application/6ADC69C6-C6F1-45D9-B609-0C85B3E47C4A/Angel.app/www/null
The strange thing is that it seems that the data image resolves after a second or two. You can see that happening here:
Notice the images start to resolve as my "interval code" repeats:
Let's dive into the code:
HTML
<!DOCTYPE html>
<html>
<head>
<meta
http-equiv="Content-Security-Policy"
content=" media-src * blob: ; script-src * 'self' 'unsafe-inline' 'unsafe-eval'; connect-src * blob: http: https: 'self' 'unsafe-inline' 'unsafe-eval' http://*/* https://*/* https://*:* "
/>
<meta name="format-detection" content="telephone=no" />
<meta name="msapplication-tap-highlight" content="no" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no,viewport-fit=cover"
/>
<link rel="stylesheet" type="text/css" href="css/index.css" />
<link
href="https://fonts.googleapis.com/css?family=Roboto+Mono:400,500,700"
rel="stylesheet"
type="text/css"
/>
<link
href="https://fonts.googleapis.com/css?family=Roboto:400,500,700,400italic"
rel="stylesheet"
type="text/css"
/>
<link
href="https://fonts.googleapis.com/icon?family=Material+Icons"
rel="stylesheet"
type="text/css"
/>
<title>Angel</title>
</head>
<body>
<div class="app">
<!--*******************
local video stream
********************-->
<div class="local-stream" id="local-stream"></div>
</div>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/faceapi/face-api.js"></script>
<script type="text/javascript" src="js/main.js"></script>
</body>
</html>
JS:
document.addEventListener("deviceready", function () {
(async () => {
let MODEL_URL =
window.cordova.file.applicationDirectory + "www/assets/models/";
let videoContainer = document.getElementById("local-stream");
var localStream, localVideoEl;
localVideoEl = document.createElement("video");
localVideoEl.style.height = "250px";
localVideoEl.style.width = "250px";
localVideoEl.setAttribute("autoplay", "autoplay");
localVideoEl.setAttribute("playsinline", "playsinline");
localVideoEl.setAttribute("id", "video");
localVideoEl.setAttribute("class", "local-video");
videoContainer.appendChild(localVideoEl);
cordova.plugins.iosrtc.registerGlobals();
return navigator.mediaDevices
.getUserMedia({
video: true,
audio: true,
})
.then(function (stream) {
console.log("getUserMedia.stream", stream);
console.log("getUserMedia.stream.getTracks", stream.getTracks());
// Note: Expose for debug
localStream = stream;
// Attach local stream to video element
localVideoEl.srcObject = localStream;
//return localStream;
(async () => {
await faceapi.nets.ssdMobilenetv1.loadFromUri(
"MYHOSTEDMODELS(THIS WORKS FINE)"
);
await faceapi.nets.faceLandmark68Net.loadFromUri(
"MYHOSTEDMODELS(THIS WORKS FINE)"
);
await faceapi.nets.faceExpressionNet.loadFromUri(
"MYHOSTEDMODELS(THIS WORKS FINE)"
);
await faceapi.nets.faceRecognitionNet.loadFromUri(
"MYHOSTEDMODELS(THIS WORKS FINE)"
);
const video = document.getElementById("video");
const canvas = faceapi.createCanvasFromMedia(video);
videoContainer.append(canvas);
const dimensions = {
width: 250,
height: 250,
};
faceapi.matchDimensions(canvas, dimensions);
setInterval(async () => {
let detection = await faceapi
.detectAllFaces(video)
.withFaceLandmarks()
.withFaceExpressions()
.withFaceDescriptors();
let resizedDimensions = faceapi.resizeResults(
detection,
dimensions
);
//DRAW ON CAMERA IF YOU WANT.
canvas.getContext("2d").clearRect(0, 0, 250, 250);
faceapi.draw.drawDetections(canvas, resizedDimensions);
faceapi.draw.drawFaceLandmarks(canvas, resizedDimensions);
faceapi.draw.drawFaceExpressions(canvas, resizedDimensions);
}, 100);
})();
})
.catch(function (err) {
console.log("getUserMedia.error errrrr", err, err.stack);
});
})().then(() => {});
});
PLUGINS (package.json)
"cordova": {
"plugins": {
"cordova-plugin-whitelist": {},
"cordova.plugins.diagnostic": {},
"cordova-plugin-statusbar": {},
"cordova-plugin-background-mode": {},
"cordova-plugin-ipad-multitasking": {},
"cordova-custom-config": {},
"cordova-plugin-file": {},
"cordova-plugin-device": {},
"cordova-plugin-wkwebview-engine": {},
"#globules-io/cordova-plugin-ios-xhr": {},
"cordova-plugin-iosrtc": {
"MANUAL_INIT_AUDIO_DEVICE": "FALSE"
}
},
"platforms": [
"browser",
"ios"
]
},
ONE LAST NOTE: Video plays correctly. It's the face-api that seems to blow the entire thing up. ANY HELP WOULD BE MUCH APPRECIATED!!!!

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