is there a way to check if the PWA was launched through a file or not? - progressive-web-apps

I'm using the file handle API to give my web app the optional capability to launch through double-clicking files in the file explorer.
Writing the code below, I expected if (!("files" in LaunchParams.prototype)) to check if a file was used to launch the app, but apparently, it checks if the feature is supported. OK, that makes sense.
After that, I thought the setConsumer callback would be called in any launch scenario, and files.length would be zero if the app was launched in other ways (like by typing the URL in the browser). But on those use cases, the callback was not called at all, and my init logic was never executed.
if (!("launchQueue" in window)) return textRecord.open('a welcome text');
if (!("files" in LaunchParams.prototype)) return textRecord.open('a welcome text');
launchQueue.setConsumer((launchParams) => {
if (launchParams.files.length <= 0) return textRecord.open('a welcome text');
const fileHandle = launchParams.files[0];
textRecord.open(fileHandle);
});
I've also followed the Launch Handler API article instructions and enabled the experimental API.
The new code confirms that "targetURL" in LaunchParams.prototype is true, but the setConsumer callback is not executed if the user accesses the web app through a standard browser tab.
function updateIfLaunchedByFile(textRecord) {
if (!("launchQueue" in window)) return;
if (!("files" in LaunchParams.prototype)) return;
console.log({
'"targetURL" in LaunchParams': "targetURL" in LaunchParams.prototype,
});
// this is always undefined
console.log({ "LaunchParams.targetURL": LaunchParams.targetURL });
// setConsumer does not trigger if the app is not launched by file, so it is not a good place to branch what to do in every launch situation
launchQueue.setConsumer((launchParams) => {
// this never run in a normal tab
console.log({ setConsumer: launchParams });
if (launchParams.files.length <= 0) return;
const fileHandle = launchParams.files[0];
textRecord.open(fileHandle);
});
}
This is the result...
Is there a universal way to check if the web app was launched through a file?

Check out the Launch Handler origin trial. It lets you determine the launch behavior exactly and lets your app detect how the launch happened. This API works well together with the File Handling API that you already use. You could, for example, check the LaunchParams.targetURL to see how the app was launched. Your feedback is very welcome.

Since I was not able to guarantee that the setConsumer callback was called in every situation (especially when the app is launched in a regular browser tab), I hacked it through setTimeout:
function wasFileLaunched() {
if (!("launchQueue" in window)) return;
if (!("files" in LaunchParams.prototype)) return;
return new Promise((resolve) => {
let invoked = false;
// setConsumer does not triggers if the app is not launched by file, so it is not a good place to branch what to do in every launch situation
launchQueue.setConsumer((launchParams) => {
invoked = true;
if (launchParams.files.length <= 0) return resolve();
const fileHandle = launchParams.files[0];
resolve(fileHandle);
});
setTimeout(() => {
console.log({ "setTimeout invoked =": invoked });
if (!invoked) resolve();
}, 10);
});
}

Related

Flutter web PWA install prompt from within the app

