I'm trying to add app to home screen via button located in "settings" page of my HTML5 mobile web app (Notice: It is working if I'm trying to add it via Chrome menu).
I've set up all of these steps:
The PWA must not already be installed
Web app must include a web app manifest.
Web app must be served over a secure HTTPS connection.
Web app has registered a service worker with a fetch event handler.
Currently I'm debugging it via Chrome Dev tools and listening to beforeinstallprompt with that code from official docs.
<script>
let deferredPrompt;
window.addEventListener('beforeinstallprompt', function(event) {
// Prevent Chrome 67 and earlier from automatically showing the prompt
e.preventDefault();
// Stash the event so it can be triggered later.
deferredPrompt = e;
});
// Installation must be done by a user gesture! Here, the button click
btnAdd.addEventListener('click', (e) => {
// hide our user interface that shows our A2HS button
btnAdd.style.display = 'none';
// Show the prompt
deferredPrompt.prompt();
// Wait for the user to respond to the prompt
deferredPrompt.userChoice
.then((choiceResult) => {
if (choiceResult.outcome === 'accepted') {
console.log('User accepted the A2HS prompt');
} else {
console.log('User dismissed the A2HS prompt');
}
deferredPrompt = null;
});
});
</script>
How to catch event on /home page, and pass it to /settings page so I could fire the event via (onClick) event?
Currently I'm using:
Angular CLI: 6.1.4
Node: 8.11.4
OS: win32 x64
Save it to global (window) object (or somewhere else with global access) and on /settings page in event handler call window.deferredPrompt.prompt()?
Related
I am creating userscript for messenger site I use. Is it possible to detect when site create notification pop up(usually on right bottom of screen) and get content of notification?
document.addEventListener('???', function(e) { // when I get notification popup(get message)
// and get content of notification
});
In websites I believe there's a Notifications API in which you can check here:
https://developer.mozilla.org/en-US/docs/Web/API/Notifications_API
It has all functions to request permissions, detect & listen to notifications on in websites. For example:
btn.addEventListener('click', function() {
let promise = Notification.requestPermission();
// wait for permission
})
At the moment I have an app with a "there's no internet conection" screen on it. This screen has a "Refresh" button that navigates the user to the previous screen, but it doesn't load anything, even when the internet connection is re-established.
onPressBack = () => {
const { navigation } = this.props;
navigation.goBack();
}
How can I refresh the app to force a componentDidMount() function to start over again to fetch all the stuff from the internet when the connection has been re-established?
You can use NetInfo to watch the internet connectivity. In the ComponentDidMount, you can addEventListener which takes an callback. Whenever the connection changes, the callback will be triggered. If the internet is connected, you can load your content/screen.
NetInfo.addEventListener(state => {
if(state.isConnected) {
// Load your content here
}
})
I want to use the add to homescreen function of pwa's.
I made a pwa of my app and for testing purposes Im using http-server to run it https://www.npmjs.com/package/http-server
When I run audits I get a score of 92. the only fail is "Does not redirect HTTP traffic to HTTPS". But passed audits include: "user can be prompted to Install the Web App" and "Site is served over HTTPS"
in chrome://flags/ I have 'bypass user engagement checks and app banners enabled'
For testing I'm listening to the beforeinstallprompt event, for now, I'm listening to the event in the ngoninit part of my homepage with:
window.addEventListener('beforeinstallprompt', e => {
console.log('beforeinstallprompt Event fired');
});
but when I press "add to home screen" in dev tools, nothing is logged in the console.
How can I catch the beforeinstallprompt-event?
Any help is greatly appreciated!
For Angular following code works for me:
you can test with Google Chrome developer tools
app.component.ts
import { Component, HostListener } from '#angular/core';
#Component({
selector: 'app-root',
template: '<button (click)="addToHomeScreen()" *ngIf="showButton">Add to Home Scree</button>',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
deferredPrompt: any;
showButton = false;
#HostListener('window:beforeinstallprompt', ['$event'])
onbeforeinstallprompt(e) {
console.log(e);
// Prevent Chrome 67 and earlier from automatically showing the prompt
e.preventDefault();
// Stash the event so it can be triggered later.
this.deferredPrompt = e;
this.showButton = true;
}
addToHomeScreen() {
// hide our user interface that shows our A2HS button
this.showButton = false;
// Show the prompt
this.deferredPrompt.prompt();
// Wait for the user to respond to the prompt
this.deferredPrompt.userChoice
.then((choiceResult) => {
if (choiceResult.outcome === 'accepted') {
console.log('User accepted the A2HS prompt');
} else {
console.log('User dismissed the A2HS prompt');
}
this.deferredPrompt = null;
});
}
}
'onbeforeinstallprompt' event is still not follows web standards
Reference : Add to Home Screen | Google Developers
GitHub Gist link
You can check this blog post about How to Use the 'beforeinstallprompt' Event to Create a Custom PWA Add to Homescreen Experience.
This is the sample code:
var deferredPrompt;
window.addEventListener('beforeinstallprompt', function (e) {
// Prevent Chrome 67 and earlier from automatically showing the prompt
e.preventDefault();
// Stash the event so it can be triggered later.
deferredPrompt = e;
showAddToHomeScreen();
});
function showAddToHomeScreen() {
var a2hsBtn = document.querySelector(".ad2hs-prompt");
a2hsBtn.style.display = "block";
a2hsBtn.addEventListener("click", addToHomeScreen);
}
function addToHomeScreen() {
var a2hsBtn = document.querySelector(".ad2hs-prompt"); // hide our user
interface that shows our A2HS button
a2hsBtn.style.display = 'none'; // Show the prompt
deferredPrompt.prompt(); // Wait for the user to respond to the prompt
deferredPrompt.userChoice
.then(function(choiceResult){
if (choiceResult.outcome === 'accepted') {
console.log('User accepted the A2HS prompt');
} else {
console.log('User dismissed the A2HS prompt');
}
deferredPrompt = null;
});}
The first thing you should do is create a variable outside the scope of the beforeinstallprompt event handler. This way you can reference it later. This handler saves a reference to the beforeinstallprompt event object. You can use this later to trigger the add to homescreen prompt on demand.
Note: Unlike service workers and the web manifest file the add to
homescreen prompt is not a web standard. This means browsers are and
always have been able to dictate how and if the user is prompted to
add a progressive web app to the homescreen.
Here is my code:
firebase.initializeApp(config);
if(!window.Notification){
alert('Not supported');
}else{
Notification.requestPermission().then(function(p){
if(p=='denied'){
alert('You denied to show notification');
}else if(p=='granted'){
alert('You allowed to show notification');
}
});
}
var database = firebase.database().ref("sensor/Motion");
database.on('child_added', function() {
$("#Mt").val("Motion detected");
$("#dateM").val( moment().format('LLL') );
if(Notification.permission!=='default'){
var notification = new Notification('Alert', {
icon: 'alert-icon-red.png',
body: "Motion detected!",
});
}else{
alert('Please allow the notification first');
}
Everything works fine in my desktop browser but on my Android device, when the screen is locked, it works for a few minute and after that it doesn't work. I get no notifications.
It sounds like your mobile browser is stopping tasks when the screen is locked, likely to improve battery life. That in general sounds like a good thing.
If you want to alert the user of an event that happens when they're not using their device, consider using Firebase Cloud Messaging for sending and handling those messages. This ensures it uses a communication channel that is more likely to be active when the user is not actively using the app.
Hi, I created app in which i get data from some server i want to that if internet is not connected then user will not able to use app. I put
document.addEventListener("deviceready", function(){ onDeviseReady(); }, false);
function onDeviseReady()
{
document.addEventListener("offline", offLine, false);
}
function offLine()
{
navigator.notification.alert(
'No Internet Connected',message,'Message','Done');
}
Now what i should do in function message(){} so that the user not be able to move here until user connected to the internet
i put in alert box in message function but this is not i want
PREFACE
Your app needs Internet Connection to run, so you should check either the device is connected to the internet or not. For that you can create a utility function (say hasConnection) which returns boolean true on internet connection or boolean false on no internet connection.
The hasConnection Function
function hasConnection() {
var networkState = navigator.network.connection.type;
if(networkState === Connection.NONE) {
return false;
}
return true;
}
And depending on the hasConnction return value you can take the right decision.
SAMPLE EXAMPLE
document.addEventListener('deviceready',onDeviceReady, false);
function onDeviceReady(){
if(!hasConnection()){ //there is no internet connection
navigator.notification.alert(
'No Internet Connection!', // message
function(){
/*
If you are using jQuery mobile for UI you can create a seperate page #no-connection-page and display that page :
$.mobile.changePage('#no-connection-page',{'chageHash':false});
*/
}, // callback
'Connection Required', // title
'OK' // buttonName
);
return false;
} else {
//There is internet Connection, get the data from server and display it to the end user
//Again, If you are using jQuery mobile, display the page that should be displayed only when Internet Connection is available
//$.mobile.changePage('#has-connection-page');
}
/*
If the device is connected to the internet while your app is running,
you can add a listener for 'online' event and take some action. For example :
*/
document.addEventListener('online', function(){
//Now the device has internet connection
//You can display the '#has-connection-page' :
//$.mobile.changePage('#has-connection-page');
});
//You can use the listener for 'offline' event to track the app if the connection has gone while the app is running.
}
ONE NOTE
Make sure that you have :
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
in android Manifest.
AT LAST
I am also creating android app using Phonepage / Cordova and jQuery-mobile that needs internet connection and using this approach, working fine for me. I hope it helps you.