Display error html for offline mode in Angular 6 - javascript

I have an app that could go in to offline mode. For that i have implemented a HostListener which listens to apps events.
#HostListener('window:offline', ['$event']) onOffline() {
this.isOnline = false;
}
This works fine and I display an error message:
<div *ngIf="!isOnline">
<div class="network-div">
<mat-icon class="network-icon">cloud_off</mat-icon>
</div>
<p class="network-text">Network error - unable to connect.
Please try again or contact support if error persists, contact the NCR
support desk.</p>
</div>
When i go offline, i get the desired message, but now that internet is down, when i refresh, I get the usual google error message with that dinasour.
I can't render the error HTML in my angular component anymore since its running in offline mode. I need to render the above HTML when i refresh.
When i click on 'Offline' of developer tool, i render an HTML and below is the screenshot:
When i refresh the same page (still in offline mode),i receive the following:
How should i handle this?

if you are registering service worker you can try:
ngOnInit() {
if (!navigator.onLine) {
this.isOnline = false;
}
}
note that you should check it after build your project and serve it.

About the browser's cache visit: How to Enable Offline Browsing in Firefox
If you attach the event listener to document.body on a browser, Chrome couldn't work.
You can register listeners for these events:
using addEventListener on the window, document, or document.body
by setting .onoffline properties on document or document.body to a
JavaScript Function object.
by specifying onoffline="..."
attributes on the tag in the HTML markup.
A javascript
window.addEventListener('load', function() {
var status = document.getElementById("status");
var log = document.getElementById("log");
function updateOnlineStatus(event) {
var condition = navigator.onLine ? "online" : "offline";
status.className = condition;
status.innerHTML = condition.toUpperCase();
log.insertAdjacentHTML("beforeend", "Event: " + event.type + "; Status: " + condition);
}
window.addEventListener('online', updateOnlineStatus);
window.addEventListener('offline', updateOnlineStatus);
});

Go to the networks tab in your developer tools and see if the SW is registered and offline works by running Audit.

Related

Chrome, allow autoconnect for HID device

So I'm trying to read out a USB-scale thats connected to my pc. I use chrome's experimental HID api.
I use Tampermonekey as userscript injector to extend a website's functionality.
The script I inject looks like this:
navigator.hid.requestDevice({ filters: [{ vendorId: 0x0922, productId: 0x8003}] }).then((devices) => {
if (devices.length == 0) return;
devices[0].open().then(() => {
if(disconnected) {
disconnected = false
}
console.log("Opened device: " + devices[0].productName);
devices[0].addEventListener("inputreport", handleInputReport);
devices[0].sendReport(outputReportId, outputReport).then(() => {
console.log("Sent output report " + outputReportId);
});
});
});
When I run it just like this(inline) I get the message in chrome:
DOMException: Failed to execute 'requestDevice' on 'HID': Must be handling a user gesture to show a permission request.
Basically, the code needs to be inside an event listener and the listener needs to be triggered by user input to run.
Al fine and dandy, except that this has to be initialized hundreds of times a day. I tried running this code in edge and here it just works without user input.
Is there a way I can disable this security feature(completely or only for the site im using it on) in chrome? I know edge is based on chromium so I expect it to be possible, but am unable to find how/where
You can use HID.getDevices() to retrieve an HID device that the user has already granted access to.
My suggestion would be to check for the device you want with getDevices first. If you can't find the device, then make something the user can interact with that will allow you to use requestDevice to connect to the device.

JavaScript dialogs alert(), confirm() and prompt() in cross origin iframe does not work any longer

