Why is this this error: Failed to execute 'fetch' on 'ServiceWorkerGlobalScope': 'only-if-cached' can be set only with 'same-origin' mode [duplicate] - service-worker

After upgrading to Chrome 64, I realized that this error appears when I load my page on a new tab.
I can't identify where it is on the service worker. Here is my code to run the fetch:
self.addEventListener('fetch', function(event) {
if (event.request.url.startsWith(self.location.origin)) {
event.respondWith(
caches.match(event.request).then(function(response) {
return response || fetch(event.request).then(function(fetch_resp){
return fetch_resp;
});
})
);
}
});
Could anyone here, who has more knowledge about service worker, help me to solve this error?

I believe this is a Chromium bug that has been reported here. Hopefully it will be fixed soon or some more information about the issue will be published.
Paul Irish implemented a temporary work around, which is as follows:
if (e.request.cache === 'only-if-cached' && e.request.mode !== 'same-origin') {
return;
}
I ran it inside the callback for the service worker install and fetch listeners and it prevented the error.
You can see the full commit of Paul's code here.

For those searching for this again, seems like it popped up after a while again when someone opens the devtools you can still see the error mentioned in the question.
See (new) bug report here: https://bugs.chromium.org/p/chromium/issues/detail?id=1098389
So let's hope this will be fixed again soon!

perhaps the cache name is not unique from other applications, seems to fix the issue for me.

Related

Electron app crashes on print ubuntu 20.04 Linux

It's been a week I am struggling with this problem. I've searched throughout the web and found many answers but none of them worked for me and also most of the topics relating to this problem are unsolved in various forums as well.
Whenever my application executes the following line of code from the main process it crashes :
win.webContents.print();
Following is the crash report:
'''
I've tried the option:
win.webContents.print({silent: true}, (success, error) => {
if(success) {
console.log("Printed...");
}else {
console.log(error);
}
});
'''
No matter what I do, I get the same crash report.
Furthermore, If I print from the console of the browser window, the same crash occurs,
'''
With the same error as shown below :
'''
I am very close to the deadline of a project in which I have to integrate a printing facility to the POS thermal receipt printer, and can not find any solutions.
Also, I've used other libraries like electron-pos-printer, But internally, it uses the same concept and codes for printing, and thus, this way also failed.
It's really frustrating... Need help !!!

Electron auto update fails silently when installing update on Windows

I have an electron app which uses electron-builder for building, packing & publishing the app.
I have the following auto-update code:
autoUpdater.logger = log;
autoUpdater.logger.transports.file.level = "info";
autoUpdater.autoDownload = true;
const updateCheck = () => {
autoUpdater.checkForUpdates().then(resp => {
log.info("autoUpdate response:");
log.info(resp);
});
};
app.on("ready", async () => {
log.info(`Version: ${app.getVersion()}`);
autoUpdater.on("update-downloaded", () => {
log.info("update downloaded");
setImmediate(() => {
try {
log.info("installing update");
// app.relaunch();
autoUpdater.quitAndInstall();
} catch (err) {
log.error("Error installing update");
log.error(err);
}
});
});
autoUpdater.on("error", err => {
log.error("AutoUpdater error");
log.error(err);
});
updateCheck();
schedule.scheduleJob("*/10 * * * *", updateCheck);
});
When I publish a new version, the auto-updater detects it, downloads it successfully, and then tries to install it.
During installation of the update, the progress bar fills up halfway, then disappears.
The app remains closed and does not automatically relaunch after the progress bar disappears.
When I re-launch it manually, it is still the old version. It detects that there is an update which has already downloaded, and tries to install it, with the same result (progress bar fills halfway then disappears, app remains closed after).
My log file shows no errors, either from the catch block or the autoUpdater.on("error") callback.
The location C:\Users\<User>\AppData\Local\<app-name>-updater has an installer.exe file which installs the previous version, and a pending folder which contains an installer for the new version. Manually executing this installer causes the app to be updated with no errors.
I tried testing using checkForUpdatesAndNotify instead of checkForUpdates (and commenting out the call to quitAndInstall), and it worked as advertised, however I would like to ensure the update is installed immediately rather than wait for the user to quit on their own.
How can I debug this further? Why am I not seeing any errors? Where should I be looking for them? What am I doing wrong?
The problem turned out to be the fact that I created the window with the option closable: false, preventing the auto updater from closing it. The auto updater works perfectly after removing this setting
Quick question: have you used
this answer to make your App window closed and minimizable to tray?
If you did, You should application.isQuiting = true before calling autoUpdater.quitAndInstall();
otherwise the application.close() function is pretty much blocked from anywhere other then the contextMenu.
I was facing the same issue and I did a lot of RnD. After trying for few days I found that there was no issue with the auto updater instead it was the issue with the file name I was uploading on my server. Make sure your exe file name for every new version is different otherwise it will not install after auto update.
For eg.
setup_0.0.1.exe than your next version file should be setup_0.0.2.exe
Make sure to update the file name in latest.yml and blockmap file as well.