I'm working on a Flutter Web PWA app and having trouble with triggering the Add To Home Screen prompt from within the flutter app. I understand it can be triggered using Javascript with the code below, but how do I do this from my Flutter dart file?
buttonInstall.addEventListener('click', (e) => {
// Hide the app provided install promotion
hideMyInstallPromotion();
// Show the install 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 install prompt');
} else {
console.log('User dismissed the install prompt');
}
})
});
Currently, Flutter web can only prompt PWA installs from the browser. The issue with displaying PWA install prompt is it breaks the compatibility/design with Android/iOS builds as the feature is web-specific.
A different approach that you can take here is by displaying "PWA install" reminders when the app is run on web. Otherwise, it's best to file this as a feature request.
I created the pwa_install package specifically for this purpose.
1. Update index.html
<!-- Capture PWA install prompt event -->
<script>
let deferredPrompt;
window.addEventListener('beforeinstallprompt', (e) => {
deferredPrompt = e;
});
function promptInstall(){
deferredPrompt.prompt();
}
// Listen for app install event
window.addEventListener('appinstalled', () => {
deferredPrompt = null;
appInstalled();
});
// Track how PWA was launched (either from browser or as PWA)
function getLaunchMode() {
const isStandalone = window.matchMedia('(display-mode: standalone)').matches;
if(deferredPrompt) hasPrompt();
if (document.referrer.startsWith('android-app://')) {
appLaunchedAsTWA();
} else if (navigator.standalone || isStandalone) {
appLaunchedAsPWA();
} else {
window.appLaunchedInBrowser();
}
}
</script>
2. Call PWAInstall().setup()
You can call this method in main.dart before calling runApp()
Future<void> main() async {
// Add this
PWAInstall().setup(installCallback: () {
debugPrint('APP INSTALLED!');
});
runApp(MaterialApp(home: App()));
}
3. Check if the Install Prompt is enabled
Before calling the promptInstall_() method, you can check if the Install Prompt is available using PWAInstall().installPromptEnabled.
installPromptEnabled will be true if:
The app was launched in a browser (It doesn't make sense to prompt a PWA install if the app is already running as a PWA)
The beforeinstallprompt event was captured.
promptInstall_() won't do anything if installPromptEnabled is false so you should check this flag before attempting to call the prompt.
4. Call PWAInstall().promptInstall_()
Finally, call PWAInstall().promptInstall_() to show the install prompt.
Note that this will not work on Safari since Safari does not implement the beforeinstallprompt method this package relies on.

How can I keep the BarcodeScanner screen open without redirecting me to another page?

I am making an application that allows me to scan QR codes, and I managed to make the code work but my doubt is that when I scan the plugin phonegap-plugin-barcodescanner takes me out of the camera interface, what I want to do is to stay in it and show me an alert with the scanned code, and to give it ok in the alert to stay in it, to avoid being clicked to enter it.
I'm working with the plugin phonegap-plugin-barcodescanner, in ionic 3
public scanQR2() {
this._ButtonText = "Escanear";
this._barcodeScanner.scan().then((barcodeData) => {
if (barcodeData.cancelled) {
console.log("User cancelled the action!");
this._ButtonText = "Escanear";
return false;
}
console.log("Scanned successfully!");
console.log(barcodeData);
}, (err) => {
console.log(err);
});
}
I hope that the application when performing a scan stays on the same interface and does not redirect me to another page

How to stop all JS scripts in Puppeteer

I would like to be able to stop any scripts from being able to run in puppeteer after the page has loaded. The reason for this is to stop carousel images and lazy loading images and essentially get the page to behave as statically as possible to enable screenshots where the images aren't changing etc.
By doing page.evaluate('debugger;') it is possible to pause the whole script, but this does not let you continue with taking screen shots as the a evaluate function does not exit until you exit the debugger (If the gui is enabled)
const page = await browser.newPage()
page.setJavaScriptEnabled(false)
If you would like to disable JavaScript after the page has loaded, you can use debugger:
await page.evaluate(() => {
debugger;
});
I was able to take screenshots after using the debugger.
Alternatively, you can replace each original node with its clone to remove the events attached to each element:
await page.evaluate(() => {
document.querySelectorAll('*').forEach(element => {
element.parentNode.replaceChild(element.cloneNode(true), element);
});
});
You can also use removeEventListener() in a loop similar to the one above to remove specific events attached to a node.
Otherwise, if you can disable JavaScript before the page has loaded, you can use page.setJavaScriptEnabled() before navigating to the page:
await page.setJavaScriptEnabled(false);
A better solution is just to block all requests with the type equals to script:
const puppeteer = require("puppeteer");
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setRequestInterception(true);
page.on("request", request => {
if (request.resourceType() === "script") {
request.abort()
} else {
request.continue()
}
})
await page.goto("https://stackoverflow.com/")
await browser.close()
})()
Source: Disabling JavaScript Using Puppeteer
If you want to freeze the page and still be able to call evaluate on it, you can
navigate to the page, wait for it to load (and maybe let its JavaScript make some DOM transformations),
get HTML snapshot of the page,
disable JavaScript,
reload the page statically (no DOM transformations will occur since JavaScript is disabled),
profit (do any amount of evaluate or screenshots on a DOM that is guaranteed to stay the same).
await page.goto('<url>', { waitUntil: 'networkidle0' }); // 1
const html = await page.content(); // 2
page.setJavaScriptEnabled(false); // 3
await page.setContent(html, { waitUntil: 'networkidle0' }); // 4
After phoning a friend the following seems to work:
await page.evaluate('document.body.innerHTML = document.body.innerHTML')