Apps script web app works in <iframe>. It seems Chrome is no longer supporting alert(), confirm(), Promote these functions on the web app.
Any workaround to this?
Chrome Version 92.0.4515.107 (Official Build) (64-bit) -- does not work
Edge Version 91.0.864.71 (Official build) (64-bit) -- works
Tried replacing alert() with window.alert(), but still does not work.
exec:1 A different origin subframe tried to create a JavaScript dialog. This is no longer allowed and was blocked. See https://www.chromestatus.com/feature/5148698084376576 for more details.
This is absurd and subjective decision of Google to remove alert(), confirm(), and prompt() for cross origin iframes. And they called it "feature". And justification is very poor - see "motivation" bellow. A very weak reason for removing such an important feature! Community and developers should protest!
Problem
https://www.chromestatus.com/feature/5148698084376576
Feature: Remove alert(), confirm(), and prompt for cross origin iframes
Chrome allows iframes to trigger Javascript dialogs, it shows “ says ...” when the iframe is the same origin as the top frame, and “An embedded page on this page says...” when the iframe is cross-origin. The current UX is confusing, and has previously led to spoofs where sites pretend the message comes from Chrome or a different website. Removing support for cross origin iframes’ ability to trigger the UI will prevent this kind of spoofing, and unblock further UI simplifications.
Motivation
The current UI for JS dialogs (in general, not just for the cross-origin subframe case) is confusing, because the message looks like the browser’s own UI. This has led to spoofs (particularly with window.prompt) where sites pretend that a particular message is coming from Chrome (e.g. 1,2,3). Chrome mitigates these spoofs by prefacing the message with “ says...”. However, when these alerts are coming from a cross-origin iframe, the UI is even more confusing because Chrome tries to explain the dialog is not coming from the browser itself or the top level page. Given the low usage of cross-origin iframe JS dialogs, the fact that when JS dialogs are used they are generally not required for the site’s primary functionality, and the difficulty in explaining reliably where the dialog is coming from, we propose removing JS dialogs for cross-origin iframes. This will also unblock our ability to further simplify the dialog by removing the hostname indication and making the dialog more obviously a part of the page (and not the browser) by moving it to the center of the content area. These changes are blocked on removing cross-origin support for JS dialogs, since otherwise these subframes could pretend their dialog is coming from the parent page.
Solution
Send message via Window.postMessage() from iframe to parent and show dialog via parent page. It is very elegant hack and shame on Google because before Chrome version 92 client saw alert dialog e.g. An embedded page iframe.com" says: ... (which was correct - client see real domain which invoked alert) but now with postMessage solution client will see a lie e.g. The page example.com" says: ... but alert was not invoked by example.com. Stupid google decision caused them to achieve the opposite effect - client will be much more confused now. Google's decision was hasty and they didn't think about the consequences. In case of prompt() and confirm() it is a little bit tricky via Window.postMessage() because we need to send result from top back to iframe.
What Google will do next? Disable Window.postMessage()? Déjà vu. We are back in Internet Explorer era... developers waste time by doing stupid hacks.
TL;DR: Demo
https://domain-a.netlify.app/parent.html
Code
With code bellow you can use overridden native alert(), confirm() and prompt() in cross origin iframe with minimum code change. There is no change for alert() usage. I case of confirm() and prompt() just add "await" keyword before it or feel free to use callback way in case you can not switch easily your sync functions to async functions. See all usage examples in iframe.html bellow.
Everything bad comes with something good - now I gained with this solution an advantage that iframe domain is not revealed (domain from address bar is now used in dialogs).
https://example-a.com/parent.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Parent (domain A)</title>
<script type="text/javascript" src="dialogs.js"></script>
</head>
<body>
<h1>Parent (domain A)</h1>
<iframe src="https://example-b.com/iframe.html">
</body>
</html>
https://example-b.com/iframe.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Iframe (domain B)</title>
<script type="text/javascript" src="dialogs.js"></script>
</head>
<body>
<h1>Iframe (domain B)</h1>
<script type="text/javascript">
alert('alert() forwarded from iframe.html');
confirm('confirm() forwarded from iframe.html via callback', (result) => {
console.log('confirm() result via callback: ', result);
});
prompt('prompt() forwarded from iframe.html via callback', null, (result) => {
console.log('prompt() result via callback: ', result);
});
(async () => {
var result1 = await confirm('confirm() forwarded from iframe.html via promise');
console.log('confirm() result via promise: ', result1);
var result2 = await prompt('prompt() forwarded from iframe.html via promise');
console.log('prompt() result via promise: ', result2);
})();
</script>
</body>
</html>
dialogs.js
(function() {
var id = 1,
store = {},
isIframe = (window === window.parent || window.opener) ? false : true;
// Send message
var sendMessage = function(windowToSend, data) {
windowToSend.postMessage(JSON.stringify(data), '*');
};
// Helper for overridden confirm() and prompt()
var processInteractiveDialog = function(data, callback) {
sendMessage(parent, data);
if (callback)
store[data.id] = callback;
else
return new Promise(resolve => { store[data.id] = resolve; })
};
// Override native dialog functions
if (isIframe) {
// alert()
window.alert = function(message) {
var data = { event : 'dialog', type : 'alert', message : message };
sendMessage(parent, data);
};
// confirm()
window.confirm = function(message, callback) {
var data = { event : 'dialog', type : 'confirm', id : id++, message : message };
return processInteractiveDialog(data, callback);
};
// prompt()
window.prompt = function(message, value, callback) {
var data = { event : 'dialog', type : 'prompt', id : id++, message : message, value : value || '' };
return processInteractiveDialog(data, callback);
};
}
// Listen to messages
window.addEventListener('message', function(event) {
try {
var data = JSON.parse(event.data);
}
catch (error) {
return;
}
if (!data || typeof data != 'object')
return;
if (data.event != 'dialog' || !data.type)
return;
// Initial message from iframe to parent
if (!isIframe) {
// alert()
if (data.type == 'alert')
alert(data.message)
// confirm()
else if (data.type == 'confirm') {
var data = { event : 'dialog', type : 'confirm', id : data.id, result : confirm(data.message) };
sendMessage(event.source, data);
}
// prompt()
else if (data.type == 'prompt') {
var data = { event : 'dialog', type : 'prompt', id : data.id, result : prompt(data.message, data.value) };
sendMessage(event.source, data);
}
}
// Response message from parent to iframe
else {
// confirm()
if (data.type == 'confirm') {
store[data.id](data.result);
delete store[data.id];
}
// prompt()
else if (data.type == 'prompt') {
store[data.id](data.result);
delete store[data.id];
}
}
}, false);
})();
File a feature request:
Consider filing a feature request using this Issue Tracker template.
I'd either request that an exception is made for Apps Script web apps, or that built-in methods for alert and confirm are added, similar to the existing alert and prompt dialogs, which currently work on Google editors.
Bug filed:
By the way, this behavior has been reported in Issue Tracker (as a bug):
Javascript in html files doesn't work
I'd consider starring it in order to keep track of it.
Workaround:
In the meanwhile, as others said, consider downgrading or changing the browser, or executing it with the following command line flag:
--disable-features="SuppressDifferentOriginSubframeJSDialogs"
Related question:
Chrome SuppressDifferentOriginSubframeJSDialogs setting override using JS?
So far, the only 'solution' for this is to add the following to your Chrome/Edge browser shortcut:
--disable-features="SuppressDifferentOriginSubframeJSDialogs"
Or downgrade your browser. Obviously neither of these are ideal. Google trying really hard to save us from ourselves here.