Any way yet to auto-update (or just clear the cache on) a PWA on iOS?

I have been struggling on iOS with something that works easily on Android: Getting my PWA to auto-update when there is a new version. I am not at all sure this is even possible on iOS. I have used vue.js and Quasar to build my app, and everything works out of the box on Android. Here is the (ugly, terrible) way things stand currently on the iOS version:
I can check my own server for the version and compare it against the current one stored in my app (in indexedDB) and throw up a notice that there is a new version. So far so good.
Other than having the user MANUALLY CLEAR THE SAFARI CACHE (!!) there is no way I can figure out how to programmatically clear the PWA cache from within the app or force an upload in another way.
So at this point I guess my questions are:
Has ANYONE been able to get a PWA on iOS (11.3 or later) to auto-update when a new version is available?
Is there a way to clear the (safari) app cache from within my PWA?
Obviously it is an incredibly awful user experience to notify the user that in order to update they must perform several steps outside of the app to be able to refresh it, but it seems this is where iOS stands at the moment unless I am missing something. Has anyone anywhere made this work?
After weeks and weeks of searching, I finally found a solution:
I add a check for versionstring on the server, and return it to the app as mentioned above.
I look for it in localtstorage (IndexedDB) and if I don’t find it, I add it. If I do find it, I compare versions and if there is a newer one on the server, I throw up a dialog.
Dismissing this dialog (my button is labeled “update”) runs window.location.reload(true) and then stores the new versionstring in localstorage
Voila! My app is updated! I can't believe it came down to something this simple, I could not find a solution anywhere. Hope this helps someone else!
UPDATE SEPT 2019:
There were a few problems with the technique above, notably that it was bypassing the PWA service worker mechanisms and that sometimes reload would not immediately load new content (because the current SW would not release the page). I have now a new solution to this that seems to work on all platforms:
function forceSWupdate() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.getRegistrations().then(function (registrations) {
for (let registration of registrations) {
registration.update()
}
})
}
}
forceSWupdate()
And inside my serviceworker I now throw up the dialog if there is an update, and do my location.reload(true) from there. This always results in my app being refreshed immediately (with the important caveat that I have added skipWaiting and clientsClaim directives to my registration).
This works on every platform the same, and I can programatically check for the update or wait for the service worker to do it by itself (although the times it checks vary greatly by platform, device, and other unknowable factors. Usually not more than 24 hours though.)
If anyone is still having issues with this, registration.update() did not work for me. I used the exact solution but when the version from my server did not match my local stored version, I had to unregister the service workers for it to work.
if ('serviceWorker' in navigator) {
await this.setState({ loadingMessage: 'Updating Your Experience' })
navigator.serviceWorker.getRegistrations().then(function(registrations) {
registrations.map(r => {
r.unregister()
})
})
await AsyncStorage.setItem('appVersion', this.state.serverAppVersion)
window.location.reload(true)
}
Then when the app reloads, the service worker is reregistered and the current version of the app is visible on iOS safari browsers and 'bookmarked' PWAs.
Instead of prompting the user, that a new version is available, you can also extend the 'activate' Eventlistener to delete your old cache whenever you publish a new serviceworker version.
Add version and name variables
var version = "v3" // increase for new version
var staticCacheName = version + "_pwa-static";
var dynamicCacheName = version + "_pwa-dynamic";
Delete caches, when their names do not fit the current version:
self.addEventListener('activate', function(event) {
event.waitUntil(
caches.keys().then(function(cacheNames) {
return Promise.all(
cacheNames.filter(function(cacheName) {
if (!cacheName.startsWith(staticCacheName) &&
!cacheName.startsWith(dynamicCacheName)) {
return true;
}
}).map(function(cacheName) {
console.log('Removing old cache.', cacheName);
return caches.delete(cacheName);
})
);
})
);
});
(credits: https://stackoverflow.com/a/45468998/14678591)
In order to make this work for iOS safari browsers and 'bookmarked' PWAs too, I just added the sligthly reduced function by #jbone107:
self.addEventListener('activate', function(event) {
event.waitUntil(
caches.keys().then(function(cacheNames) {
return Promise.all(
cacheNames.filter(function(cacheName) {
if (!cacheName.startsWith(staticCacheName) &&
!cacheName.startsWith(dynamicCacheName)) {
return true;
}
}).map(function(cacheName) {
// completely deregister for ios to get changes too
console.log('deregistering Serviceworker')
if ('serviceWorker' in navigator) {
navigator.serviceWorker.getRegistrations().then(function(registrations) {
registrations.map(r => {
r.unregister()
})
})
window.location.reload(true)
}
console.log('Removing old cache.', cacheName);
return caches.delete(cacheName);
})
);
})
);
});
This way you just have to increase the version number and updating is done by the serviceworker automatically.

Why is Spotify iOS SDK hanging indefinitely on SPTAudioStreamingController.login()?

Following is the code snippet that is hanging:
DispatchQueue.main.async {
log.info("User is a premium user. Logging into player.")
self.player?.login(withAccessToken: self.session!.accessToken)
log.info("Logged into player.")
}
A few notes:
The user is logged in with a premium user account, and a valid oauth token.
In a previous codebase, this worked.
It's running on main.async because in a previous codebase where this worked, I was running on that DispatchQueue.
Running it on the same thread, without the async {} doesn't work either.
Creating a new DispatchQueue, running it on the queue as async, also doesn't work.
According to the debugger, it's hanging on the subcall SPTAudioStreamingController.dispatchToAudioThread.
Any help, or even just long-shot ideas on what could be causing this would be greatly appreciated.
I believe you are missing a call before login that is important. You need to first call the start(withClientId: ) method.
do {
try self.player?.start(withClientId: clientID)
} catch {
log("Failed to start with clientId")
}
In the documentation, calling the start method:
"Start the SPAudioStreamingController thread with the default
audioController."
Which explains why it would hang on the dispatchToAudioThread

error using Notification API on Dart

I've used Notifications working on a JavaScript app and It's very useful when you don't have to be all the time looking at the app when something important needs to be acknowledged. I tried to replicate some work on Dart but a reference error is shown on compiled to JS Chrome.
Do you know if It's going to be implemented for Chrome soon? or is It going to remain experimental?
Thanks in advance
This is the function which tries to call Notification API. Without Notification line, everything works, when I add Notification line I get this error "Uncaught ReferenceError: requestPermission is not defined" running the code as JavaScript. (I am importing 'dart:html')
void revisarInput() {
if ( valorLogin != '' ) {
indicador = true;
_ws.send( Util.formatearJsonSocket( 'loginPwd', { 'pwd': int.parse( valorLogin )}));
}
Notification.requestPermission();
}
This was a bug in dart2js, https://code.google.com/p/dart/issues/detail?id=22483 and is fixed for Dart 1.9.
This page says
https://developer.chrome.com/apps/notifications
Stable since Chrome 28

Resources