Kill the page from loading feather

I am using Ionic 2 and would like to kill the page from feather loading similar to PHP die(); function
Below is the method that I currently working with.
fetch_data() {
let loader = this.loadingCtrl.create({ content: 'Loading...' });
loader.present();
this.bank.types().subscribe( response => {
this.linkBankTypes = response.results;
loader.dismiss();
}, err => {
loader.dismiss();
loader = this.loadingCtrl.create({ content: 'No Internet connection. Make sure Wi-Fi or cellular data is turned on, then try again.' });
//Kill the page from here
});
}
PHP's die() function stops creation of the page and lets PHP run environment to return a nasty error message to the client browser.
You can cause the Ionic to crash by throwing exceptions, but that is not a pleasant user experience and not recommended.
Instead you either navigate to an error page or show a message indicating the error.
The NavController's push or popcan be used to navigate to an error page or back to the previous page.

How to wait the page to test is loaded in non angular site?

I've tried this:
browser.wait(function () {
return browser.executeScript('return document.readyState==="complete" &&' +
' jQuery !== undefined && jQuery.active==0;').then(function (text) {
return text === true;
});
}, 30000);
If jQuery.active==0 then page is completely loaded. This should work for sites with JQuery and non angular pages.
However, I have many problems of instability to test for non angular sites.
How to fix this?
By default protractor waits until the page is loaded completely. If you are facing any error then it is because protractor is waiting for the default time to be completed, that you have specified in your conf.js file to wait until page loads. Change the value to wait a for longer time if you think your app is slow -
// How long to wait for a page to load.
getPageTimeout: 10000, //Increase this time to whatever you think is better
You can also increase the defaultTimeoutInterval to make protractor wait a little longer before the test fails -
jasmineNodeOpts: {
// Default time to wait in ms before a test fails.
defaultTimeoutInterval: 30000
},
If you want to wait for any particular element, then you can do so by using wait() function. Probably waiting for last element to load is the best way to test it. Here's how -
var EC = protractor.ExpectedConditions;
var lastElement = element(LOCATOR_OF_LAST_ELEMENT);
browser.wait(EC.visibilityOf(lastElement), 10000).then(function(){ //Alternatively change the visibilityOf to presenceOf to check for the element's presence only
//Perform operation on the last element
});
Hope it helps.
I use ExpectedConditions to wait for, and verify page loads. I walk through it a bit on my site, and example code on GitHub. Here's the gist...
Base Page: (gets extended by all page objects)
// wait for & verify correct page is loaded
this.at = function() {
var that = this;
return browser.wait(function() {
// call the page's pageLoaded method
return that.pageLoaded();
}, 5000);
};
// navigate to a page
this.to = function() {
browser.get(this.url, 5000);
// wait and verify we're on the expected page
return this.at();
};
...
Page Object:
var QsHomePage = function() {
this.url = 'http://qualityshepherd.com';
// pageLoaded uses Expected Conditions `and()`, that allows us to use
// any number of functions to wait for, and test we're on a given page
this.pageLoaded = this.and(
this.hasText($('h1.site-title'), 'Quality Shepherd')
...
};
QsHomePage.prototype = basePage; // extend basePage
module.exports = new QsHomePage();
The page object may contain a url (if direct access is possible), and a pageLoaded property that returns the ExepectedCondition function that we use to prove the page is loaded (and the right page).
Usage:
describe('Quality Shepherd blog', function() {
beforeEach(function() {
// go to page
qsHomePage.to();
});
it('home link should navigate home', function() {
qsHomePage.homeLink.click();
// wait and verify we're on expected page
expect(qsHomePage.at()).toBe(true);
});
});
Calling at() calls the ExpectedCondidion (which can be be an and() or an or(), etc...).
Hope this helps...