Web Share API permission missing

I'm trying to implement the Web Share Api functionality on my test web app but it doesn't seem I'm able to do it. This is the code:
const newVariable: any = navigator;
{newVariable && newVariable.share && <IconButton aria-label="Share" onClick={async (e) => {
try {
const id = await shareRepository.shareTrip(this.props.todolist)
const url = "https://something.com/share/" + id
await newVariable.share({
title: 'Check my todolist for ' + this.props.todolist.trip.departure + ' - ' + this.props.todolist.trip.arrival,
text: 'Check my todolist for ' + this.props.todolist.trip.departure + ' - ' + this.props.todolist.trip.arrival,
url: url,
})
} catch (error) {
alert(error)
}
}}>
<ShareIcon />
</IconButton>}
Every time I try on both Firefox and Safari for iOS, I'm getting an error saying:
NotAllowedError: the request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission.
If on those browser I try to share something from google.com I get the native dialog to choose with which app to share.
I cannot understand why. On this page there is no discussion about permission: https://developers.google.com/web/updates/2016/09/navigator-share
UPDATE:
on Chrome for android works just fine, on Firefox for Android doesn't work. On Chrome, Firefox and Safari (which I believe they use safari engine all three) is only working if I pass "" which means the page itself, or "https://something.com/share/", it breaks If I pass "https://something.com/share/"+id :/
For other future users where the current answer is too specific to that code. The root issue is that the share() method must be called from a user gesture.
If the method call was not triggered by user activation, return a promise rejected with with a "NotAllowedError" DOMException.
From the Web Share API.
A user activation is any of the following:
change
click
contextmenu
dblclick
mouseup
pointerup
reset
submit
touchend
I understood what was the issue, which is absolutely annoying.
So:
const id = await shareRepository.shareTrip(this.props.todolist)
This call is the one that is causing problems. If I comment it, on iOS there is no issue.
If I keep it I have no problem at all on Android but iOS will complain.
So I need to rethink the flow of the application to pass the id from outside the 'onClick' event.

Titanium: UIWebView worker doesn't work on Android

