Flutter web - How to redirect to root page (or any other page) when browser is refreshed? - flutter

I need to redirect to the root page when user tries to refresh the current page in browser. The default behavior is opening the same page. I tried to redirect using onBeforeUnload (this answer) and window.location.replace or Navigator.push but neither worked.

What worked for me is checking refresh status in JS (check reload), then redirecting. So I added a check before loading flutter code in index.html:
<script>
function isReload() {
try {
return (
(window.performance.navigation && window.performance.navigation.type === 1) ||
window.performance.getEntriesByType('navigation').map((nav) => nav.type).includes('reload')
);
} catch(err) {
return false;
}
}
if (isReload()) {
console.log("Page accessed by reload, redirecting...");
window.location.replace('/');
} else {
window.addEventListener('load', function(ev) {
// Download main.dart.js
_flutter.loader.loadEntrypoint({
serviceWorker: {
serviceWorkerVersion: serviceWorkerVersion,
}
}).then(function(engineInitializer) {
return engineInitializer.initializeEngine();
}).then(function(appRunner) {
return appRunner.runApp();
});
});
}
</script>

Related

Service worker returning Offline page instead of 404 page when non-existant file is requested

I'm using this service worker for caching and offline mode.
when I am already on any existing page of my website and I request a non-existent page, the Offline page is served instead of the 404 page.
If, on the other hand, I close and reopen the browser and immediately request a non-existent page of my website, the 404 page is served correctly.
I suspect it has to do with these last few lines of the code
if(!matching || matching.status == 404) { return cache.match("/service/offline/"); but i don't know how to fix this problem. Can you help me please?
Here's the full service worker:
self.addEventListener("install", function(event) {
event.waitUntil(preLoad());
});
var preLoad = function(){
console.log("Installing web app");
return caches.open("offline").then(function(cache) {
console.log("caching index and important routes");
return cache.addAll([
'/assets/css/about.min.css',
'favicon.ico',
'/assets/js/script.js',
'manifest.webmanifest.webmanifest',
'/',
'/about/',
'/contact/',
'/service/offline/'
]);
});
};
self.addEventListener("fetch", function(event) {
event.respondWith(checkResponse(event.request).catch(function() {
return returnFromCache(event.request);
}));
event.waitUntil(addToCache(event.request));
});
var checkResponse = function(request){
return new Promise(function(fulfill, reject) {
fetch(request).then(function(response){
if(response.status !== 404) {
fulfill(response);
} else {
reject();
}
}, reject);
});
};
var addToCache = function(request){
return caches.open("offline").then(function (cache) {
return fetch(request).then(function (response) {
console.log(response.url + " was cached");
return cache.put(request, response);
});
});
};
var returnFromCache = function(request){
return caches.open("offline").then(function (cache) {
return cache.match(request).then(function (matching) {
if(!matching || matching.status == 404) {
return cache.match("/service/offline/");
} else {
return matching;
}
});
});
};

unininstall PWA Manually

The following code can be used to install the program in the PWA:
var fab = document.querySelector('#fab');
var deferredPrompt;
fab.addEventListener('click', function () {
if (deferredPrompt) {
deferredPrompt.prompt();
deferredPrompt.userChoice.then(function (choice) {
if (choice.outcome === 'dismissed') {
console.log('installation was cancelled');
} else {
console.log('User Added To Home Screen');
}
});
deferredPrompt = null;
}
});
//********************************************************************
window.addEventListener('beforeinstallprompt', function (event) {
console.log('beforeinstallprompt run .');
event.preventDefault();
deferredPrompt = event;
return false;
});
now for Uninstall:
It can only be removed from the browser
Now my question is here:
Is it possible to create a code such as manual installation (mentioned above) that the user can uninstall the program without the need to use the browser tool?
Thank you all for your answers

Load more products not working in porto theme magento 2 on category page

I want infinite scrolling of product on category page but load more not working. I'm using porto theme.
Referece: https://prnt.sc/qvimev
<script>
require(["jquery"], function($) {
var url = $('.next').attr('href');
if (typeof url === "undefined") {
$('#load-more-product').html('');
}
$('#load-more-product-link').on('click', function() {
var url = $('.next').attr('href');
$('#load-more-product').hide();
$('#load-more-loader').show();
$.get(url, function(data) {
$('#load-more-loader').hide();
$('#load-more-product').show();
var result = $(data).find('.item.product.product-item');
var nxtUrl = $(data).find('.next').attr('href');
result.each(function(index, value) {
$('.products.list.items.product-items').append(value);
$("form[data-role='tocart-form']").catalogAddToCart();
});
if (typeof nxtUrl === "undefined") {
$('#load-more-product').html('<em>No More product in this Category.</em>');
} else {
$('.next').attr('href', nxtUrl);
}
});
});
});
</script>
Load More Infinite scroll is depends on Mageplaza Extension . so you need to make sure that Porto theme Mageplaza_LayeredNavigation Extension should be enabled

Vue.js 2 and auth0 authentication resulting with 'nonce'

I am trying to implement auth0 in my Vue.js 2 application.
I followed this link to implement the auth0 lock:
https://github.com/auth0-samples/auth0-vue-samples/tree/master/01-Login
This is my application in Login.vue:
HTML:
<div v-show="authenticated">
<button #click="logout()">Logout</button>
</div>
<div v-show="!authenticated">
<button #click="login()">Login</button>
</div>
Javascript:
function checkAuth() {
return !!localStorage.getItem('id_token');
}
export default {
name: 'login',
data() {
return {
localStorage,
authenticated: false,
secretThing: '',
lock: new Auth0Lock('clientId', 'domain')
}
},
events: {
'logout': function() {
this.logout();
}
},
mounted() {
console.log('mounted');
var self = this;
Vue.nextTick(function() {
self.authenticated = checkAuth();
self.lock.on('authenticated', (authResult) => {
console.log(authResult);
console.log('authenticated');
localStorage.setItem('id_token', authResult.idToken);
self.lock.getProfile(authResult.idToken, (error, profile) => {
if (error) {
console.log(error);
return;
} else {
console.log('no error');
}
localStorage.setItem('profile', JSON.stringify(profile));
self.authenticated = true;
});
});
self.lock.on('authorization_error', (error) => {
console.log(error);
});
});
},
methods: {
login() {
this.lock.show();
},
logout() {
localStorage.removeItem('id_token');
localStorage.removeItem('profile');
this.authenticated = false;
}
}
}
I am pretty sure that it already worked, but suddenly it doesnt work anymore.
My callbacks defined in auth0: http://127.0.0.1:8080/#/backend/login
That is also how I open the login in my browser.
When I login it I only get this in my localStorage:
Key: com.auth0.auth.14BK0_jsJtUZMxjiy~3HBYNg27H4Xyp
Value: {"nonce":"eKGLcD14uEduBS-3MUIQdupDrRWLkKuv"}
I also get redirected to http://127.0.0.1:8080/#/ so I do not see any network requests.
Does someone know where the problem is?
I ran the demo from auth0 with my Domain/Client and it worked without any problem.
Obviously I do not get any errors back in my console.
Atfer research I finally found the answer to my problem.
The reason, why it is not working is because my vue-router does not use the HTML5 History Mode (http://router.vuejs.org/en/essentials/history-mode.html).
To have it working without the history mode, I had to disable the redirect in my lock options and to disable auto parsing the hash:
lock: new Auth0Lock(
'clientId',
'domain', {
auth: {
autoParseHash: false,
redirect: false
}
}
)
Reference: https://github.com/auth0/lock

Facebook Session is not persisting from page - to - page

I am having a rough time with getting the facebook javascript SDK workflow to work. The requirement was to offer a "login" link, not a facebook icon. To do this, I improvised a bit. So far it works really well but the session is not persisting from page to page. I am figuring that the session gets set after the login method but it doesn't look like that. Here is login / logout which works fine:
function login() {
FB.login(function(response) {
if (response.session) {
FB.api('/me', function(response) {
document.getElementById('socialauth').innerHTML = "<span>Welcome, " + response.name + " </span>"
+ "(logout)";
});
} else {
}
}, { perms: 'email,publish_stream' });
return false;
}
function logout() {
FB.logout(function(response) {
document.getElementById('socialauth').innerHTML = "login";
});
}
And here is what I am testing with which doesn't fire:
$(document).ready(function() {
FB.getLoginStatus(function(response) {
if (response.status == "connected") {
// logged in and connected user, someone you know
alert("ok - 5 seconds has passed");
} else {
// no user session available, someone you dont know
alert("not ok");
}
});
});
I am also trying "javascript:document.cooike" in my URL box and see not evidence of the FB session.
Kindly advise?
You need to make sure your loading the Facebook SDK on each page as well. For a simple solution that uses jQuery check out https://github.com/xocialhost/jquery.xocialCore.js
The first two functions in the plugin deal with initializing FB and authentication.
Using the provided function you'd do something like this:
$(document).ready(function() {
$.xcInitFacebook = function({appId:'yourappid',callback:function() {
FB.getLoginStatus(function(response) {
if (response.status === 'connected') { alert('logged in'); }
else { alert('not logged in'); }
} });
});