I am using JavaScript web worker technique inside UIWebView HTML pages to achieve background tasks in Titanium apps. It works fine on iOS but no luck on Android, I can't even figure out the error details. Here's the script code:
<script>
function startWorker(){
var worker = new Worker('/worker.js');
// message event handler
worker.onmessage = function (event) {
// logging
Ti.API.error( 'WebWorkerMessage:'+ JSON.stringify(event) );
// update the html page - not actually needed, just for demostration should the WebView be visible
document.getElementById('result').textContent = event.data;
// fire a titanium app event
Ti.App.fireEvent( "WORKER", { data: event.data } );
};
// error event handler
worker.onerror = function(event){
Ti.API.error( 'WebWorkerError:'+ JSON.stringify(event) );
};
}
</script>
The error handler is called as soon as this script is evaluated from my Alloy controller. I am testing this script on an Android 4.4.2 device, a log for this error is useless:
WebWorkerError:{"cancelBubble":false,"returnValue":true,"srcElement":{},"defaultPrevented":false,"timeStamp":1422484158088,"cancelable":true,"bubbles":false,"eventPhase":2,"currentTarget":{},"target":{},"type":"error"}
Any suggestions?

How to implement in-app-purchase using Cordova plugin?

Please tell me the way to implement in-app-purchase using Cordova plugin.
I'm developing Android application using Cordova.
There are some in-app-purchase plugins but I decide to use Cordova Purchase Plugin.
I did some setups along README.md of In-App Purchase for PhoneGap / Cordova iOS and Android.
As a result, I could call the Plugin using Demo of the Purchase Plugin for Cordova with my little modification. (See the following, it is a portion of code.)
app.initStore = function() {
if (!window.store) {
log('Store not available');
return;
}
// Enable maximum logging level
store.verbosity = store.DEBUG;
// Enable remote receipt validation
// store.validator = "https://api.fovea.cc:1982/check-purchase";
// Inform the store of your products
log('registerProducts');
store.register({
id: 'myProductA',
alias: 'myProductA',
type: store.CONSUMABLE
});
// When any product gets updated, refresh the HTML.
store.when("product").updated(function (p) {
console.info("app.renderIAP is called");
app.renderIAP(p);
});
// Log all errors
store.error(function(error) {
log('ERROR ' + error.code + ': ' + error.message);
});
// When purchase of an extra life is approved,
// deliver it... by displaying logs in the console.
store.when("myProductA").approved(function (order) {
log("You got a ProductA");
order.finish();
});
// When the store is ready (i.e. all products are loaded and in their "final"
// state), we hide the "loading" indicator.
//
// Note that the "ready" function will be called immediately if the store
// is already ready.
store.ready(function() {
var el = document.getElementById("loading-indicator");
console.info(el + "ready is called")
if (el)
el.style.display = 'none';
});
// When store is ready, activate the "refresh" button;
store.ready(function() {
var el = document.getElementById('refresh-button');
console.info(el + "ready is called and refresh-button show?");
if (el) {
el.style.display = 'block';
el.onclick = function(ev) {
store.refresh();
};
}
});
// Refresh the store.
//
// This will contact the server to check all registered products
// validity and ownership status.
//
// It's fine to do this only at application startup, as it could be
// pretty expensive.
log('refresh');
store.refresh();
};
It did not show 'Store not available' that is shown when plugin is not available, show 'registerProducts', and 'refresh.'
(*Of course I added 'myProductA' to in-app Products on Google Play Developer Console.)
But I noticed that the below function is not called.
store.when("product").updated(function (p)
And also I couldn't understand what the parameter should fill in it, so I commented out the below.
(*I did remove the comment out, but it still not working.)
store.validator = "https://api.fovea.cc:1982/check-purchase";
I guess those things make something wrong.
I'm not sure what is stack on me, so my question is not clearly.
I want some clues to solve it... or I shouldn't implement in-app-purchase using Cordova plugin?
Please give me your hand.
(I'm not fluent in English, so I'm sorry for any confusion.)
You can try this plugin as an alternative: https://github.com/AlexDisler/cordova-plugin-inapppurchase
Here's an example of loading products and making a purchase:
inAppPurchase
.buy('com.yourapp.consumable_prod1')
.then(function (data) {
// ...then mark it as consumed:
return inAppPurchase.consume(data.productType, data.receipt, data.signature);
})
.then(function () {
console.log('product was successfully consumed!');
})
.catch(function (err) {
console.log(err);
});
It supports both Android and iOS.
Step for Integrate In-App billing in Phone-gap app.
1>> clone this project in your pc from this link In-App billing Library
2>> using CMD go to your root directory of your phonegap application
3>> then run this command cordova plugin add /path/to/your/cloned project --variable BILLING_KEY="QWINMERR..........RIGR"
Notes : for BILLING_KEY go to Developer console then open your application and go to Service& APIs for more info Please refer attached screenshots

Categories

Resources